我使用此样板启动了一个新的打字稿项目:https://github.com/jsynowiec/node-typescript-boilerplate
有些代码通过
npm run build && npm start
可以正常工作,但通过 npm test
则不行。
设置代码
git clone https://github.com/jsynowiec/node-typescript-boilerplate.git
cd node-typescript-boilerplate
npm install
然后添加到 main.ts 的底部
console.log(await greeter('Bob'));
然后运行:
npm run build && npm start
npm test
注意
start
工作正常,但 test
输出此错误:
FAIL __tests__/main.test.ts
● Test suite failed to run
src/main.ts:36:13 - error TS1378: Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', 'nodenext', or 'preserve', and the 'target' option is set to 'es2017' or higher.
console.log(await greeter('Bob'));
将行交换到 main.ts 的底部
import path from 'path';
async function init() {
console.log(path.basename('test/path/filename.json'));
console.log(await greeter('Bob'));
}
init();
然后运行:
npm run build && npm start
npm test
注意
start
工作正常,但 test
输出此错误:
RUNS __tests__/main.test.ts
/node-typescript-boilerplate/src/main.ts:497
console.log(path_1.default.basename('test/path/filename.json'));
TypeError: Cannot read properties of undefined (reading 'basename')
为什么此代码通过
start
运行良好,而不是通过 test
?
我怀疑 ts-jest
的配置方式与 tsconfig
的工作方式不同。
但我无法找出使它们相互兼容的正确配置。
我也在这里向样板存储库作者提出了一个问题: https://github.com/jsynowiec/node-typescript-boilerplate/issues/59
通过将此行添加到
tsconfig.json
来修复节点模块导入:
"esModuleInterop": true
对于顶级异步等待,您需要使用特殊的配置组合:
或者从 ts-jest 切换到 vitest,它首先构建为 ESM,并带有顶级等待: https://vitest.dev/guide/features.html