![](/img/trans.png)
[英]VSCode debugging NodeJs project in TypeScript with modules - SyntaxError: Cannot use import statement outside a module
[英]SyntaxError: Cannot use import statement outside a module in NodeJS Typescript
我正在尝试在我的 Express Typescript 应用程序中使用 Jest 编写测试。 在测试文件中,当我从另一个文件导入函数时,我得到SyntaxError: Cannot use import statement outside a module
。 这是我的 package.json-
{
"name": "customer-cart-service",
"version": "1.0.0",
"description": "",
"main": "handler.js",
"type": "module",
"scripts": {
"test": "jest --verbose ./tests"
},
"dependencies": {
"cookie-parser": "^1.4.6",
"express": "^4.17.1",
"serverless-http": "^2.7.0"
},
"devDependencies": {
"@aws-sdk/client-dynamodb": "^3.209.0",
"@aws-sdk/lib-dynamodb": "^3.209.0",
"@types/aws-lambda": "^8.10.108",
"@types/cookie-parser": "^1.4.3",
"@types/express": "^4.17.14",
"@types/jest": "^29.2.4",
"jest": "^26.6.3",
"serverless-bundle": "^5.5.0",
"serverless-dynamodb-local": "^0.2.40",
"serverless-offline": "^11.2.3",
"typescript": "^4.8.4"
}
}
这是我的 tsconfig.json-
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"baseUrl": "./",
"paths": {
"*": [
"node_modules/*",
"src/@types/*"
]
},
"outDir": "./dist",
"removeComments": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noImplicitReturns": true,
"skipLibCheck": true
}
}
添加.ts-
import { add1 } from "../functions/add"
it('simple test',()=>{
expect(add1(2,3).toBe(5);
})
添加.ts-
export function add1(a:number,b:number) {
return a+b;
}
无论我尝试什么,我都无法解决这个错误 - SyntaxError: Cannot use import statement outside a module。 如许多解决方案所示,添加 "type":"module" 无效。
这是因为您的代码正在被编译为 CommonJS,如您在 tsconfig.xml 中所见。 将module
字段更改为ESNext
应该可以解决此问题。
在此处阅读有关 ES 模块的更多信息: https://www.typescriptlang.org/docs/handbook/esm-node.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.