|
| 1 | +import { VIRTUAL } from '../../constants'; |
| 2 | +import type { File } from '$lib/Workspace.svelte'; |
| 3 | +import type { Plugin } from '@rollup/browser'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Alias plugin for resolving import aliases (e.g., $lib -> src/lib). |
| 7 | + * This will also run on npm packages, so that e.g. SvelteKit libraries using $app/environment can also make use of this. |
| 8 | + * |
| 9 | + * @example |
| 10 | + * // With aliases: { '$lib': 'src/lib' } |
| 11 | + * // import foo from '$lib/foo' -> import foo from 'src/lib/foo' |
| 12 | + * // import bar from '$lib' -> import bar from 'src/lib' |
| 13 | + */ |
| 14 | +function alias_plugin(aliases: Record<string, string> = {}, virtual: Map<string, File>): Plugin { |
| 15 | + // Sort aliases by length (longest first) to avoid conflicts |
| 16 | + const alias_entries = Object.entries(aliases).sort((a, b) => b[0].length - a[0].length); |
| 17 | + |
| 18 | + return { |
| 19 | + name: 'alias', |
| 20 | + resolveId(importee, importer) { |
| 21 | + // Skip if no aliases configured / this is a relative import |
| 22 | + if (alias_entries.length === 0 || importee[0] === '.') { |
| 23 | + return null; |
| 24 | + } |
| 25 | + |
| 26 | + // Check if the import matches any alias |
| 27 | + for (const [alias_key, alias_path] of alias_entries) { |
| 28 | + if (importee === alias_key) { |
| 29 | + // Exact match - replace with alias path |
| 30 | + return resolve(virtual, `${VIRTUAL}/${alias_path}`, importer); |
| 31 | + } else if (importee.startsWith(alias_key + '/')) { |
| 32 | + // Partial match - replace the prefix |
| 33 | + const relative_path = importee.slice(alias_key.length + 1); |
| 34 | + return resolve(virtual, `${VIRTUAL}/${alias_path}/${relative_path}`, importer); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + // No alias match, let other plugins handle it |
| 39 | + return null; |
| 40 | + } |
| 41 | + }; |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + * Tries to resolve the import path based on the virtual file map, trying different suffixes. |
| 46 | + */ |
| 47 | +export function resolve(virtual: Map<string, File>, importee: string, importer: string): string { |
| 48 | + const url = new URL(importee, importer); |
| 49 | + |
| 50 | + for (const suffix of ['', '.js', '.json', '.ts', '/index.js', '/index.ts']) { |
| 51 | + const with_suffix = `${url.href.slice(VIRTUAL.length + 1)}${suffix}`; |
| 52 | + const file = virtual.get(with_suffix); |
| 53 | + |
| 54 | + if (file) { |
| 55 | + return url.href + suffix; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + throw new Error( |
| 60 | + `'${importee}' (imported by ${importer.replace(VIRTUAL + '/', '')}) does not exist` |
| 61 | + ); |
| 62 | +} |
| 63 | + |
| 64 | +export default alias_plugin; |
0 commit comments