npm build error with svelte: Plugin typescript: #rollup/plugin-typescript TS2307: Cannot find module 'X' or its corresponding type declarations - npm

I am trying to build a component library with svelte. I tried to build it with:
npm build
I got the error message:
Plugin typescript: #rollup/plugin-typescript TS2307: Cannot find module './components/MyComponent.svelte' or its corresponding type declarations.
The components I want to export are in the index.tsx:
export { default as MyComponent } from "./components/MyComponent.svelte";
My tsconfig:
{
"extends": "#tsconfig/svelte/tsconfig.json",
"include": ["src/**/*"],
"exclude": ["node_modules/*", "__sapper__/*", "public/*"],
"compilerOptions": {
"target": "es2016",
"module": "esnext",
"outDir": "dist",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"declaration": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"importsNotUsedAsValues": "remove"
}
My rollup.config.js:
import svelte from 'rollup-plugin-svelte';
import resolve from 'rollup-plugin-node-resolve';
import postcss from 'rollup-plugin-postcss';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import json from '#rollup/plugin-json';
import autoPreprocess from 'svelte-preprocess';
import typescript from '#rollup/plugin-typescript';
import nodeResolve from '#rollup/plugin-node-resolve';
const pkg = require('./package.json');
export default {
input: 'src/index.tsx',
output: [
{
file: pkg.main,
format: 'cjs',
sourcemap: false,
},
{
file: pkg.module,
format: 'esm',
sourcemap: false,
},
],
plugins: [
json({ compact: true }),
svelte({
preprocess: autoPreprocess(),
}),
resolve(),
nodeResolve(),
typescript({ sourceMap: true, rootDir: './src' }),
peerDepsExternal(),
postcss({
extensions: ['.css'],
}),
],
};
Does anyone already had such a problem? Thanks in advance!

You may have to add a type declaration like this:
import type { SvelteComponentTyped } from 'svelte';
declare module '*.svelte' {
export default SvelteComponentTyped;
}
The svelte package also provides something like this via svelte/types/runtime/ambient.d.ts, though it may not be visible to tsc depending on configuration.
Maybe you could also include this file somehow via the tsconfig.json.

Related

Why are absolute imports not working in my react-native expo project?

An example of the imports follows:
import { useAppDispatch, useAppSelector } from '~/redux/hooks'
import * as walletActions from '~/redux/wallet/actions'
import { actions, selectState as selectWalletState } from '~/redux/wallet/slice'
import { multichain } from '~/services/multichain'
import { config } from '~/settings/config'
In my tsconfig.json...
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~/*":["./src/*"]
},
...
This all compiles, and typescript understands my imports; I can click around them in VSCode.
However, when I open the app in Expo, I get the error
Unable to resolve module ~/redux/hooks from ... ~/redux/hooks could not be found within the project or in these directories:
node_modules
Here is my babel.config.js
module.exports = function (api) {
api.cache(true)
return {
presets: ['babel-preset-expo'],
plugins: [
['react-native-reanimated/plugin'],
[
'module:react-native-dotenv',
{
envName: 'APP_ENV',
moduleName: '#env',
path: '.env',
},
],
[
'module-resolver',
{
alias: {
'~/': './src/',
},
},
],
],
}
}

Unexpected token Import after running npm update

I ran npm update on a large codebase recently, and now vite is having some issues compiling my SFC files.
> bedgg-frontend#0.0.0 dev
> vite
vite v2.9.14 dev server running at:
> Local: http://localhost:3000/
> Network: use `--host` to expose
ready in 208ms.
Unexpected token (1:30)
Unexpected token (1:30) (x2)
12:14:28 PM [vite] Internal server error: Unexpected token (1:30)
Plugin: vite:vue
File: /home/ben/projects/bed.gg-frontend/src/views/Profile.vue
1 | <script setup lang="ts">
2 | import SkinViewer from "#/components/Player/SkinViewer.vue";
| ^
3 | import LineChart from "#/components/Charts/LineChart.vue";
4 | import PlayerStats from "#/components/Stats/Cards/PlayerStats.vue";
at instantiate (/home/ben/projects/bed.gg-frontend/node_modules/#babel/parser/lib/index.js:72:32)
at constructor (/home/ben/projects/bed.gg-frontend/node_modules/#babel/parser/lib/index.js:359:12)
at Object.raise (/home/ben/projects/bed.gg-frontend/node_modules/#babel/parser/lib/index.js:3339:19)
at Object.unexpected (/home/ben/projects/bed.gg-frontend/node_modules/#babel/parser/lib/index.js:3377:16)
at Object.getExpression (/home/ben/projects/bed.gg-frontend/node_modules/#babel/parser/lib/index.js:12232:12)
at Object.getExpression (/home/ben/projects/bed.gg-frontend/node_modules/#babel/parser/lib/index.js:11162:18)
at Object.parseExpression (/home/ben/projects/bed.gg-frontend/node_modules/#babel/parser/lib/index.js:16618:17)
at processExp (/home/ben/projects/bed.gg-frontend/node_modules/#vue/compiler-sfc/dist/compiler-sfc.cjs.js:4979:30)
at Array.CompilerDOM.transform.nodeTransforms (/home/ben/projects/bed.gg-frontend/node_modules/#vue/compiler-sfc/dist/compiler-sfc.cjs.js:4949:45)
at traverseNode (/home/ben/projects/bed.gg-frontend/node_modules/#vue/compiler-core/dist/compiler-core.cjs.js:2162:41)
to me this seems like a configuration error or some sort of bug with vite.
When I updated I went from v2.9.6 to v2.9.14.
vite config
import { defineConfig } from "vite";
import vue from "#vitejs/plugin-vue";
import { join, resolve } from "path";
export default defineConfig({
mode: "development",
server: {
port: 3000,
},
resolve: {
alias: {
"#": join(__dirname, "./src"),
},
},
plugins: [
vue(),
],
define: { "process.env": {} },
css: {
preprocessorOptions: {
scss: { additionalData: `#use "sass:math";#import "#/styles/_variables.scss";` },
},
},
});
tsconfig:
{
"compilerOptions": {
"target": "esnext",
"useDefineForClassFields": true,
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["esnext", "dom"],
"types": ["vuetify", "node"],
"baseUrl": ".",
"paths": {
"#/*": ["./src/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
}
Any idea why this is happening? I've looked at many Github issues to no avail.

How to process css with postcss inside sapper-template with rollup

Having trouble using rollup-plugin-postcss with sapper-template:
npx degit sveltejs/sapper-template#rollup my-app
npm install rollup-plugin-postcss --save-dev
install various postcss plugin
create src/css/main.css
add import './css/main.css'; to the top line of src/client.js
*edit rollup.config.js
*add postcss.config.js
*going wrong here? I have tried several variations.
// rollup.config.js
...
import postcss from 'rollup-plugin-postcss'
...
export default {
client: {
input: config.client.input(),
output: config.client.output(),
plugins: [
replace({
'process.browser': true,
'process.env.NODE_ENV': JSON.stringify(mode)
}),
svelte({
dev,
hydratable: true,
emitCss: true
}),
resolve(),
commonjs(),
postcss({
// extract: true,
// sourceMap: true,
plugins: [require('autoprefixer')]
}),
...
// postcss.config.js
module.exports = {
plugins: {
...
autoprefixer: {}
}
};
No real error message, once I add postcss to the plugins in the client:{} of rollup.config.js - css breaks on the site.
This is a matter of simply putting the svelte plugin config together properly. I would recommend you use svelte-preprocess and setup your rollup.config.js as follows:
import autoPreprocess from 'svelte-preprocess';
const preprocessOptions = {
postcss: {
plugins: [
require('postcss-import'),
require('postcss-preset-env')({
stage: 0,
browsers: 'last 2 versions',
autoprefixer: { grid: true }
}),
...
]
}
};
...
export default {
client: {
plugins: [
svelte({
preprocess: autoPreprocess(preprocessOptions),
dev,
hydratable: true,
emitCss: true
}),
...
As you see here, you need to set the preprocess option of the svelte plugin.

Using vue and jest to testing svg inline

I have problem with testing view when I use image inline in code
'src/assets/icons/circle-small.svg?inline'
I have versions:
- babel-jest: 23.6.0
- vue: 2.6.10
Configuration:
Vue CLI:
const svgRule = config.module.rule('svg');
svgRule.oneOf('inline').use('vue-svg-loader').loader('vue-svg-loader').end();
Jest config:
moduleFileExtensions: [
'js',
'vue',
],
transform: {
'^.+\\.vue$': 'vue-jest',
'^.+\\.js$': '<rootDir>/babel-jest',
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2|svg)$': 'jest-transform-stub',
},
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1',
},
I import in view:
import Img from '#/assets/icons/img.svg?inline';
I getting configuration error:
Could not locate module #/assets/icons/circle-small.svg?inline mapped as:
/some/src/assets/icons/circle-small.svg?inline.
Please check your configuration for these entries:
{
"moduleNameMapper": {
"/^#\/(.*)$/": "/some/src/$1"
},
"resolver": null
}
I have a problem with configuring tests for the case when I import inline image. Can anyone know what else i should to configure or what library to use?
I found a solution, it was enough to modify regex
this was wrong:
'.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2|svg)$': 'jest-transform-stub',
and this is correct:
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)(\\?inline)?$': 'jest-transform-stub',
First, by using jest moduleNameMapper function, remove ?inline
moduleNameMapper: {
'^.+/(.*\\.svg)\\?inline$': '<rootDir>/path/svg/$1'
},
For my case
import SvgBack from '../../assets/svg/back.svg?inline'
(Convert to) --->
import SvgBack from '../../assets/svg/back.svg'
Second, transform the svg files into vuejs format
transform: {
'^.+\\.svg$': '<rootDir>/svgTransform.js',
},
svgTransform.js can find it in the guide https://github.com/visualfanatic/vue-svg-loader/blob/master/docs/faq.md#how-to-use-this-loader-with-jest
jest.config.js
module.exports = {
collectCoverage: false,
collectCoverageFrom: [
'<rootDir>/components/**/*.vue',
'<rootDir>/pages/*.vue',
],
// tell Jest to handle `*.vue` files
moduleFileExtensions: [ 'js', 'json', 'vue' ],
moduleNameMapper: {
'^.+/(.*\\.svg)\\?inline$': '<rootDir>/assets/svg/$1',
},
modulePaths: [ '<rootDir>' ],
snapshotSerializers: [ '<rootDir>/node_modules/jest-serializer-vue' ],
transform: {
// process `*.vue` files with `vue-jest`
'.*\\.(vue)$': '<rootDir>/node_modules/vue-jest',
// process js with `babel-jest`
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
// process svg with svgTransform.js
'^.+\\.svg$': '<rootDir>/tests/tools/svgTransform.js',
},
watchman: false,
}
know this thread is very old but got here searching for a solution so will anwser as my solution is a bit different from the other ones and for me simple enough to resolve my problem.
vue: 3.0.0
vue-jest: 5.0.0-0
Just added this config to jest.config.js:
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)(\\?inline)?$': '<rootDir>/tests/mocks/fileMock.js'
}
and added the fileMock.js file:
export default 'test-file-stub'
jest now will load that string and stop give error when I import svg as a component.
This resolves only the error, to check some class on the inline svg the test-file-stub needs to step up for some kind of template, really depends if needed.

