在Svelte组件中导入Typescript模块

时间:2020-04-25 14:53:44

标签: svelte svelte-3

我已设置svelte-preprocess,所以我可以成功完成此操作:

<script lang="typescript">
    let someConstant:string = "some constant";
    console.log({someConstant});
</script>

那行得通。但是我不知道如何将这个常数外在化。如果我尝试:

<script lang="typescript">
    import {someConstant} from './SomeTypescript.ts'
    console.log({someConstant});
</script>    

我收到此错误消息:

error TS2691: An import path cannot end with a '.ts' extension. Consider importing './SomeTypescript' instead.

当我将其更改为

<script lang="typescript">
    import {someConstant} from './SomeTypescript'
    console.log({someConstant});
</script>

我收到此错误:

Error: Could not resolve './SomeTypescript' from src/tom/ManageAirtableModels.svelte

什么是正确的方法?

1 个答案:

答案 0 :(得分:1)

为打字稿安装汇总插件以处理非标准文件:

yarn add -D @rollup/plugin-typescript typescript tslib

plugin-typescript添加到plugins中的rollup.config.js列表中:

//....
import autoProcess from 'svelte-preprocess'
import typescript from '@rollup/plugin-typescript'

export default {
  ...
  plugins: [
    typescript(),

    svelte({
      preprocess: autoProcess(),
      ...
    })
    ...
  ]
}

现在import不需要扩展名.ts

<script lang="typescript">
    import {someConstant} from './SomeTypescript'
    console.log({someConstant});
</script>