Search code examples
npmbuildcomponentssveltetsconfig

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


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!


Solution

  • 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.