首页 > 解决方案 > PKI.JS:不能在模块外使用 import 语句(TypeScript)

问题描述

我搜索了这个错误并找到了几十个答案,但没有一个对我有用。我正在使用带有 node.js (v12.22.7) 和 typescript (v4.2.4) 的无服务器框架编写微服务

到目前为止一切正常,直到我尝试将PKIJS添加为依赖项

我的代码片段:

/// <reference types="@types/pkijs" />
import OCSPResponse from "pkijs/src/OCSPResponse";

const ocspRespSimpl = new OCSPResponse({ schema: asn1.result });

因 SyntaxError失败:无法在模块外使用 import 语句

我的 tsconfig.json

{
  "$schema": "https://json.schemastore.org/tsconfig",
  "display": "Node 12",
  "compilerOptions": {
    "outDir": "./dist",
    "incremental": true,
    "target": "ES2019",
    "module": "commonjs",
    "lib": [
      "ES2019"
    ],
    "declaration": true,
    "sourceMap": true,
    "composite": false,
    "removeComments": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictBindCallApply": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "moduleResolution": "node",
    "types": [
      "node"
    ],
    "esModuleInterop": true,
    "skipLibCheck": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "__tests__/**/*"]
}

我的 package.json

{
  "name": "@services/admin-apis",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "clean": "rimraf ./dist ./.serverless",
    "lint": "eslint -c ../../../.eslintrc.js --fix ./src/**/*.ts",
    "prebuild": "yarn lint",
    "build": "tsc -b",
    "package": "sls package",
    "deploy": "sls deploy",
    "test": "jest -c ../../../jest.config.js --rootDir . --passWithNoTests --colors --silent"
  },
  "devDependencies": {
    "@types/pkijs": "^0.0.12",
  },
  "dependencies": {
    "@peculiar/x509": "^1.6.0",
    "@peculiar/webcrypto": "^1.2.2",
    "@peculiar/asn1-ocsp": "^2.0.38",
    "pkijs": "^2.2.1",
  }
}

显然,我无法修改 PKIJS,我该如何制作它以便我可以使用该依赖项?我已经尝试添加"type": "module"到 package.json 但它没有工作,还尝试了 tsconfig 中目标模块的几种组合,也没有工作。

标签: node.jstypescriptnode-modules

解决方案


推荐阅读