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.33k stars 788 forks source link

import { customAlphabet } from 'nanoid' fails in TS - nanoid@4.0 #410

Closed wmelton closed 1 year ago

wmelton commented 1 year ago

TypeScript native project, node 18, nanoid@v4

Error message, "Must use import to load ES Module" - Is this error message just a bad message? Meaning, is the issue actually something else?

import { customAlphabet } from 'nanoid'

How else would one include nanoid@4.0 in a TS project except via import at this point?

TSConfig:

{
    "compilerOptions": {
         "target": "esnext",
        "module": "esnext",
        "lib": ["esnext", "es6", "dom"],
        "moduleResolution": "node",
    }
}
ai commented 1 year ago

Do you have "type": "module" in project’s package.json?

Do you have this error on type check or on program execution?

wmelton commented 1 year ago

Hey @ai - thanks for the fast response.

package.json: image

Program execution, though looking at it now, I need to clarify that it appears this only happens when running Jest tests. When running the main express app, the library performs as expected without error.

Okay, sounds like maybe this is related to Jest's relatively poor support for ESM still. Bummer though - nanoid@3^ works in both runtime and jest executions.

Guess we'll stick with v3 for now unless there's some fix to make Jest happy too.

ai commented 1 year ago

I need to clarify that it appears this only happens when running Jest tests

Jest hack import and require(). I can only send you to Jest team since I can’t help with type of hacks like their.

wmelton commented 1 year ago

Makes sense - I hadn't run it both directly and with jest when I opened the ticket or I wouldn't have wasted your time. Apologies.