簡體   English   中英

Typescript - 編寫 ES6 模塊並轉譯到 Node

[英]Typescript - write ES6 modules and transpile to Node

我使用 typescript 制作 NPM 模塊,我編寫了export default xyz; 但我希望 TSC 在編譯時將其翻譯成 CommonJS。

我想保留const和其他 ES6,只需要導出為 Node ...

我已經嘗試了很多TSCONFIG,正如一些主題中所建議的那樣,目前看起來像

{
  "compilerOptions": {
    "incremental": true,
    "target": "ES6",
    "moduleResolution": "Node",
    "esModuleInterop": true,
    "declaration": true,
    "declarationMap": true,
    "removeComments": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "sourceRoot": "",
    "outDir": "dist"
  },
  "include": [
    "./src/main.ts"
  ],
  "exclude": []
}

但它仍然會生成帶有export default xyz而不是module.exports = xyz的 JS 文件。

我如何使它工作?

在您的配置中定義應該由 typescript 編譯器生成的模塊代碼。

{
  ...
  "module": "CommonJS",
  ...
}

參考

我正在尋找從 ES6 import/export創建 Node16 模塊,我想我只是沒有正確組合它。

感謝@jonrsharpe,發現選項是modules

{
  "compilerOptions": {
    "strict": true,
    "target": "ES6",
    "module": "Node16",
    "declaration": true,
    "declarationMap": true,
    "removeComments": true,
    "forceConsistentCasingInFileNames": true,
    "sourceRoot": "",
    "outDir": "dist"
  },
  "include": [
    "./src/main.ts"
  ],
  "exclude": []
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM