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

标签 typescript commonjs

我有一个大型 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/

相关文章:

typescript - 为什么编译器隐式类型转换不适用于作为扩展接口(interface)实现的文字类型属性?

node.js - Webpack 找不到实际存在的模块

javascript - 管理 Web 应用程序中全局需要的服务

javascript - Titanium 项目的正确 CommonJS 结构是什么?

typescript - 当在对象中保留注释时,代码以一种奇怪的方式编译

typescript - 在 TypeScript 中的泛型类上调用静态函数

angular - Angular 2中服务和模型之间的区别?

typescript 联合类型具有误导性

javascript - 使用导入/导出默认语法从存储库导入文件时 Jest 失败

javascript - 将需要 CommonJS 功能的 JavaScript 编译为 native Java