导入自定义 NPM 库时无法在模块外部使用 import 语句

我有一个自定义模块,我编写并上传到 NPM,它导出一个类


在 AWS-CDK 项目中,我正在安装该依赖项并尝试导入它,但在构建“cdk Synth”期间出现以下错误


Cannot use import statement outside a module

这是来自 NPM 模块的 JSON 包


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

  }

}

然后是使用该库的 CDK 项目:


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

  }

}

已尝试将 type:module 添加到包 JSON 也尝试将其添加到 tsconfig 的 NPM 库


    "target": "ES2017",                         

    "module": "ESNEXT",   


料青山看我应如是
浏览 124回答 1
1回答

慕丝7291255

我相信您希望模块中的“main”:指向“stack.js”而不是“.ts”文件。然后您需要确保在使用该模块之前运行“tsc”。还要添加“types”:“stack.d.ts”。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript