10

I updated to nanoid4 and began getting the following error:

[ERR_REQUIRE_ESM]: require() of ES Module [...]/node_modules/nanoid/index.js not supported. Instead change the require of index.js in [...]/signup_test.ts to a dynamic import() which is available in all CommonJS modules

This is the import it's complaining about:

import { customAlphabet } from 'nanoid'

This is the tsconfig file I'm using:

{
    "ts-node": {
      "files": true
    },
    "compilerOptions": {
      "jsx": "react-jsx",
      "types": [
        "node",
        "codeceptjs"
      ],
      "experimentalDecorators": true,
      "lib": [
        "dom",
        "dom.iterable",
        "esnext"
      ],
      "allowJs": true,
      "skipLibCheck": true,
      "strict": false,
      "forceConsistentCasingInFileNames": true,
      "noEmit": true,
      "esModuleInterop": true,
      "module": "ES6",
      "moduleResolution": "node",
      "resolveJsonModule": true,
      "incremental": true,
      "target": "ESNext",
    },
    "include": [
      "next-env.d.ts",
      "**/*.ts",
      "**/*.tsx"
    ],
    "exclude": [
      "node_modules"
    ]
  }

Unsure why it's broken

meds
  • 21,699
  • 37
  • 163
  • 314
  • 2
    Did you look at the generated Javascript (not your TypeScript source) to see what code is actually executing. That would tell us better what is actually going on here. My guess would be that your TypeScript settings are generating a CommonJS module out of your index.js and thus it generated a `require('nanoid')` which isn't legal is `nanoid` is an ESM module. So, perhaps your TypeScript compiler configuration is wrong. But, that's just a guess. Seeing the generated JS file would tell you more. – jfriend00 Jun 13 '22 at 03:55

4 Answers4

20

It works if you use another version of nanoid. For example:

npm uninstall nanoid
npm install nanoid@3.3.4

If it doesn't, try changing some of your tsconfig.json according to this.

Lee Moe
  • 313
  • 2
  • 9
16

The error "[ERR_REQUIRE_ESM]: require() not supported" occurs because a package you are importing has been converted to be an ESM only package, which means that the package cannot be imported with require() anymore. Use npm i nanoid@2.1.11

1

I changed my import to this: import * as nanoid from 'nanoid'; and it worked, so you can try re-writing your import statement

The nanoid docs do not specify this but I just thought about it and tried and it worked

I hope this helps others

0

Use another version of nanoId. For example:

npm uninstall nanoid
npm install nanoid@3.3.4