Node 5.6 Doesn't Understand ES6?

2020-03-08 06:49发布

问题:

Trying both node and node --harmony but I continue to get the 'SyntaxError: Unexpected token import' error.

I have two files, A.ts and B.ts. Here is what they look like-

B.ts

export class B {

}

A.ts

import {B} from './B';

console.log(new B());

Which results in-

(function (exports, require, module, __filename, __dirname) { import {B} from './B';
                                                              ^^^^^^
SyntaxError: Unexpected token import
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:140:18)
    at node.js:1001:3

Why?

回答1:

Modules are still in progress, I'm not sure if trying to throw the flag will fix your error but here's the command:

$ node --v8-options | grep 'in progress'
--harmony_modules (enable "harmony modules" (in progress))


回答2:

Try https://www.npmjs.com/package/ts-node. It allows compiling of typescript a la node.

Also make sure your tsconfig.json is set to compile with commonjs. https://github.com/Microsoft/TypeScript/wiki/tsconfig.json

Here is what my tsconfig.json looks like:

{
  "version": "1.0",
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "removeComments": true,
    "sourceMap": false
  }
}