admin-vben5/internal/vite-config/src/config/library.ts

60 lines
1.6 KiB
TypeScript
Raw Normal View History

import type { ConfigEnv, UserConfig } from 'vite';
2024-05-19 21:20:42 +08:00
2024-06-08 19:49:06 +08:00
import type { DefineLibraryOptions } from '../typing';
2024-05-19 21:20:42 +08:00
import { readPackageJSON } from '@vben/node-utils';
2024-06-08 19:49:06 +08:00
2024-05-19 21:20:42 +08:00
import { defineConfig, mergeConfig } from 'vite';
import { loadLibraryPlugins } from '../plugins';
2024-05-19 21:20:42 +08:00
import { getCommonConfig } from './common';
function defineLibraryConfig(userConfigPromise?: DefineLibraryOptions) {
return defineConfig(async (config: ConfigEnv) => {
const options = await userConfigPromise?.(config);
2024-06-16 15:45:15 +08:00
const { command, mode } = config;
const { library = {}, vite = {} } = options || {};
const root = process.cwd();
2024-05-19 21:20:42 +08:00
const isBuild = command === 'build';
const plugins = await loadLibraryPlugins({
2024-05-19 21:20:42 +08:00
dts: false,
2024-06-23 20:05:22 +08:00
injectMetadata: true,
2024-05-19 21:20:42 +08:00
isBuild,
mode,
...library,
2024-05-19 21:20:42 +08:00
});
const { dependencies = {}, peerDependencies = {} } =
await readPackageJSON(root);
2024-06-29 14:45:02 +08:00
const externalPackages = [
2024-05-19 21:20:42 +08:00
...Object.keys(dependencies),
...Object.keys(peerDependencies),
];
2024-06-29 14:45:02 +08:00
2024-05-19 21:20:42 +08:00
const packageConfig: UserConfig = {
build: {
lib: {
entry: 'src/index.ts',
fileName: () => 'index.mjs',
2024-05-19 21:20:42 +08:00
formats: ['es'],
},
rollupOptions: {
2024-06-29 14:45:02 +08:00
external: (id) => {
return externalPackages.some(
(pkg) => id === pkg || id.startsWith(`${pkg}/`),
);
},
2024-05-19 21:20:42 +08:00
},
},
plugins,
};
const commonConfig = await getCommonConfig();
const mergedConmonConfig = mergeConfig(commonConfig, packageConfig);
return mergeConfig(mergedConmonConfig, vite);
2024-05-19 21:20:42 +08:00
});
}
export { defineLibraryConfig };