ai / nanoid

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript

Home Page:https://zelark.github.io/nano-id-cc/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can't use nanoid@4 with typescript

paulsmithkc opened this issue · comments

nanoid@4 fails to import when used with typescript due to problems in import/require detection.

Example code:

import { nanoid } from 'nanoid';
console.log(nanoid());

Typescript config:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "strict": true,
    "outDir": "dist",
    "typeRoots": ["node_modules/@types", "typings"],
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "useUnknownInCatchVariables": false
  },
  "exclude": ["node_modules", "__mocks__", "tests"]
}

Runtime Error:

[1]     ***/node_modules/nanoid/index.js:1
[1]     ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { randomFillSync } from 'crypto'
[1]                                                                                       ^^^^^^
[1] 
[1]     SyntaxError: Cannot use import statement outside a module

Nano ID 4 works only with ESM projects (TS must compile code to JS code with import too).

For CJS projects you need to use Nano ID 3 (we still support it).