ai / nanoid

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript

Home Page:https://zelark.github.io/nano-id-cc/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

cant import v4.0.1 in TypeScript

kehiy opened this issue · comments

commented

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.

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

commented

but I'm using import now!

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

commented

yes!
I think my ts config is problem😐

@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)();
}