【发布时间】:2020-02-04 18:06:07
【问题描述】:
我收到此错误:
D:\nginx\ibdrweb\webapps\ibdr-document-2\doc-app\sources\forms\dynamic-form\lus\lus.js:1
import { Tools } from "@ShareUtils/tools";
^
SyntaxError: Unexpected token {
at Module._compile (internal/modules/cjs/loader.js:721:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
当我尝试执行以下命令时:
ts-mocha -p doc-app/tests/tsconfig.json doc-app/tests/lus-tests.ts
此问题已在此处https://github.com/Microsoft/TypeScript/issues/26018 讨论并已关闭。 尝试在 tsconfig.json 更改 "module": "commonjs" 没有帮助。 很多人写道问题仍然存在。
我的项目是这样的
|- doc-app
| |- < many direcotiries used at tests.ts >
| |- tests
| lus-tests.ts
| tsconfig.json
|
|- node_modules
|- tsconfig.json
注意:节点“v10.16.0”
tsconfig.json 在测试目录
{
"compilerOptions": {
"target": "es5",
"declaration": true,
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false,
"suppressImplicitAnyIndexErrors": true,
"lib": ["es6", "dom"],
"typeRoots": [
"node_modules/@types"
]
},
"awesomeTypescriptLoaderOptions": {
"useWebpackText": true,
"useTranspileModule": true,
"doTypeCheck": true,
"forkChecker": true
},
"include": [
"./"
],
"exclude": [
"node_modules"
]
}
package.json 的有用部分
"devDependencies": {
"@types/chai": "4.1.7",
"@types/mocha": "5.2.7",
"@types/sinon": "7.0.13",
...
"chai": "4.2.0",
...
"mocha": "6.1.4",
...
"sinon": "7.3.2",
...
"ts-mocha": "6.0.0",
"ts-node": "8.4.1",
"typescript": "2.9.2", //if change it to "3.6.3" it dosen't help
}
如果我在 tsconfig.json 中指定“模块”:“exnext”,那么错误是
D:\nginx\ibdrweb\webapps\ibdr-document-2\doc-app\tests\lus-tests.ts:1
import "mocha";
^^^^^^^
SyntaxError: Unexpected string
at Module._compile (internal/modules/cjs/loader.js:721:23)
注意: import { Tools } from "@ShareUtils/tools"; node_modules 中的模块“工具”
【问题讨论】:
-
如果测试没有导入模块(这又依赖于 node_modules 中的其他模块),那么它运行没有错误。一旦出现指向 node_modules 的依赖项,就会生成“意外令牌”错误。问题是如何正确运行用 typescript 编写的单元测试,其中有来自 node_modules 的依赖项?
标签: javascript node.js typescript unit-testing mocha.js