我有一个大型 JavaScript 代码库,我想慢慢过渡到 TypeScript。它目前使用 CommonJS 格式设置,在一个完美的世界中,我希望能够一次将一个 .js
文件更改为 .ts
。
我的 tsconfig.json
看起来像这样:
{
"compilerOptions": {
"allowJs": true,
"checkJs": false,
"target": "es5",
"module": "commonjs",
"noEmit": true,
"strict": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"types": [
"node"
],
},
"exclude": [
"node_modules"
]
}
我修改了我的启动脚本以使用 ts-node -P tsconfig.json
。这似乎一切正常。
我的问题在于将 TS 导入 JS。 正如我提到的,它目前是使用 CommonJS 设置的,所以 module.exports
和 require
.例如,file-a.js
需要 file-b.js
:
// file-a.js
const { exampleB } = require('../file-b');
// file-b.js
function exampleB() {
return "Hello World";
}
module.exports = {
exampleB,
};
当我将 file-b.js
更改为 .ts
时,解决了所有基本类型检查问题,然后启动命令,我得到了异常 错误:找不到来自
。file-a.js
的模块“../file-b”
我假设这是 Typescript 无法解析我的 CommonJS 格式。我是否可以将 TypeScript 配置为使用这种格式,并允许我在慢慢过渡时将 TS 文件导入 JS?
如果有帮助,我什至可以将所有 module.exports = { fn }
更改为 export fn
。
最佳答案
这是我所做的:
- 使用
tsconfig.json
、file-a.js
/(*) 创建了some_folder
,file-b.js
在里面。全部包含您提供的内容。 npm install -D ts-node
npm install -D typescript
npm install -D @types/node
'/home/.../some_folder/node_modules/.bin/ts-node' -P tsconfig.json file-a.js
成功了。- 将
file-b.js
重命名为file-b.ts
- 再次运行
'/home/.../some_folder/node_modules/.bin/ts-node' -P tsconfig.json file-a.js
......它也工作得很好.
因此,要么您需要为您的问题添加更多上下文,以便可以重现您面临的问题,要么开始创建一个"template"Typescript 项目,就像我的项目一样简单'转载。确保它有效,然后才开始从您的原始项目中添加文件。可能在某个地方,您在一个看似无关的地方做了一些更改,只是看不到它。
(*) 在您提出的问题中,您写的是 ../file-b
而不是 ./file-b
。但是为了清楚起见,我跳过了这个细节。但我也尝试将 file-b
放在项目文件夹之外,并尝试将 file-a
放在子文件夹中。一切正常。
关于typescript - 在保持 CommonJS 格式的同时过渡到 TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61259373/