繁体   English   中英

SyntaxError:无法在 NodeJS Typescript 的模块外使用 import 语句

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM