cant import v4.0.1 in TypeScript
kehiy opened this issue · comments
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.
but I'm using import now!
Are you using TypeScript? With wrong settings it will compile import
to require
.
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)();
}