Svelte:无法识别导入的TypeScript文件



我正试图使用Rollup用Svelte和TypeScript构建一个应用程序,当我试图构建Svelte组件时,我似乎无法让它编译.svelte组件中包含的.ts文件。

我一直收到这个错误:

[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
src/ui/pages/files-page/utils/mapPaths.ts (1:12)
1: import type { PathMapping } from '~/types/path.d';
^

这是我的FilesPage.svelte,其中包括mapPaths.ts文件:

<script lang="ts">
import FileList from '~/ui/layouts/file-list/FileList.svelte';
import mapPaths from './utils/mapPaths';
export let paths: string[] = [];
$: mappedPaths = mapPaths(paths);
</script>
<FileList paths={mappedPaths} />

和我的mapPaths.ts文件:

import type { PathMapping } from '~/types/path.d';
export default (paths: string[]): PathMapping => {
const mapping = paths.reduce(
(m, path) => {
const root = path.replace(/_d+$/, '');
m.set(root, (m.get(root) || 0) + 1);
return m;
},
new Map() as Map<string, number>
);
return Array.from(mapping.entries());
};

这是我的rollup.config.js:

import typescript from '@rollup/plugin-typescript';
import nodeResolve from '@rollup/plugin-node-resolve';
import alias from '@rollup/plugin-alias';
import commonjs from 'rollup-plugin-commonjs';
import svelte from 'rollup-plugin-svelte';
import sveltePreprocess from 'svelte-preprocess';
export default {
input: 'src/web.ts',
output: {
sourcemap: false,
format: 'iife',
name: 'app',
file: 'build/web.js'
},
plugins: [
svelte({
preprocess: sveltePreprocess(),
emitCss: false
}),
alias({
entries: [
{ find: '~', replacement: 'src' }
]
}),
nodeResolve({
dedupe: ['svelte']
}),
commonjs(),
typescript()
]
};

并且我的tsconfig.json:

{
"extends": "@tsconfig/svelte/tsconfig.json",
"include": [
"src/**/*"
],
"exclude": [
"node_modules/*"
],
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"module": "es2020",
"moduleResolution": "node",
"baseUrl": ".",
"paths": {
"~/*": [
"src/*"
]
}
}
}

我一直在摆弄插件的顺序,但没有用。它们应该按照我所理解的推荐顺序(除了alias(。

任何帮助都非常感谢,因为我的构建拒绝工作,有点疯狂。

我遇到了同样的问题。这似乎是一个复杂的错误,但以下是为我解决它的方法

现在的快速修复方法是手动将rootDir编译器选项设置为"src";。

所以我在rollup.config.js中的typescript插件中的ts编译器选项中添加了这个标志(当然,我的源目录也叫src,你可以更改它以适应你的目录结构(:

plugins: [
...
typescript({
...
rootDir: './src',
}),
...
],

不幸的是,我不能保证它对你也有效,因为这是一个快速的解决方案。如果更新也是一种选择,那么这个问题似乎在较新版本的typescript中得到了解决。

最新更新