【问题标题】:Can TypeScript import both ESM and CJS dependencies?TypeScript 可以同时导入 ESM 和 CJS 依赖项吗?
【发布时间】:2022-11-12 08:12:30
【问题描述】:

我正在编写一个使用 NPM 安装的依赖项的 TypeScript 应用程序:

  • 其中一些依赖项通过 CJS 导出
  • 其中一些依赖项通过 ESM 导出

是否有tsconfig.json 配置可以让我透明地使用所有这些依赖项?

【问题讨论】:

  • 我会将您的 tsconfig module 设置为 esm 变体,因为 esm 可以 import any commonjs dep。如果您的一个 cjs 部门尝试 require 一个(传递的)esm 部门,您会遇到问题。请参阅compatibility 注释。
  • 您需要哪些依赖项,以便我们可以尝试自己进行配置?
  • @caTS我不明白它会有什么不同? NPM 充满了 CJS 和 ESM 依赖项,它们中的任何一个都适用于此。
  • 坦率地说,我不知道任何 CJS 包。而且我不知道是否有办法在不查看源代码或尝试使用它的情况下确定这一点。如果你能举个例子,对我和其他人来说会很方便。

标签: typescript es6-modules commonjs


【解决方案1】:

是的,它可以!

例如,这是一个带有 ESM dependency (chalk)common.js dependency (aes-js) 的新 ES 模块项目:

package.json:

{
  "type": "module",
  "private": true,
  "scripts": {
    "build": "tsc",
    "start": "yarn build && node dist/index.js"
  },
  "license": "ISC",
  "devDependencies": {
    "@types/aes-js": "^3.1.1",
    "typescript": "^4.8.4"
  },
  "dependencies": {
    "aes-js": "^3.1.2",
    "chalk": "^5.1.2"
  }
}

index.ts:

import chalk from "chalk"
import aesjs from "aes-js"

console.log(chalk.blue(aesjs.utils.utf8.toBytes("this is a string")))

tsconfig.json

{
  "compilerOptions": {
    "target": "es2022",
    "module": "es2022",
    "esModuleInterop": true,
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "outDir": "dist"
  }
}

解释:esModuleInterop 是你的朋友。它确保module.exports = 变成默认导出(CommonJS -> ES6),反之亦然,确保默认导出与module.exports =(ES6 -> CommonJS)相同

【讨论】:

    猜你喜欢
    • 2012-03-07
    • 1970-01-01
    • 2013-07-27
    • 2014-11-15
    • 2023-04-08
    • 2018-01-31
    • 2022-12-07
    • 2021-02-27
    • 1970-01-01
    相关资源
    最近更新 更多