在构建时让Typescript编译器添加文件扩展名.js

问题描述

在我正在处理的打字稿项目中,该项目在节点和浏览器中运行(使用html和package.json中的type = 'module)。但是,它不希望以.js扩展名结尾加载文件,而Typescript会生成如下所示的文件

import {foo,bar} from 'threeLetterWords';

此导入在节点和浏览器中均失败,因为它需要找到“ threeLetterWords.js”。如何使TSC自动将这些.js扩展名添加到导入的末尾?

我的`tsconfig.json':

{
  "compilerOptions": {
    "outDir": "./Build","target": "ES6",}
}

还有我的文件结构:

root  
  |___Build  
  |     |__(the root directory except for the build folder)  
  |  
  |__Public  
  |    |__scripts
  |    |     |__main.js  
  |    |     |__threeLetterWords.js  
  |    |__index.html
  |
  |__Server Logic
  |     |__threeLetterWordsServer.js
  |
  |__app.js
  |__package.json
  |__tsconfig.json

我见过hashes,但是这个问题是3年前问的,而且vscode自动导入是无扩展名的,所以我必须手动更改很多(100 +)。

是否取得了任何进展,如果可以,该如何解决

解决方法

threeLetterWords.jsthreeLetterWords是两个不同的模块。字符串.js在模块URI中绝对没有任何魔术含义。

如果要使用模块threeLetterWords,则必须告诉TypeScript使用模块threeLetterWords。如果要使用模块threeLetterWords.js,则必须告诉TypeScript使用模块threeLetterWords.js

TypeScript永远不会更改您告诉它使用的模块名称。我有一个依赖的项目,它不会更改模块名称,因为我正在使用Node模块加载器将模块解析为本地扩展,CommonJS模块或JSON模块。