aboutsummaryrefslogtreecommitdiff
path: root/node_modules/vuepress/lib/prepare/loadConfig.js
blob: aa913ba013e8dccd1a2fd8a38ce94293e59e44ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const fs = require('fs-extra')
const path = require('path')
const yamlParser = require('js-yaml')
const tomlParser = require('toml')

module.exports = function loadConfig (vuepressDir, bustCache = true) {
  const configPath = path.resolve(vuepressDir, 'config.js')
  const configYmlPath = path.resolve(vuepressDir, 'config.yml')
  const configTomlPath = path.resolve(vuepressDir, 'config.toml')

  if (bustCache) {
    delete require.cache[configPath]
  }

  // resolve siteConfig
  let siteConfig = {}
  if (fs.existsSync(configYmlPath)) {
    siteConfig = parseConfig(configYmlPath)
  } else if (fs.existsSync(configTomlPath)) {
    siteConfig = parseConfig(configTomlPath)
  } else if (fs.existsSync(configPath)) {
    siteConfig = require(configPath)
  }

  return siteConfig
}

function parseConfig (file) {
  const content = fs.readFileSync(file, 'utf-8')
  const [extension] = /.\w+$/.exec(file)
  let data

  switch (extension) {
  case '.yml':
  case '.yaml':
    data = yamlParser.safeLoad(content)
    break

  case '.toml':
    data = tomlParser.parse(content)
    // reformat to match config since TOML does not allow different data type
    // https://github.com/toml-lang/toml#array
    const format = []
    if (data.head) {
      Object.keys(data.head).forEach(meta => {
        data.head[meta].forEach(values => {
          format.push([meta, values])
        })
      })
    }
    data.head = format
    break
  }

  return data || {}
}