Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

javascript - node.js: Unexpected token {

So I have a unit test written for mocha using TypeScript. I am trying to run it using gulp (which doesn't really play a part here). I get the following exception:

(function (exports, require, module, __filename, __dirname) { import { assert } from 'chai';
                                                                     ^

SyntaxError: Unexpected token {
    at new Script (vm.js:74:7)
    at createScript (vm.js:246:10)
    at Object.runInThisContext (vm.js:298:10)
    at Module._compile (internal/modules/cjs/loader.js:657:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)

Could someone tell me what setting in need in my tsconfig.json to fix problems like these?

node -v 
v10.6.0
tsc -v
Version 2.9.2

and here's my tsconfig.json:

{
    "include" : [
        "src",
        "test",
        "unittest"
    ],
    "compileOnSave": true,
    "compilerOptions": {
        "module": "es2015",
        "moduleResolution": "node",
        "esModuleInterop": true,
        "target": "es5",
        "noImplicitAny": true,
        "declaration": true,
        "sourceMap": true,
        "preserveConstEnums": true,
        "lib": [
            "es2015", "dom"
        ],
        "noUnusedLocals": true,
        "noImplicitReturns": true,
        "noImplicitThis": true,
        "alwaysStrict": true,
        "strictNullChecks": false,
        "noUnusedParameters": false,
        "pretty": true,
        "allowUnreachableCode": false,
        "experimentalDecorators": true,
        "suppressImplicitAnyIndexErrors": true,
        "outDir": "./build"
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Node doesn't fully support import yet or at least not by default, so errors will happen when importing using the import in that way.

When using TypeScript you should use "module": "commonjs" in your compilerOptions, because that is what node.js uses. When compiled, TypeScript will convert all the imports to node supported require's.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...