Typescript编译器正在忘记为ES6模块导入添加文件扩展名? [英] Typescript compiler is forgetting to add file extensions to ES6 module imports?

查看:206
本文介绍了Typescript编译器正在忘记为ES6模块导入添加文件扩展名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Typescript项目编译为具有ES6模块分辨率的JS,但似乎有些不对.

I am trying to compile a Typescript project to JS with ES6 module resolution, but something seems not right.

我的 tsconfig.json 看起来像这样:

{
    "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" -Attribute:

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(在about:config中设置了dom.moduleScripts.enabled)和Chrome Canary(设置了实验性网络平台"标志)进行测试时.在两种情况下均不起作用.

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';语句转换为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.

我做错什么了吗?还是打字稿"module": "es6"设置不能正常工作? 是否可以通过将.js文件扩展名添加到生成的导入语句中的方式来配置tsc?

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中的错误.

This is a bug in TypeScript.

短期内,您可以通过指定输出文件来解决它:

In the short term you can work around it by specifying the output file:

指定.js扩展名和路径:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