prepare.js 5.2 KB
Newer Older
E
Evan You 已提交
1 2 3 4 5 6 7 8 9 10 11
const fs = require('fs')
const path = require('path')
const globby = require('globby')
const yaml = require('yaml-front-matter')
const tempPath = path.resolve(__dirname, 'app/.temp')

module.exports = async function prepare (sourceDir) {
  // 1. load options
  const options = await resolveOptions(sourceDir)

  // 2. generate dynamic component registration file
E
tweaks  
Evan You 已提交
12
  const componentCode = await genComponentRegistrationFile(options)
E
Evan You 已提交
13 14

  // 3. generate routes
E
tweaks  
Evan You 已提交
15 16 17 18 19 20 21 22 23 24 25 26 27
  const routesCode = await genRoutesFile(options)

  // 4. generate siteData
  const dataCode = `export const siteData = ${JSON.stringify(options.siteData, null, 2)}`

  fs.writeFileSync(
    path.join(tempPath, 'siteData.js'),
    [
      componentCode,
      routesCode,
      dataCode
    ].join('\n\n')
  )
E
Evan You 已提交
28

29 30 31 32 33 34 35 36 37
  // 5. generate basic polyfill if need to support older browsers
  let polyfillCode = ``
  if (!options.siteConfig.evergreen) {
    polyfillCode =
`import 'es6-promise/auto'
if (!Object.assign) Object.assign = require('object-assign')`
  }
  fs.writeFileSync(path.join(tempPath, 'polyfill.js'), polyfillCode)

E
Evan You 已提交
38 39 40 41
  return options
}

