Cannot use import statement outside a module when importing a custom NPM library

Viewed 1233

I have a custom module that I wrote and uploaded to NPM which exports a class

In an AWS-CDK Project, I am installing that dependency and trying to import it but I get the following error during build "cdk synth"

Cannot use import statement outside a module

Here is package JSON from the NPM module

  "name": "@organization/cdk-organization-fe",
  "version": "1.0.2",
  "description": "Frontend construct for apps",
  "main": "stack.ts",
  "publishConfig": {
    "access": "restricted"
  },
  "type":"module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "tsc": "tsc"
  },
  "author": "me,
  "license": "ISC",
  "dependencies": {
    "@aws-cdk/aws-cloudfront": "^1.73.0",
    "@aws-cdk/aws-s3": "^1.73.0",
    "@aws-cdk/aws-s3-deployment": "^1.73.0",
    "@aws-cdk/aws-certificatemanager": "^1.73.0",
    "@aws-cdk/aws-logs": "^1.73.0",
    "@aws-cdk/aws-lambda": "^1.73.0",
    "@aws-cdk/aws-iam": "^1.73.0",
    "aws-cdk": "^1.73.0",
    "path": "^0.12.7",
    "typescript": "^4.0.5"
  }
}

and then the CDK project using the library:

  "name": "showtix_fe",
  "version": "0.1.0",
  "bin": {
    "showtix_fe": "bin/showtix_fe.js"
  },
  "type": "module",
  "scripts": {
    "build": "tsc",
    "watch": "tsc -w",
    "test": "jest",
    "cdk": "cdk"
  },
  "devDependencies": {
    "@aws-cdk/assert": "1.73.0",
    "@types/jest": "^24.0.22",
    "@types/node": "10.17.5",
    "jest": "^24.9.0",
    "ts-jest": "^24.1.0",
    "aws-cdk": "^1.73.0",
    "ts-node": "^8.1.0",
    "typescript": "~3.7.2"
  },
  "dependencies": {
    "@aws-cdk/core": "^1.73.0",
    "@organization/cdk-organization-fe": "^1.0.2",
    "source-map-support": "^0.5.16"
  }
}

have tried adding type:module to the package JSON also have tried adding this to the NPM library for the tsconfig

    "target": "ES2017",                         
    "module": "ESNEXT",   
1 Answers

I believe you want your "main": in the module to point to "stack.js" not the ".ts" file. Then you need to make sure to run 'tsc' before using the module. Also add "types": "stack.d.ts" too.

Related