ai / nanoid

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript
https://zelark.github.io/nano-id-cc/
MIT License
24.66k stars 794 forks source link

Can't use nanoid@4 with typescript #442

Closed paulsmithkc closed 1 year ago

paulsmithkc commented 1 year ago

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
ai commented 1 year ago

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