Home > Mobile >  Typescript - write ES6 modules and transpile to Node
Typescript - write ES6 modules and transpile to Node

Time:09-21

I use typescript to make NPM module and I write modules like export default xyz; but I'd like TSC to translate it to CommonJS on transpilation.

And I want to keep const and other ES6, just need the exports to be Node...

I've tried many TSCONFIG, as advised in some topics, currently it looks like

{
  "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": []
}

but it still produces JS file with export default xyz instead of module.exports = xyz.

How do I make it work?

CodePudding user response:

Define in your config which module code should be generated by the typescript compiler.

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

ref

CodePudding user response:

I was looking for creating Node16 module from ES6 import/export and I think I just didn't combine it properly.

Thanks to @jonrsharpe, found the option is modules.

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