prepare.js 5.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 7
const yaml = require('yaml-front-matter')
const tempPath = path.resolve(__dirname, 'app/.temp')

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

E
Evan You 已提交
10 11 12 13 14
module.exports = async function prepare (sourceDir) {
  // 1. load options
  const options = await resolveOptions(sourceDir)

  // 2. generate dynamic component registration file
E
tweaks  
Evan You 已提交
15
  const componentCode = await genComponentRegistrationFile(options)
E
Evan You 已提交
16 17

  // 3. generate routes
E
tweaks  
Evan You 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30
  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 已提交
31

32 33 34 35 36 37 38 39 40
  // 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 已提交
41 42 43 44
  return options
}

async function resolveOptions (sourceDir) {
E
Evan You 已提交
45 46
  const vuepressDir = path.resolve(sourceDir, '.vuepress')
  const configPath = path.resolve(vuepressDir, 'config.js')
47 48

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

E
Evan You 已提交
51 52
  // normalize description
  if (siteConfig.description) {
E
Evan You 已提交
53 54 55
    (siteConfig.head || (siteConfig.head = [])).unshift([
      'meta', { name: 'description', content: siteConfig.description }
    ])
E
Evan You 已提交
56 57
  }

E
Evan You 已提交
58
  const options = {
E
Evan You 已提交
59
    siteConfig,
E
Evan You 已提交
60
    sourceDir,
E
Evan You 已提交
61 62 63
    outDir: siteConfig.dest
      ? path.resolve(siteConfig.dest)
      : path.resolve(sourceDir, '.vuepress/dist'),
E
Evan You 已提交
64
    publicPath: siteConfig.base || '/',
E
Evan You 已提交
65 66 67 68
    pageFiles: await globby(['**/*.md', '!.vuepress'], { cwd: sourceDir }),
    pagesData: null,
    themePath: null,
    notFoundPath: null
E
Evan You 已提交
69 70
  }

E
Evan You 已提交
71 72 73 74 75 76
  // resolve theme
  const hasTheme = (
    siteConfig.theme ||
    fs.existsSync(path.resolve(vuepressDir, 'theme'))
  )

E
Evan You 已提交
77 78 79 80 81
  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 已提交
82 83
    // resolve custom theme
    const themeDir = siteConfig.theme
E
Evan You 已提交
84
      ? path.resolve(__dirname, `../../vuepress-theme-${siteConfig.theme}`)
E
Evan You 已提交
85
      : path.resolve(sourceDir, 'theme')
E
Evan You 已提交
86

E
Evan You 已提交
87 88 89 90
    const themePath = path.resolve(themeDir, 'Layout.vue')
    if (fs.existsSync(themePath)) {
      options.themePath = themePath
    } else {
E
Evan You 已提交
91 92 93
      throw new Error(`[vuepress] Cannot resolve Layout.vue file for custom theme${
        siteConfig.theme ? ` "${siteConfig.theme}"` : ``
      }.`)
E
Evan You 已提交
94 95 96 97 98 99
    }

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

E
Evan You 已提交
104 105
  // resolve pages
  const pagesData = options.pageFiles.map(file => {
E
Evan You 已提交
106 107 108
    const urlPath = isIndexFile(file)
      ? '/'
      : `/${file.replace(/\.md$/, '').replace(/\\/g, '/')}.html`
E
Evan You 已提交
109
    const content = fs.readFileSync(path.resolve(sourceDir, file), 'utf-8')
E
tweaks  
Evan You 已提交
110
    const data = {
E
Evan You 已提交
111 112
      path: urlPath
    }
E
Evan You 已提交
113 114

    // extract yaml frontmatter
E
Evan You 已提交
115
    const frontmatter = yaml.loadFront(content)
E
Evan You 已提交
116
    // infer title
E
Evan You 已提交
117
    const titleMatch = frontmatter.__content.trim().match(/^#+\s+(.*)/)
E
Evan You 已提交
118 119 120
    if (titleMatch) {
      data.title = titleMatch[1]
    }
E
Evan You 已提交
121
    delete frontmatter.__content
E
Evan You 已提交
122 123
    if (Object.keys(frontmatter).length) {
      data.frontmatter = frontmatter
E
Evan You 已提交
124
    }
E
tweaks  
Evan You 已提交
125
    return data
E
Evan You 已提交
126 127
  })

E
Evan You 已提交
128
  // resolve site data
E
Evan You 已提交
129
  options.siteData = {
E
Evan You 已提交
130
    title: siteConfig.title,
E
Evan You 已提交
131
    description: siteConfig.description,
E
Evan You 已提交
132
    base: siteConfig.base || '/',
E
Evan You 已提交
133 134 135
    pages: pagesData,
    themeConfig: siteConfig.themeConfig
  }
E
Evan You 已提交
136 137 138 139

  return options
}

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

E
Evan You 已提交
156 157
function toComponentName (file) {
  const isPage = /\.md$/.test(file)
E
Evan You 已提交
158 159 160 161 162 163 164 165 166
  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 已提交
167 168
}

E
Evan You 已提交
169
async function resolveComponents (sourceDir) {
E
Evan You 已提交
170
  const componentDir = path.resolve(sourceDir, '.vuepress/components')
E
Evan You 已提交
171 172 173
  if (!fs.existsSync(componentDir)) {
    return
  }
E
tweaks  
Evan You 已提交
174
  return await globby(['**/*.vue'], { cwd: componentDir })
E
Evan You 已提交
175 176
}

E
Evan You 已提交
177
async function genRoutesFile ({ siteData: { pages }}) {
E
tweaks  
Evan You 已提交
178
  function genRoute ({ path }) {
E
Evan You 已提交
179 180
    const code = `
    {
E
Evan You 已提交
181
      path: ${JSON.stringify(path)},
E
Evan You 已提交
182 183 184 185 186
      component: Theme
    }`
    return code
  }

E
tweaks  
Evan You 已提交
187
  return (
E
Evan You 已提交
188
    `import Theme from '~theme'\n` +
E
tweaks  
Evan You 已提交
189 190
    `export const routes = [${pages.map(genRoute).join(',')}\n]`
  )
E
Evan You 已提交
191
}