prepare.js 7.4 KB
Newer Older
E
Evan You 已提交
1 2 3
const fs = require('fs')
const path = require('path')
const globby = require('globby')
E
Evan You 已提交
4
const mkdirp = require('mkdirp')
E
Evan You 已提交
5 6
const yaml = require('yaml-front-matter')
const tempPath = path.resolve(__dirname, 'app/.temp')
E
Evan You 已提交
7
const { inferTitle, extractHeaders } = require('./util')
E
Evan You 已提交
8

E
Evan You 已提交
9 10
mkdirp(tempPath)

E
Evan You 已提交
11 12 13 14 15 16 17 18 19 20
const tempCache = new Map()
function writeTemp (file, content) {
  // cache write to avoid hitting the dist if it didn't change
  const cached = tempCache.get(file)
  if (cached !== content) {
    fs.writeFileSync(path.join(tempPath, file), content)
    tempCache.set(file, content)
  }
}

E
Evan You 已提交
21 22 23 24
module.exports = async function prepare (sourceDir) {
  // 1. load options
  const options = await resolveOptions(sourceDir)

E
Evan You 已提交
25 26
  // 2. generate routes & user components registration code
  const routesCode = await genRoutesFile(options)
E
tweaks  
Evan You 已提交
27
  const componentCode = await genComponentRegistrationFile(options)
E
Evan You 已提交
28

E
Evan You 已提交
29 30 31 32
  writeTemp('routes.js', [
    componentCode,
    routesCode
  ].join('\n\n'))
E
tweaks  
Evan You 已提交
33

E
Evan You 已提交
34
  // 3. generate siteData
E
tweaks  
Evan You 已提交
35
  const dataCode = `export const siteData = ${JSON.stringify(options.siteData, null, 2)}`
E
Evan You 已提交
36
  writeTemp('siteData.js', dataCode)
E
tweaks  
Evan You 已提交
37

E
Evan You 已提交
38
  // 4. generate basic polyfill if need to support older browsers
39 40 41 42 43 44
  let polyfillCode = ``
  if (!options.siteConfig.evergreen) {
    polyfillCode =
`import 'es6-promise/auto'
if (!Object.assign) Object.assign = require('object-assign')`
  }
E
Evan You 已提交
45
  writeTemp('polyfill.js', polyfillCode)
46

E
Evan You 已提交
47
  // 5. handle user override
E
Evan You 已提交
48
  if (options.useDefaultTheme) {
E
Evan You 已提交
49 50 51
    const overridePath = path.resolve(sourceDir, '.vuepress/override.styl')
    const hasUserOverride = fs.existsSync(overridePath)
    writeTemp(`override.styl`, hasUserOverride ? `@import(${JSON.stringify(overridePath)})` : ``)
E
Evan You 已提交
52 53
  }

E
Evan You 已提交
54 55 56 57
  return options
}

