nanoid: TypeError: (0 , _nanoid.nanoid) is not a function

I trying upgrade nanoid from 2.x to 3.x in CRA environment

The export value from nanoid is always undefined

And i got error when running below jest test

import { nanoid } from 'nanoid';
it('Should work', () => {
  console.log('nanoid is ', nanoid);
  const genId = nanoid();
  expect(() => genId()).not.toThrow();
});

Console message

console.log src/services/spotify/auth/__tests__/authorize.test.ts:14
    nanoid is  undefined
TypeError: (0 , _nanoid.nanoid) is not a function

Also i try below test

import * as nanoid from 'nanoid';

it('Should work', () => {
  console.log('nanoid is ', nanoid);
  const genId = nanoid.nanoid();
  expect(() => genId()).not.toThrow();
});

Console message

  console.log src/services/spotify/auth/__tests__/authorize.test.ts:14
    nanoid is  { default: 'index.cjs' }
TypeError: nanoid.nanoid is not a function

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 17
  • Comments: 27 (10 by maintainers)

Most upvoted comments

I created pull request https://github.com/facebook/create-react-app/pull/8768

Please add đź‘Ť if you want to merge it quicker

In node.js this is not working:

const nanoid = require('nanoid');
nanoid();

This works:

const {nanoid} = require('nanoid');
nanoid();

I’m facing the same problem when using react testing library TypeError: (0 , _nanoid.nanoid) is not a function

using nanoid version ^3.1.12

Any news on this? For some reason, this problem occurs only when i’m mocking the module globally (inside “__mocks__/nanoid.ts”) like this: export default { nanoid: () => '123456789012', }; But not when i mock it inside individual test suites like this: jest.mock('nanoid', () => ({ nanoid: () => '123456789012', }));

For anyone that is still facing the issue. ESM can’t import named CJS exports unless CJS scripts execute out of order

So you can do this:

import nanoid from 'nanoid'

but you can’t do this:

import { nanoid } from 'nanoid'

That’s because CJS scripts compute their named exports as they execute, whereas ESM’s named exports must be computed during the parsing phase.

A workaround is

import _nanoid from 'nanoid'
const { nanoid } = _nanoid

I’m having the same issue when running on Code Sandbox. It seems to work fine below version 3.1.17 of nanoid. Is this related, or could it be an issue with Code Sandbox?

@tareqdayya Create React App maintainers accepted my PR but still do not release it. Feel free to create an issue in their repo and ask for release.

I can’t help here. Ask CRA maintainers about releasing the fix,