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
4 years ago
6
import chalk from 'chalk';
nebv
authored
5 years ago
7
Vben
authored
4 years ago
8
9
import { getRootPath, getEnvConfig } from '../utils';
import { getConfigFileName } from '../getConfigFileName';
nebv
authored
5 years ago
10
vben
authored
4 years ago
11
12
import pkg from '../../package.json';
nebv
authored
5 years ago
13
14
15
16
17
18
19
20
21
function createConfig(
{
configName,
config,
configFileName = GLOB_CONFIG_FILE_NAME,
}: { configName: string; config: any; configFileName?: string } = { configName: '', config: {} }
) {
try {
const windowConf = `window.${configName}`;
vben
authored
5 years ago
22
// Ensure that the variable will not be modified
nebv
authored
5 years ago
23
24
25
26
27
28
const configStr = `${windowConf}=${JSON.stringify(config)};
Object.freeze(${windowConf});
Object.defineProperty(window, "${configName}", {
configurable: false,
writable: false,
});
vben
authored
4 years ago
29
`.replace(/\s/g, '');
Vben
authored
4 years ago
30
31
fs.mkdirp(getRootPath(OUTPUT_DIR));
writeFileSync(getRootPath(`${OUTPUT_DIR}/${configFileName}`), configStr);
nebv
authored
5 years ago
32
vben
authored
4 years ago
33
34
console.log(chalk.cyan(`✨ [${pkg.name}]`) + ` - configuration file is build successfully:`);
console.log(chalk.gray(OUTPUT_DIR + '/' + chalk.green(configFileName)) + '\n');
nebv
authored
5 years ago
35
} catch (error) {
vben
authored
4 years ago
36
console.log(chalk.red('configuration file configuration file failed to package:\n' + error));
nebv
authored
5 years ago
37
38
39
40
41
}
}
export function runBuildConfig() {
const config = getEnvConfig();
Vben
authored
4 years ago
42
const configFileName = getConfigFileName(config);
nebv
authored
5 years ago
43
44
createConfig({ config, configName: configFileName });
}