gaoluyang
13 小时以前 f3f9035ef93b7267e8c346b84e47a0f1382abf62
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
import fs from 'fs/promises';
import fsSync from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { execSync } from "child_process";
 
// 获取 __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
 
// 读取 JSON 配置
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 params = parseArgs(process.argv);
const company = params["company"] ?? "default";
const companyMap = config[company];
 
const envFilePath = path.join(process.cwd(), '.env.production.local');
 
try {
    // 1️⃣ 生成 .env
    console.log("=======生成.env=======");
    const envContent = Object.entries(companyMap.env)
        .map(([key, value]) => `${key}='${value}'`)
        .join('\n') + '\n';
    await fs.writeFile(envFilePath, envContent, 'utf-8');
 
    // 2️⃣ 备份原始资源并替换
    console.log("=======修改资源=======");
    for (const [key, value] 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 fs.mkdir(path.dirname(backupFile), { recursive: true });
        await fs.copyFile(originFile, backupFile);
        await fs.copyFile(replaceFile, originFile);
    }
 
    console.log("=====开始打包======");
    execSync("vite build", { stdio: "inherit" });
    console.log("=====打包完成======");
} finally {
    console.log("=====恢复资源======");
 
    // 删除临时 .env 文件
    if (fsSync.existsSync(envFilePath)) {
        await fs.unlink(envFilePath);
        console.log(`🗑️ 已删除 ${envFilePath}`);
    }
 
    // 恢复资源文件
    if (fsSync.existsSync(replacePath)) {
        for (const [key, value] of Object.entries(companyMap)) {
            if (key === 'env') continue;
 
            const originFile = path.join(rootPath, config[key]);
            const backupFile = path.join(replacePath, config[key]);
 
            await fs.copyFile(backupFile, originFile);
        }
        await fs.rm(replacePath, { recursive: true, force: true });
        console.log(`🗑️ 已删除 ${replacePath}`);
    }
}
 
// 简单命令行参数解析
function parseArgs(argv) {
    const params = {};
    for (const arg of argv.slice(2)) {
        if (arg.startsWith('--')) {
            const [key, value] = arg.slice(2).split('=');
            params[key] = value ?? true;
        }
    }
    return params;
}