简体   繁体   中英

TypeScript doesn't understand "import" from library in Node.js. Get SyntaxError: Unexpected identifier?

I'm using the nanoid library in Node.js, but I'm writing my backend in TypeScript.

When I try to compile my TypeScript, I get:

/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)

This is the piece of code that causes it:

import { customAlphabet } from "nanoid/async";

I figured it would just naturally work?

My tsconfig.json looks like this:

{
  "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/*"]
    }
  }
}

My node version is v12.10.0 and my typescript version is v3.7.4 .

Shouldn't that line be either import { crypto } from 'crypto' or import * as crypto from 'crypto' ?

try this import * as crypto from 'crypto'

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