|
| 1 | +import type { Alias, Plugin as VitePlugin } from 'vite'; |
| 2 | +import type { BuildInternals } from '../../core/build/internal.js'; |
| 3 | + |
| 4 | +/** |
| 5 | + * `@rollup/plugin-alias` doesn't resolve aliases in Rollup input by default. This plugin fixes it |
| 6 | + * with a partial fork of it's resolve function. https://github.com/rollup/plugins/blob/master/packages/alias/src/index.ts |
| 7 | + * When https://github.com/rollup/plugins/pull/1402 is merged, we can remove this plugin. |
| 8 | + */ |
| 9 | +export function vitePluginAliasResolve(internals: BuildInternals): VitePlugin { |
| 10 | + let aliases: Alias[]; |
| 11 | + |
| 12 | + return { |
| 13 | + name: '@astro/plugin-alias-resolve', |
| 14 | + enforce: 'pre', |
| 15 | + configResolved(config) { |
| 16 | + aliases = config.resolve.alias; |
| 17 | + }, |
| 18 | + async resolveId(id, importer, opts) { |
| 19 | + if ( |
| 20 | + !importer && |
| 21 | + (internals.discoveredHydratedComponents.has(id) || |
| 22 | + internals.discoveredClientOnlyComponents.has(id)) |
| 23 | + ) { |
| 24 | + const matchedEntry = aliases.find((entry) => matches(entry.find, id)); |
| 25 | + if (!matchedEntry) { |
| 26 | + return null; |
| 27 | + } |
| 28 | + |
| 29 | + const updatedId = id.replace(matchedEntry.find, matchedEntry.replacement); |
| 30 | + |
| 31 | + return this.resolve(updatedId, importer, Object.assign({ skipSelf: true }, opts)).then( |
| 32 | + (resolved) => resolved || { id: updatedId } |
| 33 | + ); |
| 34 | + } |
| 35 | + }, |
| 36 | + }; |
| 37 | +} |
| 38 | + |
| 39 | +function matches(pattern: string | RegExp, importee: string) { |
| 40 | + if (pattern instanceof RegExp) { |
| 41 | + return pattern.test(importee); |
| 42 | + } |
| 43 | + if (importee.length < pattern.length) { |
| 44 | + return false; |
| 45 | + } |
| 46 | + if (importee === pattern) { |
| 47 | + return true; |
| 48 | + } |
| 49 | + return importee.startsWith(pattern + '/'); |
| 50 | +} |
0 commit comments