64 lines
2.0 KiB
TypeScript
64 lines
2.0 KiB
TypeScript
|
|
import type { Alias, AliasOptions, Plugin } from 'vite';
|
||
|
|
import process from 'node:process';
|
||
|
|
import { pathToFileURL } from 'node:url';
|
||
|
|
import { getPackages } from '@manypkg/get-packages';
|
||
|
|
import packageJson from '../package.json';
|
||
|
|
|
||
|
|
async function collectEntryAlias(packageDirSet: Set<string>): Promise<Alias[]> {
|
||
|
|
const workspaces = await getPackages(process.cwd());
|
||
|
|
return Object.entries(packageJson.dependencies).reduce((cur: any, pkg) => {
|
||
|
|
const [name, version] = pkg;
|
||
|
|
|
||
|
|
if (name && (version as any).startsWith('workspace')) {
|
||
|
|
const packageObj = workspaces.packages.find(p => p.packageJson.name === name);
|
||
|
|
if (packageObj) {
|
||
|
|
cur.push({
|
||
|
|
find: new RegExp(`^${name}$`),
|
||
|
|
// replacement: path.resolve(packageObj.dir, './src/index'),
|
||
|
|
replacement: new URL('./src/index', pathToFileURL(`${packageObj.dir}/`)),
|
||
|
|
});
|
||
|
|
packageDirSet.add(packageObj.dir);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
return cur;
|
||
|
|
}, []);
|
||
|
|
}
|
||
|
|
function mergeAlias(alias: AliasOptions, aliases: Alias[]) {
|
||
|
|
if (Array.isArray(alias)) {
|
||
|
|
return [...aliases, ...alias];
|
||
|
|
} else {
|
||
|
|
return Object.entries(alias).reduce((cur, [key, value]) => {
|
||
|
|
cur.push({
|
||
|
|
find: key,
|
||
|
|
replacement: value,
|
||
|
|
});
|
||
|
|
return cur;
|
||
|
|
}, aliases);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
export async function Aliases(): Promise<Plugin> {
|
||
|
|
const packageDirSet = new Set<string>();
|
||
|
|
const aliases = await collectEntryAlias(packageDirSet);
|
||
|
|
return {
|
||
|
|
name: 'aliases',
|
||
|
|
enforce: 'pre',
|
||
|
|
config(config) {
|
||
|
|
config.resolve = {
|
||
|
|
...config.resolve,
|
||
|
|
alias: config.resolve?.alias ? mergeAlias(config.resolve.alias, aliases) : aliases,
|
||
|
|
};
|
||
|
|
},
|
||
|
|
transform(code, id) {
|
||
|
|
// 取根目录路径
|
||
|
|
const dir = id.split('/src/')[0];
|
||
|
|
// 将引用地方的 `@` 别名替换为子包的绝对路径
|
||
|
|
code = code.replace(/from '@\//g, `from '${dir}/src/`)
|
||
|
|
.replace(/import\('@\//g, `import('${dir}/src/`);
|
||
|
|
return {
|
||
|
|
code,
|
||
|
|
map: null,
|
||
|
|
};
|
||
|
|
},
|
||
|
|
};
|
||
|
|
}
|