javascript - 节点.js : Unexpected token {

标签 javascript typescript tsc

所以我有一个使用 TypeScript 为 mocha 编写的单元测试。 我正在尝试使用 gulp 运行它(这在这里并没有真正发挥作用)。 我得到以下异常:

(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)

有人可以告诉我 tsconfig.json 中需要什么设置来解决这些问题吗?

node -v 
v10.6.0
tsc -v
Version 2.9.2

这是我的 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"
    }
}

最佳答案

Node 还不完全支持 import 或者至少默认情况下不支持,因此以这种方式使用 import 导入时会发生错误。

使用 TypeScript 时,您应该在 compilerOptions 中使用 "module": "commonjs",因为 node.js 使用的就是它。编译时,TypeScript 会将所有 imports 转换为节点支持的 require

关于javascript - 节点.js : Unexpected token {,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51564072/

相关文章:

node.js - TypeScript - 使用 <reference path ="....."> 标签

javascript - 存储在变量中的正则表达式在匹配时不起作用

javascript - 如何通过单击显示/隐藏下拉菜单?

javascript - 在链接单击上运行数据库查询并仍然加载链接 URL

javascript - TypeScript + AngularJS : Can't interact with the html generated by ng-bind-html

javascript - TypeScript 中的 friend 类

javascript - Vue 3 推荐的 TypeScript TSConfig compilerOptions TARGET 设置?

typescript - 从 Visual Studio 发布 typescript 时的 8K 命令行限制

node.js - typescript 错误——错误 : Cannot find module 'typescript/tsc.js'

javascript:组合函数和 if 的问题