yyb
21 小时以前 5470429a79313630a7ddef601de1d89e7dada754
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import fs from "fs/promises";
import fsSync from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { execSync } from "child_process";
 
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
 
const data = await fs.readFile(path.join(__dirname, "config.json"), "utf-8");
const config = JSON.parse(data);
 
const rootPath = path.resolve(__dirname, "..");
const resourcePath = path.join(rootPath, "multiple", "assets");
const replacePath = path.join(rootPath, "replace");
const envFilePath = path.join(rootPath, ".env.production.local");
 
const params = parseArgs(process.argv);
const company = resolveCompany(params);
const companyMap = config[company];
 
if (!companyMap) {
  const availableCompanies = Object.entries(config)
    .filter(([, value]) => value && typeof value === "object" && value.env)
    .map(([key]) => key)
    .sort();
  throw new Error(
    `未知 company: "${company}"。可选值: ${availableCompanies.join(", ")}`
  );
}
 
console.log(`当前 company: ${company}`);
 
async function copyFileWithOverwrite(src, dest) {
  await fs.mkdir(path.dirname(dest), { recursive: true });
  if (fsSync.existsSync(dest)) {
    try {
      await fs.chmod(dest, 0o666);
    } catch {
      // Ignore chmod failure and continue.
    }
    await fs.rm(dest, { force: true });
  }
  await fs.copyFile(src, dest);
}
 
try {
  console.log("=======生成.env=======");
  const envContent =
    Object.entries(companyMap.env)
      .map(([key, value]) => `${key}='${value}'`)
      .join("\n") + "\n";
  await fs.writeFile(envFilePath, envContent, "utf-8");
 
  console.log("=======修改资源=======");
  for (const [key] of Object.entries(companyMap)) {
    if (key === "env") continue;
 
    const originFile = path.join(rootPath, config[key]);
    const backupFile = path.join(replacePath, config[key]);
    const replaceFile = path.join(resourcePath, companyMap[key]);
 
    await copyFileWithOverwrite(originFile, backupFile);
    await copyFileWithOverwrite(replaceFile, originFile);
  }
 
  console.log("=====开始打包=====");
  const buildEnv = createBuildEnv(companyMap.env);
  execSync("vite build", { stdio: "inherit", cwd: rootPath, env: buildEnv });
  console.log("=====打包完成======");
} finally {
  console.log("=====恢复资源======");
 
  if (fsSync.existsSync(envFilePath)) {
    await fs.unlink(envFilePath);
    console.log(`🗑️ 已删除 ${envFilePath}`);
  }
 
  if (fsSync.existsSync(replacePath)) {
    for (const [key] of Object.entries(companyMap)) {
      if (key === "env") continue;
 
      const originFile = path.join(rootPath, config[key]);
      const backupFile = path.join(replacePath, config[key]);
      await copyFileWithOverwrite(backupFile, originFile);
    }
    await fs.rm(replacePath, { recursive: true, force: true });
    console.log(`🗑️ 已删除 ${replacePath}`);
  }
}
 
function parseArgs(argv) {
  const params = {};
  for (let index = 2; index < argv.length; index++) {
    const arg = argv[index];
    if (!arg.startsWith("--")) continue;
 
    const normalized = arg.slice(2);
    const equalIndex = normalized.indexOf("=");
    if (equalIndex >= 0) {
      const key = normalized.slice(0, equalIndex);
      const value = normalized.slice(equalIndex + 1);
      params[key] = value || true;
      continue;
    }
 
    const nextArg = argv[index + 1];
    if (nextArg && !nextArg.startsWith("--")) {
      params[normalized] = nextArg;
      index += 1;
      continue;
    }
 
    params[normalized] = true;
  }
  return params;
}
 
function resolveCompany(parsedParams) {
  const fromArg = parseValue(parsedParams.company);
  if (fromArg) return fromArg;
 
  const fromNpmConfig = parseValue(process.env.npm_config_company);
  if (fromNpmConfig) return fromNpmConfig;
 
  const fromEnv = parseValue(process.env.COMPANY ?? process.env.company);
  if (fromEnv) return fromEnv;
 
  return "default";
}
 
function parseValue(value) {
  if (value == null || value === true) return undefined;
  if (typeof value !== "string") return undefined;
  const trimmed = value.trim();
  if (!trimmed) return undefined;
  return trimmed.replace(/^["']|["']$/g, "");
}
 
function createBuildEnv(companyEnv) {
  const env = { ...process.env };
  for (const key of Object.keys(env)) {
    if (key.startsWith("VITE_")) {
      delete env[key];
    }
  }
  return {
    ...env,
    ...companyEnv,
    VITE_APP_ENV: "production",
  };
}