question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Support ESM-style `"imports"` field aliases in `package.json`

See original GitHub issue

Clear 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

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:10
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

14reactions
fi3eworkcommented, Apr 10, 2022

Subpath imports are supported by Webpack and esbuild. I think it should also be supported by Vite. I’m gonna woking on this.

11reactions
alienzhoucommented, Aug 1, 2022

Has it been resolved?

When building a project which contains chalk@5.0.0, it throws an error:

[vite]: Rollup failed to resolve import "#ansi-styles" from "node_modules/chalk/source/index.js".
This is most likely unintended because it can break your application at runtime.
...

Here’s an online example. Visit and run npm run build.


package.json in chalk@5.0.0:

{
	"name": "chalk",
	"version": "5.0.0",
	"description": "Terminal string styling done right",
	"license": "MIT",
	"repository": "chalk/chalk",
	"funding": "https://github.com/chalk/chalk?sponsor=1",
	"type": "module",
	"exports": "./source/index.js",
	"imports": {
		"#ansi-styles": "./source/vendor/ansi-styles/index.js",
		"#supports-color": {
			"node": "./source/vendor/supports-color/index.js",
			"default": "./source/vendor/supports-color/browser.js"
		}
	},
	"types": "./source/index.d.ts",
	"engines": {
		"node": "^12.17.0 || ^14.13 || >=16.0.0"
	},
	"scripts": {
		"test": "xo && c8 ava && tsd",
		"bench": "matcha benchmark.js"
	},
	"files": [
		"source",
		"!source/index.test-d.ts"
	],
	"keywords": [
		"color",
		"colour",
		"colors",
		"terminal",
		"console",
		"cli",
		"string",
		"ansi",
		"style",
		"styles",
		"tty",
		"formatting",
		"rgb",
		"256",
		"shell",
		"xterm",
		"log",
		"logging",
		"command-line",
		"text"
	],
	"devDependencies": {
		"@types/node": "^16.11.10",
		"ava": "^3.15.0",
		"c8": "^7.10.0",
		"color-convert": "^2.0.1",
		"execa": "^6.0.0",
		"log-update": "^5.0.0",
		"matcha": "^0.7.0",
		"tsd": "^0.19.0",
		"xo": "^0.47.0",
		"yoctodelay": "^2.0.0"
	},
	"xo": {
		"rules": {
			"unicorn/prefer-string-slice": "off"
		}
	},
	"c8": {
		"reporter": [
			"text",
			"lcov"
		],
		"exclude": [
			"source/vendor"
		]
	}
}

Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found