vite-plugin-config.ts 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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');
  26. config.build = {
  27. ...buildConfig,
  28. outDir: normalizedOutDir,
  29. };
  30. }
  31. config.resolve = {
  32. alias: {
  33. ...(config.resolve?.alias ?? {}),
  34. // See the readme for an explanation of this alias.
  35. '@/vdb': path.resolve(packageRoot, './src/lib'),
  36. '@/graphql': path.resolve(packageRoot, './src/lib/graphql'),
  37. },
  38. };
  39. // This is required to prevent Vite from pre-bundling the
  40. // dashboard source when it resides in node_modules.
  41. config.optimizeDeps = {
  42. ...config.optimizeDeps,
  43. exclude: [
  44. ...(config.optimizeDeps?.exclude || []),
  45. '@vendure/dashboard',
  46. '@/vdb',
  47. 'virtual:vendure-ui-config',
  48. 'virtual:admin-api-schema',
  49. 'virtual:dashboard-extensions',
  50. ],
  51. // We however do want to pre-bundle recharts, as it depends
  52. // on lodash which is a CJS packages and _does_ require
  53. // pre-bundling.
  54. include: [
  55. ...(config.optimizeDeps?.include || []),
  56. '@/components > recharts',
  57. '@/components > react-dropzone',
  58. '@vendure/common/lib/generated-types',
  59. ],
  60. };
  61. return config;
  62. },
  63. };
  64. }