【问题标题】:TypeScript doesn't understand "import" from library in Node.js. Get SyntaxError: Unexpected identifier?TypeScript 不理解 Node.js 中库的“导入”。获取 SyntaxError:意外的标识符?
【发布时间】:2020-09-23 11:00:20
【问题描述】:

我在 Node.js 中使用 nanoid 库,但我在 TypeScript 中编写后端。

当我尝试编译我的 TypeScript 时,我得到:

/project/node_modules/nanoid/async/index.js:1
import crypto from 'crypto'
       ^^^^^^

SyntaxError: Unexpected identifier
    at Module._compile (internal/modules/cjs/loader.js:872:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
    at Module.load (internal/modules/cjs/loader.js:790:32)
    at Function.Module._load (internal/modules/cjs/loader.js:703:12)
    at Module.require (internal/modules/cjs/loader.js:830:19)
    at require (internal/modules/cjs/helpers.js:68:18)
    at Object.<anonymous> (/project/dist/utils/generateId.js:4:17)
    at Module._compile (internal/modules/cjs/loader.js:936:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
    at Module.load (internal/modules/cjs/loader.js:790:32)

这是导致它的一段代码:

import { customAlphabet } from "nanoid/async";

我认为它自然会起作用?

我的tsconfig.json 看起来像这样:

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "resolveJsonModule": true,
    "paths": {
      "*": ["node_modules/*", "src/*"]
    }
  }
}

我的节点版本是v12.10.0,我的打字稿版本是v3.7.4

【问题讨论】:

  • nanoid的包好像是esm风格的,需要转成cjs
  • @tmhao2005 我想我需要这样的东西,github.com/standard-things/esm,对吧?
  • 我使用了您的 tsconfig.json 并尝试了 customAlphabet 导入,它看起来不错 - codesandbox.io/s/nifty-chebyshev-dr6qo。可能会发布更多代码或创建沙箱
  • @ultimoTG 我不认为codesandbox 增加了很多清晰度,因为这将与网络捆绑器一起使用——它特别是一个与节点相关的问题。尽管如此,我现在想出了一个解决方案,我将发布。
  • 我不知道你为什么运行可以在其中导入 esm 模块的 cjs 代码。看起来nanoid 在他们的 package.json 文件中有一个非常明确的定义 module/main 属性(分别为 esm 和 cjs)

标签: javascript node.js typescript ecmascript-6 ts-node


【解决方案1】:

那条线也不应该是 import { crypto } from 'crypto' 或者 import * as crypto from 'crypto' ?

【讨论】:

  • 不确定是否重要,因为问题在于导入。此外,即使这是一个问题,那也只是一个库问题,因为这个错误发生在我的 node_modules 中。
【解决方案2】:

试试这个import * as crypto from 'crypto'

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 2017-10-11
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    相关资源
    最近更新 更多