application.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import type { UserConfig } from 'vite';
  2. import type { DefineApplicationOptions } from '../typing';
  3. import { resolve } from 'node:path';
  4. import { defineConfig, loadEnv, mergeConfig } from 'vite';
  5. import { getApplicationConditionPlugins } from '../plugins';
  6. import { getCommonConfig } from './common';
  7. function defineApplicationConfig(options: DefineApplicationOptions = {}) {
  8. return defineConfig(async (config) => {
  9. const { command, mode } = config;
  10. const { application = {}, vite = {} } = options;
  11. const root = process.cwd();
  12. const isBuild = command === 'build';
  13. const env = loadEnv(mode, root);
  14. const plugins = await getApplicationConditionPlugins({
  15. compress: false,
  16. compressTypes: ['brotli', 'gzip'],
  17. devtools: true,
  18. env,
  19. extraAppConfig: true,
  20. html: true,
  21. i18n: true,
  22. injectAppLoading: true,
  23. isBuild,
  24. mock: true,
  25. mode,
  26. pwa: true,
  27. turboConsole: false,
  28. ...(typeof application === 'function'
  29. ? application(config)
  30. : application),
  31. });
  32. const applicationConfig: UserConfig = {
  33. build: {
  34. rollupOptions: {
  35. output: {
  36. assetFileNames: '[ext]/[name]-[hash].[ext]',
  37. chunkFileNames: 'js/[name]-[hash].mjs',
  38. entryFileNames: 'jse/index-[name]-[hash].mjs',
  39. },
  40. },
  41. target: 'es2015',
  42. },
  43. esbuild: {
  44. drop: isBuild
  45. ? [
  46. // 'console',
  47. 'debugger',
  48. ]
  49. : [],
  50. legalComments: 'none',
  51. },
  52. plugins,
  53. resolve: {
  54. alias: [
  55. {
  56. find: /@\//,
  57. replacement: `${resolve(root, '.', 'src')}/`,
  58. },
  59. /**
  60. * 确保大仓内的子包,如果通过源码方式引用,可以直接使用@别名
  61. */
  62. // {
  63. // find: '@',
  64. // replacement: '@',
  65. // customResolver(source, importer) {
  66. // if (source[0] === '@') {
  67. // const realPath = source.replace(
  68. // /^@/,
  69. // resolve(findUpPackageDir(importer), 'src'),
  70. // );
  71. // return findFileByExtension(realPath);
  72. // }
  73. // return null;
  74. // },
  75. // },
  76. ],
  77. },
  78. server: {
  79. host: true,
  80. warmup: {
  81. // 预热文件
  82. clientFiles: ['./index.html', './src/{views,layouts}/*'],
  83. },
  84. },
  85. };
  86. const mergedConfig = mergeConfig(
  87. await getCommonConfig(),
  88. applicationConfig,
  89. );
  90. return mergeConfig(
  91. mergedConfig,
  92. typeof vite === 'function' ? vite(config) : vite,
  93. );
  94. });
  95. }
  96. export { defineApplicationConfig };