library.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import type { ConfigEnv, UserConfig } from 'vite';
  2. import type { DefineLibraryOptions } from '../typing';
  3. import { readPackageJSON } from '@vben/node-utils';
  4. import { defineConfig, mergeConfig } from 'vite';
  5. import { loadLibraryPlugins } from '../plugins';
  6. import { getCommonConfig } from './common';
  7. function defineLibraryConfig(userConfigPromise?: DefineLibraryOptions) {
  8. return defineConfig(async (config: ConfigEnv) => {
  9. const options = await userConfigPromise?.(config);
  10. const { command, mode } = config;
  11. const { library = {}, vite = {} } = options || {};
  12. const root = process.cwd();
  13. const isBuild = command === 'build';
  14. const plugins = await loadLibraryPlugins({
  15. dts: false,
  16. injectMetadata: true,
  17. isBuild,
  18. mode,
  19. ...library,
  20. });
  21. const { dependencies = {}, peerDependencies = {} } =
  22. await readPackageJSON(root);
  23. const externalPackages = [
  24. ...Object.keys(dependencies),
  25. ...Object.keys(peerDependencies),
  26. ];
  27. const packageConfig: UserConfig = {
  28. build: {
  29. lib: {
  30. entry: 'src/index.ts',
  31. fileName: () => 'index.mjs',
  32. formats: ['es'],
  33. },
  34. rollupOptions: {
  35. external: (id) => {
  36. return externalPackages.some(
  37. (pkg) => id === pkg || id.startsWith(`${pkg}/`),
  38. );
  39. },
  40. },
  41. },
  42. plugins,
  43. };
  44. const commonConfig = await getCommonConfig();
  45. const mergedConmonConfig = mergeConfig(commonConfig, packageConfig);
  46. return mergeConfig(mergedConmonConfig, vite);
  47. });
  48. }
  49. export { defineLibraryConfig };