简体   繁体   中英

SyntaxError: Cannot use import statement outside a module in NodeJS Typescript

I am trying to write tests with Jest in my Express Typescript application. In the test files, when I am import functions from another file, I get SyntaxError: Cannot use import statement outside a module . This is my 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-

{
  "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-

import { add1 } from "../functions/add"

it('simple test',()=>{
    expect(add1(2,3).toBe(5);
})

add.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. Adding "type":"module" as shown in many solutions did not work.

This is because your code is being compiled to CommonJS as seen in your tsconfig. Changing the module field to ESNext should fix the issue.

Read more about ES modules here: https://www.typescriptlang.org/docs/handbook/esm-node.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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