Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

import.meta.resolve doesn't provide a file extension while require.resolve does. #4543

Open
2 tasks done
hmidmrii opened this issue Feb 6, 2025 · 2 comments
Open
2 tasks done

Comments

@hmidmrii
Copy link

hmidmrii commented Feb 6, 2025

Node.js Version

v20.14.0

NPM Version

v10.7.0

Operating System

Windows 11

Subsystem

Other

Description

I have an ESM file that have the following import statement:

import keyBy from 'lodash-es/keyBy';

which is throwing an error about not being able to find the file:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '\node_modules\lodash-es\keyBy' imported from file.mjs
Did you mean to import "lodash-es/keyBy.js"?

same code in CJS env was working (obviously using lodash instead of lodash-es),

after investigating I tried resolving instead of importing to check, and here's the result:

// CJS
require.resolve('lodash');
// "node_modules/lodash/index.js"

require.resolve('lodash/keyBy');
// "node_modules/lodash/keyBy.js"

// ------------------------------

// ESM
import.meta.resolve('lodash-es');
// "node_modules/lodash-es/lodash.js"

import.meta.resolve('lodash-es/keyBy');
// "node_modules/lodash-es/keyBy"

as you can see only lodash-es/keyBy doesn't have a file extension 🤕

is this an expected behavior or did I catch a big fish (jk)?

please correct me I'm missing something here 🙏

Minimal Reproduction

import keyBy from 'lodash-es/keyBy';

Output

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '\node_modules\lodash-es\keyBy' imported from file.mjs
Did you mean to import "lodash-es/keyBy.js"?

Before You Submit

  • I have looked for issues that already exist before submitting this
  • My issue follows the guidelines in the README file, and follows the 'How to ask a good question' guide at https://stackoverflow.com/help/how-to-ask
@hmidmrii
Copy link
Author

hmidmrii commented Feb 6, 2025

it's not urgent at all, since I can use import { keyBy } from 'lodash-es'; and it will work perfectly fine,

but it would be good to learn the behaviors of import

@ljharb
Copy link
Member

ljharb commented Feb 6, 2025

That's because require uses the CJS algorithm, which automatically fills in file extensions for you - ESM does not.

Neither lodash nor lodash-es provide an exports field, so you are required to use the full path, including extension, for import.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants