gpt4 book ai didi

typescript - 在保持 CommonJS 格式的同时过渡到 TypeScript

转载 作者:行者123 更新时间:2023-12-04 10:12:32 24 4
gpt4 key购买 nike

我有一个大型 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.exportsrequire .例如,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

最佳答案

这是我所做的:

  1. 使用 tsconfig.jsonfile-a.js/(*) 创建了 some_folderfile-b.js 在里面。全部包含您提供的内容。
  2. npm install -D ts-node
  3. npm install -D typescript
  4. npm install -D @types/node
  5. '/home/.../some_folder/node_modules/.bin/ts-node' -P tsconfig.json file-a.js 成功了。
  6. file-b.js 重命名为 file-b.ts
  7. 再次运行 '/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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com