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.57k stars 791 forks source link

cant import v4.0.1 in TypeScript #418

Closed kehiy closed 1 year ago

kehiy commented 1 year ago

I'm trying to import nanoid in ts like this:

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

but I get this error:

Error [ERR_REQUIRE_ESM]: require() of ES Module D:\projects\node_modules\nanoid\index.js from D:\projects\SIFER\SIFER-backend\src\controllers\uniqueCipherController.ts not supported.
Instead change the require of index.js in D:\projects\a.ts to a dynamic import() which is available in all CommonJS modules.
ai commented 1 year ago

Nano ID 4.0 is ESM-only project. It works only with import. I recommend moving your project to ESM. Or you can install npm install nanoid@3 instead.

https://github.com/ai/nanoid#install

kehiy commented 1 year ago

but I'm using import now!

ai commented 1 year ago

Are you using TypeScript? With wrong settings it will compile import to require.

kehiy commented 1 year ago

yes! I think my ts config is problem😐

kasir-barati commented 1 year ago

@ai it is not always an option to config like this:

{
    "extends": "../../tsconfig.json",
    "compilerOptions": {
        "module": "ES6",
        "target": "es2017",
    }
}

At least not when you are using NestJS. Because then you cannot import @nestjs/*. What do you think? Should NestJS move away from commonjs too? Just asked out of curiosity.

Anyway, I tried this solution but it did not work too:

https://stackoverflow.com/a/73420399/8784518 e.x.

async function nanoidGenerator(length = 20) {
    const { customAlphabet } = await import('nanoid');
    return customAlphabet(PUBLIC_ID_SEED, length)();
}