无法导入TypeScript模块而不提供文件扩展名

19

我在TypeScript方面非常新手,希望能够导入我的TS文件而不需要指定它们是TS文件。

我必须做的事情

import {sealed} from "./decorators/decorators.ts";

我认为正确的方式是这样,而不是我想要的方式

import {sealed} from "./decorators/decorators";

这导致错误指出它只在寻找以 .js 或 .jsx 结尾的文件。

我的 tsconfig.json 看起来像这样

{
"compileOnSave": true,
"compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "jsx": "react",
    "allowJs": true,
    "target": "es6",
    "removeComments": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
},
"exclude": [
    "node_modules",
    "typings/browser",
    "typings/browser.d.ts"
]

}


我看到你正在将模块编译成CommonJS模块。你使用什么来加载它们?Webpack吗?还是这是一个Node应用程序? - thitemple
我正在使用Webpack。 - Steve Silvestri
2个回答

19

如果您正在使用webpack,请尝试将以下内容添加到您的webpack.config.js文件中:

resolve: {
  extensions: ['', '.js', '.jsx', '.ts', '.tsx']
},

1
噢,那绝对是它。谢谢! - Steve Silvestri

7

来自thitemple的答案对我有用,但我需要从数组中删除'',因为它会阻止webpack启动。

resolve: {
  extensions: ['.js', '.jsx', '.ts', '.tsx']
},

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接