Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

es6 modules to commonjs with typescript under node harmony flag

I'm using TypeScript (1.6) with node under the --harmony flag, so I'd like to transpile the es6 module syntax to commonjs.

From what I can tell, I can't do this with TypeScript 1.6. If I set my target to es6, and module to commonjs, I get a TypeScript error -

Cannot compile modules into 'commonjs', 'amd', 'system' or 'umd' when targeting 'ES6' or higher.

Why won't TypeScript compile to commonjs with an ES6 target? I imagine a lot people want to do this since node doesn't support ES6 modules yet.

I'd thought the new moduleResolution compiler option might solve this issue, but it doesn't appear to do anything.

Currently, I'm having to use babel just to transpile the module syntax to commonjs, but I'd like to remove babel from my builds so I can take advantage of source maps.

Is there a way I can achieve this? NOTE: I do not want to transpile to ES5. I want my JS running as ES6 under the harmony flag. Thanks!

like image 977
Simon Trewhella Avatar asked Oct 03 '15 07:10

Simon Trewhella


People also ask

How do I use the CommonJS module in ES6 module?

An ES6 Module can load other ES6 modules using import. An ES6 Module can load CommonJS using import. A CommonJS module can load other CommonJS modules using require. A CommonJS module previously COULD NOT load an ES6 Module, but today it can load an ES6 module using the import() function.

Can you use ES6 modules in node?

The syntax for importing modules in ES6 looks like this. The reason for this error is that Node js doesn't support ES6 import directly. If you try to use import for importing modules directly in node js it will throw out that error.

Is CommonJS deprecated?

It is not deprecated.

What is the difference between ES6 and CommonJS?

While CommonJS and ES6 modules share similar syntax, they work in fundamentally different ways: ES6 modules are pre-parsed in order to resolve further imports before code is executed. CommonJS modules load dependencies on demand while executing the code.


1 Answers

The TypeScript team will add support for what you are looking for in the next release. You can wait for a few weeks/months. Alternatively, you can use a Polyfill for the ES6 module loader:

  • es6-module-loader
  • SystemJS

There are more libraries like the ones above available online just check which one does the job for you until official support for --module with --target es6 arrives.

UPDATE

tsconfig.json

{
  "compilerOptions": {
    "target":"ES6",
    "moduleResolution": "classic",
  }
}
  • ES6 support with generators
  • No import stuff transpiling due to "moduleResolution": "classic"
like image 95
Remo H. Jansen Avatar answered Oct 06 '22 18:10

Remo H. Jansen