1 |
|
2 | 'use strict';
|
3 |
|
4 |
|
5 | var fs = require('fs');
|
6 |
|
7 | var colors = require('ansi-colors');
|
8 | var json5 = require('json5');
|
9 |
|
10 | var log = require('./log/logger');
|
11 |
|
12 | var TITLE = colors.gray('config:');
|
13 |
|
14 | var DEFAULT_CONFIG_FILES = [
|
15 | 'mpconfig.json',
|
16 | 'mpconfig.jsonc',
|
17 | '.mpconfig.json',
|
18 | '.mpconfig.jsonc',
|
19 | ]
|
20 |
|
21 | const CACHE = {}
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | function 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 |
|
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 |
|
53 | throw ex;
|
54 | }
|
55 | }
|
56 |
|
57 |
|
58 |
|
59 |
|
60 | function autoLoad() {
|
61 |
|
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 |
|
72 |
|
73 |
|
74 | function 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 |
|
88 | module.exports.load = loadConfig;
|
89 | module.exports.save = saveConfig;
|
90 | module.exports.auto = autoLoad;
|
91 |
|
92 |
|
93 |
|
94 |
|
95 | module.exports.default = {
|
96 |
|
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 |