UNPKG

2.96 kBJavaScriptView Raw
1///@ts-check
2'use strict';
3// 加载配置
4
5var fs = require('fs');
6// var minify = require('node-json-minify');
7var colors = require('ansi-colors');
8var json5 = require('json5');
9
10var log = require('./log/logger');
11
12var TITLE = colors.gray('config:');
13
14var DEFAULT_CONFIG_FILES = [
15 'mpconfig.json',
16 'mpconfig.jsonc',
17 '.mpconfig.json',
18 '.mpconfig.jsonc',
19]
20
21const CACHE = {}
22
23/**
24 * 读取配置
25 * @param {string|any} configFile
26 */
27function loadConfig(configFile) {
28 if (CACHE[configFile]) {
29 return CACHE[configFile];
30 }
31 if (configFile) {
32 if (!fs.existsSync(configFile)) {
33 log.error(TITLE, colors.red.underline(configFile), colors.bgRed('does not exist'));
34 throw new Error(configFile + 'does not exist');
35 }
36 }
37 try {
38 var json = fs.readFileSync(configFile, 'utf-8');
39 var config = json5.parse(json);
40 // @ts-ignore
41 const version = require('../package.json').version;
42 log.info(TITLE, colors.cyan.italic(`v${version}`), 'load config', colors.blue.underline(configFile))
43 const allowedKeys = Object.keys(exports.default);
44
45 config = Object.keys(config)
46 .filter(key => allowedKeys.indexOf(key) >= 0)
47 .reduce((obj, key) => { obj[key] = config[key]; return obj }, {})
48 CACHE[configFile] = config;
49 return config;
50 } catch (ex) {
51 log.error(TITLE, colors.red.underline(configFile), 'failed to load.', colors.red(ex));
52 // process.exit(1);
53 throw ex;
54 }
55}
56
57/**
58 * 自动读取配置
59 */
60function autoLoad() {
61 // try load default configure file
62 for (var index = 0; index < DEFAULT_CONFIG_FILES.length; index++) {
63 if (fs.existsSync(DEFAULT_CONFIG_FILES[index])) {
64 return loadConfig(DEFAULT_CONFIG_FILES[index]);
65 }
66 }
67 return {}
68};
69/**
70 * 生成配置文件
71 * @param {object} conf
72 * @param {string} [file] 默认 '.mpconfig.jsonc'
73 */
74function saveConfig(conf, file) {
75 file = file || '.mpconfig.jsonc';
76 if (fs.existsSync(file)) {
77 log.error(TITLE, colors.red('file (' + file + ') already exists!'), 'Please delete it to regenerate.')
78 log.error(TITLE, colors.red('配置文件 (' + file + ') 已存在!'), '可删除后重新生成。')
79 } else {
80 conf.$schema = 'https://miniprogram-build.newfuture.cc/config.schema.json';
81 const str = JSON.stringify(conf, undefined, 4);
82 fs.writeFileSync(file, str);
83 log.info(TITLE, colors.green('file `' + file + '` is generated!'))
84 log.info(TITLE, colors.green('配置文件 `' + file + '` 已生成!'))
85 }
86}
87
88module.exports.load = loadConfig;
89module.exports.save = saveConfig;
90module.exports.auto = autoLoad;
91
92/**
93 * 全局配置
94 */
95module.exports.default = {
96 // debug: true,
97 release: false,
98 src: 'src',
99 dist: 'dist',
100 assets: 'assets',
101 exclude: [],
102 copy: '',
103 tsconfig: '',
104 var: {
105 }
106};
\No newline at end of file