Support ESM-style `"imports"` field aliases in `package.json`
See original GitHub issueClear and concise description of the problem
As of v14, Node.js now supports defining aliases for ESM imports in the packages.json
through the "imports"
field. Vite supports rollup-style aliases.
It would be nice if Vite was capable out of the box of reading the "imports"
field and translating it correctly to rollup aliases.
Suggested solution
As a proof of concept, I have implemented a version that uses rollup’s customResolver
feature and works as long as no conditional imports are used. It turned out to be surprisingly simple:
import path from 'path'
import fs from 'fs'
import { defineConfig } from 'vite'
import { findUpSync } from 'find-up'
const pkg = findUpSync('package.json', { cwd: process.cwd() })
const { imports = {} } = JSON.parse(fs.readFileSync(pkg, 'utf8'))
export default defineConfig({
// ...
resolve: {
alias: [
{
// Use a custom rollup resolver to emulate ESM-style imports
// mappings in vite, as read from `package.json` above:
find: /^#/,
replacement: '#',
customResolver(id) {
for (const [find, replacement] of Object.entries(imports)) {
const { match, capture } = matchIdentifier(id, find)
if (match) {
const replacementPath = path.resolve(replacement)
id = capture
? replacementPath.replace('*', capture)
: replacementPath
}
}
return id
}
}
]
}
})
function matchIdentifier(id, pattern) {
const regexp = new RegExp(`^${pattern.replace('*', '(.*)')}$`)
const match = id.match(regexp)
return {
match: !!match,
capture: match?.[1]
}
}
This works for my code-base with the following imports map:
"imports": {
"#config": "./src/config/index.js",
"#app": "./src/server/app.js",
"#models": "./src/server/models/index.js",
"#models/*": "./src/server/models/*.js",
"#controllers": "./src/server/controllers/index.js",
"#controllers/*": "./src/server/controllers/*.js",
"#services": "./src/server/services/index.js",
"#services/*": "./src/server/services/*.js",
"#errors": "./src/server/errors/index.js",
"#utils": "./src/server/utils/index.js",
"#utils/*": "./src/server/utils/*.js",
"#features/*": "./src/server/features/*.js",
"#admin/schema": "./src/admin/schema/index.js",
"#admin/*": "./src/admin/*.js",
"#test/*": "./test/*.js"
}
It shouldn’t be too hard to expand this to also support conditional imports.
Alternative
No response
Additional context
No response
Validations
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn’t already an issue that request the same feature to avoid creating a duplicate.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:10
- Comments:5 (1 by maintainers)
Top Results From Across the Web
Aliasing module paths in Node JS | Arun Michael Dsouza
Entries in the imports field must always start with # to ensure they are disambiguated from package specifiers. Other solutions. module-alias.
Read more >ECMAScript modules | Node.js v19.3.0 Documentation
json contains an "exports" field, in which case files within packages can only be accessed via the paths defined in "exports" . For...
Read more >Support "imports" field of package.json : WEB-51282 - YouTrack
Hi,. Node.js @ 14.13.0 introduced the `imports` field, and it's actually the lone solution to really import some local modules using a shortcut, ......
Read more >Unable to import module when using alias in package json
I was using this question as a reference to import my modules with aliases. I have the following package.json :
Read more >How to make your own npm package with typescript
The magic is in the package.json file, which tells npm: ... See `npm help init` for definitive documentation on these fields and exactly ......
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Subpath imports are supported by Webpack and esbuild. I think it should also be supported by Vite. I’m gonna woking on this.
Has it been resolved?
When building a project which contains chalk@5.0.0, it throws an error:
Here’s an online example. Visit and run
npm run build
.package.json in chalk@5.0.0: