Skip to content
Advertisement

Typescript – write ES6 modules and transpile to Node

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?

Advertisement

Answer

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

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

ref

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement