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

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

Closed
4 tasks done
lehni opened this issue Mar 20, 2022 · 5 comments · Fixed by #7770
Closed
4 tasks done

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

lehni opened this issue Mar 20, 2022 · 5 comments · Fixed by #7770
Labels
enhancement New feature or request

Comments

@lehni
Copy link

lehni commented Mar 20, 2022

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

@fi3ework
Copy link
Member

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

@alienzhou
Copy link

alienzhou commented 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"
		]
	}
}

@otaviomad
Copy link

Can we get an update on this? I was surprised to find out that vite was the only one of the main bundlers that didn't support this feature when making our reference toolkit. There is a PR that has gone with no reviews for about 6 months now.

#7770

@bnjm
Copy link

bnjm commented Oct 21, 2022

[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.
...

If the error is only from rollup (while building), for now you can use @rollup/plugin-node-resolve which supports conditional exports / imports. Here's @alienzhou's repo forked to show that working:
https://stackblitz.com/edit/vitejs-vite-k1bhgi?file=vite.config.ts&terminal=dev. Since it might break other things you might want to narrow down which modules are included

@IgnusG
Copy link

IgnusG commented Nov 19, 2022

At least for building with rollup this seems to be fixed. When running vitest however - which seems to use whatever vite is using during its own runtime vitest-dev/vitest#1365 - it's still throwing an error.

@github-actions github-actions bot locked and limited conversation to collaborators Mar 21, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request
Projects
None yet
7 participants