library.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import type { UserConfig } from 'vite';
  2. import type { DefineLibraryOptions } from '../typing';
  3. import { readPackageJSON } from '@vben/node-utils';
  4. import { defineConfig, mergeConfig } from 'vite';
  5. import { getLibraryConditionPlugins } from '../plugins';
  6. import { getCommonConfig } from './common';
  7. function defineLibraryConfig(options: DefineLibraryOptions = {}) {
  8. return defineConfig(async (config) => {
  9. const { command, mode } = config;
  10. const root = process.cwd();
  11. const { library = {}, vite = {} } = options;
  12. const isBuild = command === 'build';
  13. const plugins = await getLibraryConditionPlugins({
  14. dts: false,
  15. injectLibCss: true,
  16. injectMetadata: true,
  17. isBuild,
  18. mode,
  19. ...(typeof library === 'function' ? library(config) : 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 mergedConfig = mergeConfig(commonConfig, packageConfig);
  46. return mergeConfig(
  47. mergedConfig,
  48. typeof vite === 'function' ? vite(config) : vite,
  49. );
  50. });
  51. }
  52. export { defineLibraryConfig };