1 | const fs = require('fs')
|
2 | const tildify = require('tildify')
|
3 | const chalk = require('chalk')
|
4 | const merge = require('lodash.merge')
|
5 | const cosmiconfig = require('cosmiconfig')
|
6 | const AppError = require('./app-error')
|
7 | const { cwd, getConfigFile } = require('./utils')
|
8 |
|
9 | module.exports = function (options) {
|
10 | if (options.config === false) {
|
11 | return Promise.resolve()
|
12 | }
|
13 |
|
14 | const configFile = getConfigFile(options.config)
|
15 | const useConfig = fs.existsSync(configFile) ? configFile : null
|
16 | return cosmiconfig('poi', { cache: false, argv: false })
|
17 | .load(cwd(options.cwd), useConfig)
|
18 | .then(result => {
|
19 | if (result && result.filepath) {
|
20 | console.log(`> Using external Poi config file`)
|
21 | console.log(chalk.dim(`> location: "${tildify(result.filepath)}"`))
|
22 | return handleConfig(result.config, options)
|
23 | }
|
24 | })
|
25 | .catch(err => {
|
26 | if (err.code === 'ENOENT') {
|
27 |
|
28 | if (options.config) {
|
29 | throw new AppError(`Config file was not found!\n\n${err.message}`)
|
30 | }
|
31 | } else {
|
32 | throw new AppError(err.message)
|
33 | }
|
34 | })
|
35 | }
|
36 |
|
37 | function handleConfig(config, options) {
|
38 | if (typeof config === 'function') {
|
39 | config = config(options, require)
|
40 | }
|
41 |
|
42 | config = merge(config, config[options.mode])
|
43 |
|
44 | delete config.development
|
45 | delete config.production
|
46 | delete config.watch
|
47 | delete config.test
|
48 |
|
49 | return config
|
50 | }
|