extra-app-config.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import type { PluginOption } from 'vite';
  2. import {
  3. colors,
  4. generatorContentHash,
  5. readPackageJSON,
  6. } from '@vben/node-utils';
  7. import { loadEnv } 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. console.log(colors.cyan(`✨configuration file is build successfully!`));
  41. } catch (error) {
  42. console.log(
  43. colors.red(
  44. `configuration file configuration file failed to package:\n${error}`,
  45. ),
  46. );
  47. }
  48. },
  49. name: 'vite:extra-app-config',
  50. async transformIndexHtml(html) {
  51. const hash = `v=${version}-${generatorContentHash(source, 8)}`;
  52. const appConfigSrc = `${publicPath}${GLOBAL_CONFIG_FILE_NAME}?${hash}`;
  53. return {
  54. html,
  55. tags: [{ attrs: { src: appConfigSrc }, tag: 'script' }],
  56. };
  57. },
  58. };
  59. }
  60. async function getConfigSource() {
  61. const config = await loadEnv();
  62. const windowVariable = `window.${VBEN_ADMIN_PRO_APP_CONF}`;
  63. // 确保变量不会被修改
  64. let source = `${windowVariable}=${JSON.stringify(config)};`;
  65. source += `
  66. Object.freeze(${windowVariable});
  67. Object.defineProperty(window, "${VBEN_ADMIN_PRO_APP_CONF}", {
  68. configurable: false,
  69. writable: false,
  70. });
  71. `.replaceAll(/\s/g, '');
  72. return source;
  73. }
  74. function ensureTrailingSlash(path: string) {
  75. return path.endsWith('/') ? path : `${path}/`;
  76. }
  77. export { viteExtraAppConfigPlugin };