[英]SyntaxError: Cannot use import statement outside a module in NodeJS Typescript
I am trying to write tests with Jest in my Express Typescript application.我正在尝试在我的 Express Typescript 应用程序中使用 Jest 编写测试。 In the test files, when I am import functions from another file, I get
SyntaxError: Cannot use import statement outside a module
.在测试文件中,当我从另一个文件导入函数时,我得到
SyntaxError: Cannot use import statement outside a module
。 This is my package.json-这是我的 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"
}
}
This is my tsconfig.json-这是我的 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
}
}
add.ts-添加.ts-
import { add1 } from "../functions/add"
it('simple test',()=>{
expect(add1(2,3).toBe(5);
})
add.ts-添加.ts-
export function add1(a:number,b:number) {
return a+b;
}
Whatever I try, I am unable to resolve this error- SyntaxError: Cannot use import statement outside a module.无论我尝试什么,我都无法解决这个错误 - SyntaxError: Cannot use import statement outside a module。 Adding "type":"module" as shown in many solutions did not work.
如许多解决方案所示,添加 "type":"module" 无效。
This is because your code is being compiled to CommonJS as seen in your tsconfig.这是因为您的代码正在被编译为 CommonJS,如您在 tsconfig.xml 中所见。 Changing the
module
field to ESNext
should fix the issue.将
module
字段更改为ESNext
应该可以解决此问题。
Read more about ES modules here: https://www.typescriptlang.org/docs/handbook/esm-node.html在此处阅读有关 ES 模块的更多信息: https://www.typescriptlang.org/docs/handbook/esm-node.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.