inject-env-to-window.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. const CONFIG_NAME = "__PRODUCTION____APP__CONF__";
  2. const CONFIG_FILE_NAME = "_app.config.js";
  3. const OUTPUT_DIR = "release/dist";
  4. import path from "path";
  5. import dotenv from "dotenv";
  6. import fs from "fs";
  7. /**
  8. * 获取用户根目录
  9. * @param dir file path
  10. */
  11. function getRootPath(...dir) {
  12. return path.resolve(process.cwd(), ...dir);
  13. }
  14. /**
  15. * 获取以指定前缀开头的环境变量
  16. * @param match prefix
  17. * @param confFiles ext 为什么要测试和正式的都要循环有可能是测试加了东西但是正式没加,到时候上线会报错
  18. * 应该是防止环境变量缺失
  19. */
  20. function getEnvConfig(
  21. match = "VITE_",
  22. confFiles = [".env.development", ".env.production"]
  23. ) {
  24. let envConfig = {};
  25. confFiles.forEach(item => {
  26. try {
  27. const env = dotenv.parse(
  28. fs.readFileSync(path.resolve(process.cwd(), item))
  29. );
  30. envConfig = { ...envConfig, ...env };
  31. } catch (e) {
  32. console.error(`解析错误:${item}`, e);
  33. }
  34. });
  35. const reg = new RegExp(`^(${match})`);
  36. Object.keys(envConfig).forEach(key => {
  37. if (!reg.test(key)) {
  38. Reflect.deleteProperty(envConfig, key);
  39. }
  40. });
  41. return envConfig;
  42. }
  43. function createConfig(params) {
  44. const { configName, config, configFileName } = params;
  45. try {
  46. const windowConf = `window.${configName}`;
  47. // 确保变量不会被修改
  48. const configStr = `${windowConf}=${JSON.stringify(config)};
  49. Object.freeze(${windowConf});
  50. Object.defineProperty(window, "${configName}", {
  51. configurable: false,
  52. writable: false,
  53. });
  54. `.replace(/\s/g, "");
  55. // 拼接新的输出根目录地址
  56. const filePath = `${OUTPUT_DIR}/`;
  57. // 创建根目录
  58. fs.mkdirSync(getRootPath(filePath), {
  59. recursive: true,
  60. });
  61. fs.writeFileSync(getRootPath(filePath + configFileName), configStr);
  62. console.log(`✨ 配置文件构建成功:`);
  63. console.log(filePath + "\n");
  64. } catch (error) {
  65. console.log("配置文件配置文件打包失败:\n" + error);
  66. }
  67. }
  68. const runBuild = async () => {
  69. try {
  70. const config = getEnvConfig();
  71. createConfig({
  72. config,
  73. configName: CONFIG_NAME,
  74. configFileName: CONFIG_FILE_NAME,
  75. });
  76. console.log(`环境变量注入成功 - 构建成功!`);
  77. } catch (error) {
  78. console.log("虚拟构建错误:\n" + error);
  79. process.exit(1);
  80. }
  81. };
  82. runBuild();