Dynamic imports don't work when `exports` specified in package.json
See original GitHub issueBug report
What is the current behavior?
For example, highlight.js
has the following in exports
of package.json
:
{
"exports": {
"./lib/languages/*": {
"require": "./lib/languages/*.js",
"import": "./es/languages/*.js"
}
}
}
I tried to import a language dynamically using the following code in a Vue 3 / TS 4 app:
const langName = ref('')
const message = ref('')
const module = await import(
`highlight.js/lib/languages/${langName.value}`
)
message.value = module.default.name
This leads to the following error:
error in ./src/App.vue?vue&type=script&lang=ts
Module not found: Error: Package path ./lib/languages is not exported from package <path_to_proj>/node_modules/highlight.js (see exports field in <path_to_proj>/node_modules/highlight.js/package.json)
If the current behavior is a bug, please provide the steps to reproduce.
- Clone minimum reproduction repo and
npm install
. - Run the project with
npm run serve
. - See error.
What is the expected behavior?
Replacing ${langName.value}
with a literal value works and imports the file as expected:
const langName = ref('')
const message = ref('')
const module = await import(
`highlight.js/lib/languages/javascript`
)
message.value = module.default.name
Dynamic import should work equally well.
Workarounds
The comment https://github.com/highlightjs/highlight.js/issues/3223#issuecomment-886143417 contains possible workarounds, if that helps to narrow the problem.
Other relevant information: webpack version: 5 Node.js version: 14 Operating System: mac OS Additional tools: TypeScript 4, Vue 3, Babel 7
Issue Analytics
- State:
- Created 2 years ago
- Reactions:17
- Comments:17 (5 by maintainers)
Top GitHub Comments
So how are people dealing with this in real life other than begging package maintainers to stop using
imports
?It would be nice to have a workaround to suggest to our users, particular if this is not going to be fixed anytime soon.
To overcome this in an Angular app, I’ve used a relative path to the loaded module, for example:
became
(ignore path differences, it should not matter)
App builds and successfully loads the languages again