...mapState SyntaxError in Vue.js, with vuex

when I'm using ...mapState in vue.js, I ran into an error when bundling files with webpack. The error is
Module build failed: SyntaxError: Unexpected token.
I've tried kinds of babel plugins such as stage-0 and transform-object-rest-spread.
Howerver, none seems to be ok for me. Would you please so kind tell me how to solve it?
the source code is
<script type="text/babel">
import { mapState } from 'vuex';
let [a, b, ...other] = [1,2,3,5,7,9]; // this line is ok
console.log(a);
console.log(b);
console.log(other);
export default{
computed:{
localComputed(){
return 10;
},
...mapState({ //this line caused the error
count: state => state.count
})
},
methods: {
increment() {
this.$store.commit('increment');
},
decrement() {
this.$store.commit('decrement');
}
}
}
</script>
and this is the webpack config fragment
{
test: /\.(js|es|es6|jsx)$/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
['react'],
['es2015', {modules: false, loose: true}],
['stage-2']
],
plugins: [
['transform-runtime'],
// https://github.com/JeffreyWay/laravel-mix/issues/76
['transform-object-rest-spread'],
['transform-es2015-destructuring']
],
comments: false,
cacheDirectory: true
}
},
{
loader: 'eslint-loader',
options: {
configFile: eslintConfigPath
}
}
],
exclude: excludeReg
}
I had a similar problem a while ago. As far as I can see, your issue is that your babel-loader does not currently work on .vue files (which is correct as such).
The vue-loader, which handles .vue files, uses babel internally as well, but it won't use webpack's babel-loader config. The easiest way to provide a config for babel in the vue-loader is (unfortunately) creating a separate .babelrc file with your babel config in the root folder of your project:
.babelrc
{
presets: [
["react"],
["es2015", { "modules": false, "loose": true}],
["stage-2"]
],
plugins: [
["transform-runtime"],
["transform-object-rest-spread"],
["transform-es2015-destructuring"]
]
}
Note that .babelrc requires valid JSON.