extra-app-config.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import {
  2. colors,
  3. generatorContentHash,
  4. readPackageJSON,
  5. } from '@vben/node-utils';
  6. import { type PluginOption } from 'vite';
  7. import { getEnvConfig } from '../utils/env';
  8. interface PluginOptions {
  9. isBuild: boolean;
  10. root: string;
  11. }
  12. const GLOBAL_CONFIG_FILE_NAME = '_app.config.js';
  13. const VBEN_ADMIN_PRO_APP_CONF = '_VBEN_ADMIN_PRO_APP_CONF_';
  14. /**
  15. * 用于将配置文件抽离出来并注入到项目中
  16. * @returns
  17. */
  18. async function viteExtraAppConfigPlugin({
  19. isBuild,
  20. root,
  21. }: PluginOptions): Promise<PluginOption | undefined> {
  22. let publicPath: string;
  23. let source: string;
  24. if (!isBuild) {
  25. return;
  26. }
  27. const { version = '' } = await readPackageJSON(root);
  28. return {
  29. async configResolved(config) {
  30. publicPath = ensureTrailingSlash(config.base);
  31. source = await getConfigSource();
  32. },
  33. async generateBundle() {
  34. try {
  35. this.emitFile({
  36. fileName: GLOBAL_CONFIG_FILE_NAME,
  37. source,
  38. type: 'asset',
  39. });
  40. // eslint-disable-next-line no-console
  41. console.log(colors.cyan(`✨configuration file is build successfully!`));
  42. } catch (error) {
  43. // eslint-disable-next-line no-console
  44. console.log(
  45. colors.red(
  46. `configuration file configuration file failed to package:\n${error}`,
  47. ),
  48. );
  49. }
  50. },
  51. name: 'vite:extra-app-config',
  52. async transformIndexHtml(html) {
  53. const hash = `v=${version}-${generatorContentHash(source, 8)}`;
  54. const appConfigSrc = `${publicPath}${GLOBAL_CONFIG_FILE_NAME}?${hash}`;
  55. return {
  56. html,
  57. tags: [{ attrs: { src: appConfigSrc }, tag: 'script' }],
  58. };
  59. },
  60. };
  61. }
  62. async function getConfigSource() {
  63. const config = await getEnvConfig();
  64. const windowVariable = `window.${VBEN_ADMIN_PRO_APP_CONF}`;
  65. // 确保变量不会被修改
  66. let source = `${windowVariable}=${JSON.stringify(config)};`;
  67. source += `
  68. Object.freeze(${windowVariable});
  69. Object.defineProperty(window, "${VBEN_ADMIN_PRO_APP_CONF}", {
  70. configurable: false,
  71. writable: false,
  72. });
  73. `.replaceAll(/\s/g, '');
  74. return source;
  75. }
  76. function ensureTrailingSlash(path: string) {
  77. return path.endsWith('/') ? path : `${path}/`;
  78. }
  79. export { viteExtraAppConfigPlugin };