async function resolveOptions (sourceDir) {
E
Evan You 已提交
58 59
  const vuepressDir = path.resolve(sourceDir, '.vuepress')
  const configPath = path.resolve(vuepressDir, 'config.js')
60 61

  delete require.cache[configPath]
E
Evan You 已提交
62
  const siteConfig = fs.existsSync(configPath) ? require(configPath) : {}
E
Evan You 已提交
63

E
Evan You 已提交
64 65
  // normalize description
  if (siteConfig.description) {
E
Evan You 已提交
66 67 68
    (siteConfig.head || (siteConfig.head = [])).unshift([
      'meta', { name: 'description', content: siteConfig.description }
    ])
E
Evan You 已提交
69 70
  }

E
Evan You 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
  // normalize head tag urls for base
  const base = siteConfig.base || '/'
  if (base !== '/' && siteConfig.head) {
    siteConfig.head.forEach(tag => {
      const attrs = tag[1]
      if (attrs) {
        for (const name in attrs) {
          if (name === 'src' || name === 'href') {
            const value = attrs[name]
            if (value.charAt(0) === '/') {
              attrs[name] = base + value.slice(1)
            }
          }
        }
      }
    })
  }

E
Evan You 已提交
89 90 91 92 93 94
  // resolve theme
  const useDefaultTheme = (
    !siteConfig.theme &&
    !fs.existsSync(path.resolve(vuepressDir, 'theme'))
  )

E
Evan You 已提交
95
  const options = {
E
Evan You 已提交
96
    siteConfig,
E
Evan You 已提交
97
    sourceDir,
E
Evan You 已提交
98 99 100
    outDir: siteConfig.dest
      ? path.resolve(siteConfig.dest)
      : path.resolve(sourceDir, '.vuepress/dist'),
E
Evan You 已提交
101
    publicPath: base,
102
    pageFiles: sort(await globby(['**/*.md', '!.vuepress', '!node_modules'], { cwd: sourceDir })),
E
Evan You 已提交
103 104
    pagesData: null,
    themePath: null,
E
Evan You 已提交
105 106
    notFoundPath: null,
    useDefaultTheme
E
Evan You 已提交
107 108
  }

E
Evan You 已提交
109
  if (useDefaultTheme) {
E
Evan You 已提交
110 111 112 113
    // use default theme
    options.themePath = path.resolve(__dirname, 'default-theme/Layout.vue')
    options.notFoundPath = path.resolve(__dirname, 'default-theme/NotFound.vue')
  } else {
E
Evan You 已提交
114 115
    let themeDir
    let themePath
E
Evan You 已提交
116
    // resolve custom theme
E
Evan You 已提交
117 118 119 120 121 122 123 124 125
    if (siteConfig.theme) {
      try {
        themePath = require.resolve(`vuepress-theme-${siteConfig.theme}/Layout.vue`)
        themeDir = path.dirname(themePath)
      } catch (e) {
        throw new Error(`[vuepress] Failed to load custom theme "${
          siteConfig.theme
        }". File vuepress-theme-${siteConfig.theme}/Layout.vue does not exist.`)
      }
E
Evan You 已提交
126
    } else {
E
Evan You 已提交
127 128 129 130 131
      themeDir = path.resolve(vuepressDir, 'theme')
      themePath = path.resolve(themeDir, 'Layout.vue')
      if (!fs.existsSync(themePath)) {
        throw new Error(`[vuepress] Cannot resolve Layout.vue file in .vuepress/theme.`)
      }
E
Evan You 已提交
132
    }
E
Evan You 已提交
133
    options.themePath = themePath
E
Evan You 已提交
134 135 136 137 138

    const notFoundPath = path.resolve(themeDir, '/NotFound.vue')
    if (fs.existsSync(notFoundPath)) {
      options.notFoundPath = notFoundPath
    } else {
E
Evan You 已提交
139
      options.notFoundPath = path.resolve(__dirname, 'default-theme/NotFound.vue')
E
Evan You 已提交
140
    }
E
tweaks  
Evan You 已提交
141 142
  }

E
Evan You 已提交
143 144
  // resolve pages
  const pagesData = options.pageFiles.map(file => {
E
tweaks  
Evan You 已提交
145
    const data = {
E
Evan You 已提交
146
      path: fileToPath(file)
E
Evan You 已提交
147
    }
E
Evan You 已提交
148 149

    // extract yaml frontmatter
E
Evan You 已提交
150
    const content = fs.readFileSync(path.resolve(sourceDir, file), 'utf-8')
E
Evan You 已提交
151
    const frontmatter = yaml.loadFront(content)
E
Evan You 已提交
152
    // infer title
E
Evan You 已提交
153 154 155
    const title = inferTitle(frontmatter)
    if (title) {
      data.title = title
E
Evan You 已提交
156
    }
E
Evan You 已提交
157 158 159 160
    const headers = extractHeaders(frontmatter.__content, ['h2', 'h3'])
    if (headers.length) {
      data.headers = headers
    }
E
Evan You 已提交
161
    delete frontmatter.__content
E
Evan You 已提交
162 163
    if (Object.keys(frontmatter).length) {
      data.frontmatter = frontmatter
E
Evan You 已提交
164
    }
E
tweaks  
Evan You 已提交
165
    return data
E
Evan You 已提交
166 167
  })

E
Evan You 已提交
168
  // resolve site data
E
Evan You 已提交
169
  options.siteData = {
E
Evan You 已提交
170 171
    title: siteConfig.title || '',
    description: siteConfig.description || '',
E
Evan You 已提交
172
    base: siteConfig.base || '/',
E
Evan You 已提交
173
    pages: pagesData,
E
Evan You 已提交
174
    themeConfig: siteConfig.themeConfig || {}
E
Evan You 已提交
175
  }
E
Evan You 已提交
176 177 178 179

  return options
}

