plugins.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { reactRouter } from '@react-router/dev/vite';
  2. import legacy from '@vitejs/plugin-legacy';
  3. import react from '@vitejs/plugin-react';
  4. import removeConsole from 'vite-plugin-remove-console';
  5. // import wasm from 'vite-plugin-wasm'; // 代码中直接 import 'xxx.wasm' 时需要用到此插件
  6. // import topLevelAwait from 'vite-plugin-top-level-await'; // 使用 vite-plugin-wasm 插件时需要同时引入此插件
  7. import { viteBuildInfo } from '../buildInfo';
  8. import { configCompressPlugin } from '../compress';
  9. import svgConvert from '../svgConvert';
  10. import { clientChunksPlugin } from './chunks';
  11. import type { PluginOption } from 'vite';
  12. /**
  13. * 组装插件数组。依赖渲染模式(isCSR)、环境(isProd)与 env(压缩方式)。
  14. * @param isCSR 是否 CSR 模式。CSR 用官方 plugin-react;SSG 用 reactRouter(接管 React 处理与入口)。二者互斥。
  15. * @param isProd 是否生产构建。生产才启用 removeConsole。
  16. * @param env 处理后的环境变量(提供 VITE_BUILD_COMPRESSION)。
  17. */
  18. export function createPlugins(isCSR: boolean, isProd: boolean, env: ImportMetaEnv): PluginOption[] {
  19. return [
  20. // React 处理:CSR 用官方 plugin-react;SSG 用 reactRouter(自带 React 处理并接管入口)。二者互斥。
  21. isCSR ? react() : reactRouter(),
  22. // clientChunksPlugin 仅 SSG 需要(framework 分 client/ssr 双环境构建);
  23. // CSR 单环境构建,vendor 分包直接写在 build.rollupOptions 里。
  24. !isCSR && clientChunksPlugin,
  25. // wasm(),
  26. // topLevelAwait(),
  27. legacy({
  28. // 浏览器支持基线(browserslist 语法):chrome87/safari13/firefox78/edge88 这条老线,
  29. // 与 build.ts 的 CSS_TARGET(esbuild 语法)表达同一基线,需保持一致。
  30. // legacy() 会为该基线生成 nomodule 的 legacy chunk + polyfill,并用 Babel 降级现代 JS 语法,
  31. // 使产物可在这些老浏览器上运行(现代浏览器仍走 type=module 的现代 chunk)。
  32. targets: ['chrome >= 87', 'safari >= 13', 'firefox >= 78', 'edge >= 88', 'not IE 11'],
  33. }),
  34. isProd &&
  35. removeConsole({
  36. includes: ['log', 'warn'],
  37. external: ['error'],
  38. }),
  39. svgConvert(),
  40. viteBuildInfo(),
  41. configCompressPlugin(env.VITE_BUILD_COMPRESSION!),
  42. ].filter(Boolean) as PluginOption[];
  43. }