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.22k stars 790 forks source link

Issue while running in Firebase Emulator (Cloud Functions) #458

Closed virajp closed 9 months ago

virajp commented 9 months ago

Issue: Getting following error while running inside Firebase Functions

Error [ERR_REQUIRE_ESM]: require() of ES Module ./node_modules/nanoid/index.js from ./cff/lib/utils/idGeneration.js not supported.
Instead change the require of index.js in ./cff/lib/utils/idGeneration.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (./cff/lib/utils/idGeneration.js:4:18) {
  code: 'ERR_REQUIRE_ESM'
}

Setup:

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2017",
    "module": "CommonJS",
    "strict": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "useUnknownInCatchVariables": true,
    "lib": [
      "ES2017",
      "DOM",
    ],
    "typeRoots": [
      "types",
      "node_modules/@types",
    ],
  },
  "compileOnSave": true,
  "include": [
    "src",
  ],
  "settings": {
    "import/resolver": {
      "typescript": {}
    },
  },
}

Code:

idGeneration.ts

import { customAlphabet } from "nanoid";

export function generateId(): string {
  const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  const result = customAlphabet(alphabet, 12)();
  return result;
}

Notes:

Temporary Fix:

Switching to the older version of nanoid (v3.3.7) does not throw this error.

ai commented 9 months ago

As error and docs describes you need to use ESM environment. We do not support CommonJS environment for 4.x and 5.x (there is 3.x branch still supported for legacy environments).