E
Evan You 已提交
180
async function genComponentRegistrationFile ({ sourceDir }) {
E
Evan You 已提交
181
  function genImport (file) {
E
Evan You 已提交
182
    const name = fileToComponentName(file)
E
Evan You 已提交
183
    const baseDir = path.resolve(sourceDir, '.vuepress/components')
E
Evan You 已提交
184 185 186 187 188
    const absolutePath = path.resolve(baseDir, file)
    const code = `Vue.component(${JSON.stringify(name)}, () => import(${JSON.stringify(absolutePath)}))`
    return code
  }
  const components = (await resolveComponents(sourceDir)) || []
E
Evan You 已提交
189
  return `import Vue from 'vue'\n` + components.map(genImport).join('\n')
E
Evan You 已提交
190 191
}

192
const indexRE = /\b(index|readme)\.md$/i
E
Evan You 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
const extRE = /\.(vue|md)$/

function fileToPath (file) {
  if (isIndexFile(file)) {
    // README.md -> /
    // foo/README.md -> /foo/
    return '/' + file.replace(indexRE, '')
  } else {
    // foo.md -> /foo.html
    // foo/bar.md -> /foo/bar.html
    return `/${file.replace(extRE, '').replace(/\\/g, '/')}.html`
  }
}

function fileToComponentName (file) {
  let normalizedName = file
    .replace(/\/|\\/g, '-')
    .replace(extRE, '')
  if (isIndexFile(file)) {
    normalizedName = normalizedName.replace(/readme$/i, 'index')
  }
  const pagePrefix = /\.md$/.test(file) ? `page-` : ``
  return `${pagePrefix}${normalizedName}`
E
Evan You 已提交
216 217 218
}

function isIndexFile (file) {
E
Evan You 已提交
219
  return indexRE.test(file)
E
Evan You 已提交
220 221
}

E
Evan You 已提交
222
async function resolveComponents (sourceDir) {
E
Evan You 已提交
223
  const componentDir = path.resolve(sourceDir, '.vuepress/components')
E
Evan You 已提交
224 225 226
  if (!fs.existsSync(componentDir)) {
    return
  }
E
Evan You 已提交
227
  return sort(await globby(['**/*.vue'], { cwd: componentDir }))
E
Evan You 已提交
228 229
}

E
Evan You 已提交
230 231 232 233
async function genRoutesFile ({ siteData: { pages }, sourceDir, pageFiles }) {
  function genRoute ({ path: pagePath }, index) {
    const file = pageFiles[index]
    const filePath = path.resolve(sourceDir, file)
E
Evan You 已提交
234 235
    const code = `
    {
E
Evan You 已提交
236 237 238 239 240 241 242 243
      path: ${JSON.stringify(pagePath)},
      component: Theme,
      beforeEnter: (to, from, next) => {
        import(${JSON.stringify(filePath)}).then(comp => {
          Vue.component(${JSON.stringify(fileToComponentName(file))}, comp.default)
          next()
        })
      }
E
Evan You 已提交
244 245 246 247
    }`
    return code
  }

E
tweaks  
Evan You 已提交
248
  return (
E
Evan You 已提交
249
    `import Theme from '~theme'\n` +
E
tweaks  
Evan You 已提交
250 251
    `export const routes = [${pages.map(genRoute).join(',')}\n]`
  )
E
Evan You 已提交
252
}
E
Evan You 已提交
253 254 255 256 257 258 259 260

function sort (arr) {
  return arr.sort((a, b) => {
    if (a < b) return -1
    if (a > b) return 1
    return 0
  })
}