Typescript 编译器忘记向 ES6 模块导入添加文件扩展名? [英] Typescript compiler is forgetting to add file extensions to ES6 module imports?
问题描述
我正在尝试使用 ES6 模块解析将 Typescript 项目编译为 JS,但似乎有些不对.
I am trying to compile a Typescript project to JS with ES6 module resolution, but something seems not right.
我的 tsconfig.json 看起来像这样:
My tsconfig.json looks like this:
{
"compilerOptions": {
"module": "es6",
"target": "es6",
"sourceMap": true,
"lib": ["es6"]
}
}
我用两个模块构建了一个简单的测试用例.第一个模块 (module1.ts) 只是导出一个常量:
I build a simple test case with just two modules. The first module (module1.ts) just exports a constant:
export const testText = "It works!";
第二个模块 (main.ts) 只是从第一个模块导入导出:
The second module (main.ts) just imports the export from the first module:
import { testText } from 'module1';
alert(testText);
第二个模块 (main.js) 的输出文件包含在我的 index.html 中,带有 type="module"
-属性:
The output file of the second module (main.js) is included in my index.html with the type="module"
-Attribute:
<script src="main.js" type="module"></script>
当我使用 Firefox(dom.moduleScripts.enabled
在 about:config 中设置)和 Chrome Canary(设置了实验性 Web 平台标志)进行测试时.在这两种情况下它都不起作用.
When I test this with either Firefox (dom.moduleScripts.enabled
is set in about:config) and Chrome Canary (Experimental Web Platform flag is set). In both cases it doesn't work.
Typescript 编译器似乎将 TS import { testText } from 'module1';
-statement 转换为 JS 语句 import { testText } from 'module1';
.(注:两者完全一样)
The Typescript compiler seems to transpile the TS import { testText } from 'module1';
-statement to the JS statement import { testText } from 'module1';
. (Note: both are exactly the same)
正确的 ES6 导入语句是:import { testText } from 'module1.js';
(注意 .js 文件扩展名)如果我手动将文件扩展名添加到生成的代码中,它会起作用.
The correct ES6 import-statement would be:
import { testText } from 'module1.js';
(Note the .js file extension)
If I manually add the file extension to the generated code, it works.
我做错了什么还是 Typescript "module": "es6"
设置无法正常工作?有没有办法配置 tsc,将 .js 文件扩展名添加到生成的导入语句中?
Did I do something wrong or does the Typescript "module": "es6"
setting just not work correctly?
Is there a way to configure the tsc in such a way that .js file extensions are added to the generated import statements?
推荐答案
这是一个 TypeScript 中的错误.
在短期内,您可以通过指定输出文件来解决这个问题:
In the short term you can work around it by specifying the output file:
在main.ts
中指定.js
扩展名和路径:
in main.ts
specify the .js
extension and path:
import { testText } from './module1.js';
alert(testText);
这将正确选择 module.ts
,但输出包含 .js
扩展名.
This will pick up module.ts
correctly, but output with the .js
extension included.
请注意,您还需要使用 ./
作为本地文件的前缀,因为裸"模块名称是为将来使用而保留的.
Note that you also need to prefix local files with ./
as 'bare' module names are reserved for future use.
这篇关于Typescript 编译器忘记向 ES6 模块导入添加文件扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!