appConfig.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * Copyright (c) 2013-Now https://jeesite.com All rights reserved.
  3. * No deletion without permission, or be held responsible to law.
  4. * @author ThinkGem
  5. */
  6. import { type PluginOption } from 'vite';
  7. import { PackageJson } from 'pkg-types';
  8. import { getEnvConfig } from './index';
  9. import { getEnvConfigName } from './getEnvConfigName';
  10. import { version } from '../../package.json';
  11. import colors from 'picocolors';
  12. const PLUGIN_NAME = 'app-config';
  13. const APP_CONFIG_FILE_NAME = '_app.config.js';
  14. export function appConfigPlugin(isBuild: boolean, viteEnv: ViteEnv): PluginOption {
  15. if (!isBuild) {
  16. return {
  17. name: PLUGIN_NAME,
  18. };
  19. }
  20. let publicPath: string;
  21. let appConfigContent: string;
  22. return {
  23. name: PLUGIN_NAME,
  24. async configResolved(_config) {
  25. publicPath = _config.base;
  26. appConfigContent = await getConfigContent(viteEnv);
  27. },
  28. async transformIndexHtml(html) {
  29. publicPath = (publicPath.endsWith('/') ? publicPath : `${publicPath}/`) || '/';
  30. const src = `${publicPath}${APP_CONFIG_FILE_NAME}?v=${version}-${new Date().getTime()}`;
  31. return { html, tags: [{ tag: 'script', attrs: { src } }] };
  32. },
  33. async generateBundle() {
  34. try {
  35. this.emitFile({
  36. type: 'asset',
  37. fileName: APP_CONFIG_FILE_NAME,
  38. source: appConfigContent,
  39. });
  40. this.emitFile({
  41. type: 'asset',
  42. fileName: 'timestamp.txt',
  43. source: `${new Date().getTime()}`,
  44. });
  45. console.log(colors.cyan(`✨configuration file is build successfully!`));
  46. } catch (error) {
  47. console.log(colors.red('configuration file configuration file failed to package:\n' + error));
  48. }
  49. },
  50. };
  51. }
  52. async function getConfigContent(env: ViteEnv) {
  53. const config = await getEnvConfig();
  54. const envConfigName = getEnvConfigName(env);
  55. const windowVariable = `window.${envConfigName}`;
  56. // Ensure that the variable will not be modified
  57. let source = `${windowVariable}=${JSON.stringify(config)};`;
  58. source += `
  59. Object.freeze(${windowVariable});
  60. Object.defineProperty(window, "${envConfigName}", {
  61. configurable: false,
  62. writable: false,
  63. });
  64. if(location.hostname!=='localhost'&&location.hostname!=='127.0.0.1'){
  65. var _hmt = _hmt || []; (function() {
  66. var hm = document.createElement("script");
  67. hm.src = "https://hm.baidu.com/hm.js?65b88e88a94e0118de2962f328f17622";
  68. var s = document.getElementsByTagName("script")[0];
  69. s.parentNode.insertBefore(hm, s);
  70. })();}
  71. `.replace(/(?!var|\b)\s/g, '');
  72. return source;
  73. }