async function resolveOptions (sourceDir) {
E
Evan You 已提交
42 43 44
  const vuepressDir = path.resolve(sourceDir, '.vuepress')
  const configPath = path.resolve(vuepressDir, 'config.js')
  const siteConfig = fs.existsSync(configPath) ? require(configPath) : {}
E
Evan You 已提交
45

E
Evan You 已提交
46 47 48 49 50 51 52 53
  // normalize description
  if (siteConfig.description) {
    (siteConfig.head || (siteConfig.head = [])).unshift({
      tag: 'meta',
      attrs: { name: 'description', content: siteConfig.description }
    })
  }

E
Evan You 已提交
54
  const options = {
E
Evan You 已提交
55
    siteConfig,
E
Evan You 已提交
56
    sourceDir,
E
Evan You 已提交
57 58 59
    outDir: siteConfig.dest
      ? path.resolve(siteConfig.dest)
      : path.resolve(sourceDir, '.vuepress/dist'),
E
Evan You 已提交
60
    publicPath: siteConfig.base || '/',
E
Evan You 已提交
61
    pageFiles: await globby(['**/*.md', '!.vuepress'], { cwd: sourceDir })
E
Evan You 已提交
62 63
  }

E
Evan You 已提交
64 65 66 67 68 69
  // resolve theme
  const hasTheme = (
    siteConfig.theme ||
    fs.existsSync(path.resolve(vuepressDir, 'theme'))
  )

E
Evan You 已提交
70 71 72 73 74
  if (!hasTheme) {
    // 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 已提交
75 76
    // resolve custom theme
    const themeDir = siteConfig.theme
E
Evan You 已提交
77
      ? path.resolve(__dirname, `../../vuepress-theme-${siteConfig.theme}`)
E
Evan You 已提交
78
      : path.resolve(sourceDir, 'theme')
E
Evan You 已提交
79

E
Evan You 已提交
80 81 82 83
    const themePath = path.resolve(themeDir, 'Layout.vue')
    if (fs.existsSync(themePath)) {
      options.themePath = themePath
    } else {
E
Evan You 已提交
84 85 86
      throw new Error(`[vuepress] Cannot resolve Layout.vue file for custom theme${
        siteConfig.theme ? ` "${siteConfig.theme}"` : ``
      }.`)
E
Evan You 已提交
87 88 89 90 91 92
    }

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

E
Evan You 已提交
97 98
  // resolve pages
  const pagesData = options.pageFiles.map(file => {
E
Evan You 已提交
99 100 101
    const urlPath = isIndexFile(file)
      ? '/'
      : `/${file.replace(/\.md$/, '').replace(/\\/g, '/')}.html`
E
Evan You 已提交
102
    const content = fs.readFileSync(path.resolve(sourceDir, file), 'utf-8')
E
tweaks  
Evan You 已提交
103
    const data = {
E
Evan You 已提交
104 105
      path: urlPath
    }
E
Evan You 已提交
106 107

    // extract yaml frontmatter
E
Evan You 已提交
108
    const frontmatter = yaml.loadFront(content)
E
Evan You 已提交
109
    // infer title
E
Evan You 已提交
110
    const titleMatch = frontmatter.__content.trim().match(/^#+\s+(.*)/)
E
Evan You 已提交
111 112 113
    if (titleMatch) {
      data.title = titleMatch[1]
    }
E
Evan You 已提交
114
    delete frontmatter.__content
E
Evan You 已提交
115 116
    if (Object.keys(frontmatter).length) {
      data.frontmatter = frontmatter
E
Evan You 已提交
117
    }
E
tweaks  
Evan You 已提交
118
    return data
E
Evan You 已提交
119 120
  })

E
Evan You 已提交
121
  // resolve site data
E
Evan You 已提交
122
  options.siteData = {
E
Evan You 已提交
123
    title: siteConfig.title,
E
Evan You 已提交
124
    description: siteConfig.description,
E
Evan You 已提交
125
    base: siteConfig.base || '/',
E
Evan You 已提交
126 127 128
    pages: pagesData,
    themeConfig: siteConfig.themeConfig
  }
E
Evan You 已提交
129 130 131 132

  return options
}

E
Evan You 已提交
133
async function genComponentRegistrationFile ({ sourceDir, pageFiles }) {
E
Evan You 已提交
134 135 136 137
  function genImport (file) {
    const name = toComponentName(file)
    const baseDir = /\.md$/.test(file)
      ? sourceDir
E
Evan You 已提交
138
      : path.resolve(sourceDir, '.vuepress/components')
E
Evan You 已提交
139 140 141 142 143 144
    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 已提交
145
  const all = [...pageFiles, ...components]
E
tweaks  
Evan You 已提交
146
  return `import Vue from 'vue'\n` + all.map(genImport).join('\n')
E
Evan You 已提交
147 148
}

E
Evan You 已提交
149 150
function toComponentName (file) {
  const isPage = /\.md$/.test(file)
E
Evan You 已提交
151 152 153 154 155 156 157 158 159
  const isIndex = isIndexFile(file)
  const normalizedName = isIndex
    ? 'index'
    : file.replace(/\.(vue|md)$/, '').replace(/\/|\\/g, '-')
  return isPage ? `page-${normalizedName}` : normalizedName
}

function isIndexFile (file) {
  return /^(index|readme)\.md$/i.test(file)
E
Evan You 已提交
160 161
}

E
Evan You 已提交
162
async function resolveComponents (sourceDir) {
E
Evan You 已提交
163
  const componentDir = path.resolve(sourceDir, '.vuepress/components')
E
Evan You 已提交
164 165 166
  if (!fs.existsSync(componentDir)) {
    return
  }
E
tweaks  
Evan You 已提交
167
  return await globby(['**/*.vue'], { cwd: componentDir })
E
Evan You 已提交
168 169
}

E
Evan You 已提交
170
async function genRoutesFile ({ siteData: { pages }}) {
E
tweaks  
Evan You 已提交
171
  function genRoute ({ path }) {
E
Evan You 已提交
172 173
    const code = `
    {
E
Evan You 已提交
174
      path: ${JSON.stringify(path)},
E
Evan You 已提交
175 176 177 178 179
      component: Theme
    }`
    return code
  }

E
tweaks  
Evan You 已提交
180
  return (
E
Evan You 已提交
181
    `import Theme from '~theme'\n` +
E
tweaks  
Evan You 已提交
182 183
    `export const routes = [${pages.map(genRoute).join(',')}\n]`
  )
E
Evan You 已提交
184
}