1
0

vite-plugin-config.ts 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import path from 'path';
  2. import { ConfigEnv, Plugin, UserConfig } from 'vite';
  3. export function viteConfigPlugin({ packageRoot }: { packageRoot: string }): Plugin {
  4. return {
  5. name: 'vendure:vite-config-plugin',
  6. config: (config: UserConfig, env: ConfigEnv) => {
  7. // Only set the vite `root` to the dashboard package when running the dev server.
  8. // During a production build we still need to reference the dashboard source which
  9. // lives in `node_modules`, but we don't want the build output to be emitted in there.
  10. // Therefore we set `root` only for `serve` and, for `build`, we instead make sure that
  11. // an `outDir` **outside** of `node_modules` is used (defaulting to the current working
  12. // directory if the user did not provide one already).
  13. config.root = packageRoot;
  14. // If we are building and no explicit outDir has been provided (or it is a relative path),
  15. // set it to an **absolute** path relative to the cwd so that the output never ends up in
  16. // `node_modules`.
  17. if (env.command === 'build') {
  18. const buildConfig = config.build ?? {};
  19. const hasOutDir = typeof buildConfig.outDir === 'string' && buildConfig.outDir.length > 0;
  20. const outDirIsAbsolute = hasOutDir && path.isAbsolute(buildConfig.outDir as string);
  21. const normalizedOutDir = hasOutDir
  22. ? outDirIsAbsolute
  23. ? (buildConfig.outDir as string)
  24. : path.resolve(process.cwd(), buildConfig.outDir as string)
  25. : path.resolve(process.cwd(), 'dist/vendure-dashboard');
  26. config.build = {
  27. ...buildConfig,
  28. outDir: normalizedOutDir,
  29. };
  30. }
  31. config.resolve = {
  32. alias: {
  33. ...(config.resolve?.alias ?? {}),
  34. '@': path.resolve(packageRoot, './src/lib'),
  35. },
  36. };
  37. // This is required to prevent Vite from pre-bundling the
  38. // dashboard source when it resides in node_modules.
  39. config.optimizeDeps = {
  40. ...config.optimizeDeps,
  41. exclude: [
  42. ...(config.optimizeDeps?.exclude || []),
  43. '@vendure/dashboard',
  44. '@/providers',
  45. '@/framework',
  46. '@/lib',
  47. '@/components',
  48. '@/hooks',
  49. 'virtual:vendure-ui-config',
  50. 'virtual:admin-api-schema',
  51. 'virtual:dashboard-extensions',
  52. ],
  53. // We however do want to pre-bundle recharts, as it depends
  54. // on lodash which is a CJS packages and _does_ require
  55. // pre-bundling.
  56. include: [
  57. ...(config.optimizeDeps?.include || []),
  58. '@/components > recharts',
  59. '@/components > react-dropzone',
  60. ],
  61. };
  62. return config;
  63. },
  64. };
  65. }