vben
authored
5 years ago
1
2
3
/**
* Generate additional configuration files when used for packaging. The file can be configured with some global variables, so that it can be changed directly externally without repackaging
*/
vben
authored
4 years ago
4
import { GLOB_CONFIG_FILE_NAME, OUTPUT_DIR } from '../constant';
nebv
authored
5 years ago
5
import fs, { writeFileSync } from 'fs-extra';
vben
authored
3 years ago
6
import colors from 'picocolors';
nebv
authored
5 years ago
7
8
import { getEnvConfig, getRootPath } from '../utils';
Vben
authored
4 years ago
9
import { getConfigFileName } from '../getConfigFileName';
nebv
authored
5 years ago
10
vben
authored
4 years ago
11
12
import pkg from '../../package.json';
13
14
15
16
17
18
interface CreateConfigParams {
configName: string;
config: any;
configFileName?: string;
}
19
20
function createConfig(params: CreateConfigParams) {
const { configName, config, configFileName } = params;
nebv
authored
5 years ago
21
22
try {
const windowConf = `window.${configName}`;
vben
authored
5 years ago
23
// Ensure that the variable will not be modified
24
25
let configStr = `${windowConf}=${JSON.stringify(config)};`;
configStr += `
nebv
authored
5 years ago
26
27
28
29
30
Object.freeze(${windowConf});
Object.defineProperty(window, "${configName}", {
configurable: false,
writable: false,
});
vben
authored
4 years ago
31
`.replace(/\s/g, '');
32
Vben
authored
4 years ago
33
34
fs.mkdirp(getRootPath(OUTPUT_DIR));
writeFileSync(getRootPath(`${OUTPUT_DIR}/${configFileName}`), configStr);
nebv
authored
5 years ago
35
vben
authored
3 years ago
36
37
console.log(colors.cyan(`✨ [${pkg.name}]`) + ` - configuration file is build successfully:`);
console.log(colors.gray(OUTPUT_DIR + '/' + colors.green(configFileName)) + '\n');
nebv
authored
5 years ago
38
} catch (error) {
vben
authored
3 years ago
39
console.log(colors.red('configuration file configuration file failed to package:\n' + error));
nebv
authored
5 years ago
40
41
42
43
44
}
}
export function runBuildConfig() {
const config = getEnvConfig();
Vben
authored
4 years ago
45
const configFileName = getConfigFileName(config);
46
createConfig({ config, configName: configFileName, configFileName: GLOB_CONFIG_FILE_NAME });
nebv
authored
5 years ago
47
}