UNPKG

1.75 kBJavaScriptView Raw
1const fs = require('fs-extra')
2const getPathnameProjectConfigFile = require('./get-pathname-project-config-file')
3
4/**
5 * 从项目配置中读取对应配置项的内容
6 *
7 * 项目配置:在 0.6 之前为 koot.js,0.6 之后为自动生成的临时配置文件
8 * - 使用临时配置文件是为了兼容 0.6 之前的行为
9 * - TODO: 在未来可能会抛弃独立配置文件行为,界时该方法会改写
10 *
11 * @async
12 * @param {String} key
13 * @returns {*}
14 */
15module.exports = async (key) => {
16 const pathnameKootJS = getPathnameProjectConfigFile()
17
18 try {
19 const config = require(pathnameKootJS)
20 return config[key]
21 } catch (e) { }
22
23 const content = await fs.readFile(pathnameKootJS, 'utf-8')
24
25 {
26 const regex = new RegExp(`${key}[ ]*=[ ]*['"](.+?)['"]`, "gm")
27 const matches = regex.exec(content)
28 if (Array.isArray(matches) && matches.length > 1)
29 return matches[1]
30 }
31
32 {
33 const regex = new RegExp(`${key}[ ]*=[ ]*{(.+?)}`, "gm")
34 const matches = regex.exec(content)
35 if (Array.isArray(matches) && matches.length > 1) {
36 try {
37 return JSON.parse(`{${matches[1]}}`)
38 } catch (e) {
39 const c = matches[1]
40 .replace(/([: ])require\(['"](.+?)['"]\)\.(\w+?)([}, ])/g, '$1"$2:$3"$4')
41 .replace(/([: ])require\(['"](.+?)['"]\)\.(\w+?)$/g, '$1"$2:$3"')
42 .replace(/([: ])require\(['"](.+?)['"]\)([}, ])/g, '$1"$2"$3')
43 .replace(/([: ])require\(['"](.+?)['"]\)$/g, '$1"$2"')
44 return JSON.parse(`{${c}}`)
45 }
46 }
47 }
48
49 return undefined
50}