nanoid: [TYPESCRIPT] Error [ERR_REQUIRE_ESM]: Must use import to load ES Module

Hi, I got this error when import nanoid to my project:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /todo-api/node_modules/nanoid/index.js
require() of ES modules is not supported.
require() of /todo-api/node_modules/nanoid/index.js from /todo-api/controllers/todo-apis/todo-apis.ts is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /todo-api/node_modules/nanoid/package.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1080:13)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (/todo-api/controllers/todo-apis/todo-apis.ts:1:1)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Module.m._compile (/todo-api/node_modules/ts-node/src/index.ts:1056:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Object.require.extensions.<computed> [as .ts] (/todo-api/node_modules/ts-node/src/index.ts:1059:12)

Please help! Please let me know if you need more information. Thanks.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 30 (10 by maintainers)

Most upvoted comments

I used to have the same issue with my NestJS app. So I downgraded this package to version nanoid@^3.3.4 and it solved the problem.

Is package size a serious consideration for node.js, or only for browser? If your position is firm, then I recommend updating your readme/docs to reflect this breaking change so that new projects will not constantly end up in this issue.