![](/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.