prepare.js 4.8 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 46

  const options = {
E
Evan You 已提交
47
    siteConfig,
E
Evan You 已提交
48
    sourceDir,
E
Evan You 已提交
49 50 51
    outDir: siteConfig.dest
      ? path.resolve(siteConfig.dest)
      : path.resolve(sourceDir, '.vuepress/dist'),
E
Evan You 已提交
52 53
    publicPath: siteConfig.baseUrl || '/',
    pageFiles: await globby(['**/*.md', '!.vuepress'], { cwd: sourceDir })
E
Evan You 已提交
54 55
  }

E
Evan You 已提交
56 57 58 59 60 61
  // resolve theme
  const hasTheme = (
    siteConfig.theme ||
    fs.existsSync(path.resolve(vuepressDir, 'theme'))
  )

E
Evan You 已提交
62 63 64 65 66
  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 已提交
67 68 69 70
    // resolve custom theme
    const themeDir = siteConfig.theme
      ? path.resolve(__dirname, `../../${siteConfig.theme}`)
      : path.resolve(sourceDir, 'theme')
E
Evan You 已提交
71

E
Evan You 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84
    const themePath = path.resolve(themeDir, 'Layout.vue')
    if (fs.existsSync(themePath)) {
      options.themePath = themePath
    } else {
      throw new Error('[vuepress] Custom theme must have a Layout.vue file.')
    }

    const notFoundPath = path.resolve(themeDir, '/NotFound.vue')
    if (fs.existsSync(notFoundPath)) {
      options.notFoundPath = notFoundPath
    } else {
      throw new Error('[vuepress] Custom theme must have a NotFound.vue file.')
    }
E
tweaks  
Evan You 已提交
85 86
  }

E
Evan You 已提交
87 88
  // resolve pages
  const pagesData = options.pageFiles.map(file => {
E
Evan You 已提交
89 90 91
    const urlPath = isIndexFile(file)
      ? '/'
      : `/${file.replace(/\.md$/, '').replace(/\\/g, '/')}.html`
E
Evan You 已提交
92
    const content = fs.readFileSync(path.resolve(sourceDir, file), 'utf-8')
E
tweaks  
Evan You 已提交
93
    const data = {
E
Evan You 已提交
94 95
      path: urlPath
    }
E
Evan You 已提交
96 97

    // extract yaml frontmatter
E
Evan You 已提交
98
    const frontmatter = yaml.loadFront(content)
E
Evan You 已提交
99 100 101 102 103
    // infer title
    const titleMatch = frontmatter.__content.match(/^#+\s+(.*)/)
    if (titleMatch) {
      data.title = titleMatch[1]
    }
E
Evan You 已提交
104
    delete frontmatter.__content
E
Evan You 已提交
105 106
    if (Object.keys(frontmatter).length) {
      data.frontmatter = frontmatter
E
Evan You 已提交
107
    }
E
tweaks  
Evan You 已提交
108
    return data
E
Evan You 已提交
109 110
  })

E
Evan You 已提交
111 112
  // resolve site data
  options.siteData = Object.assign({}, siteConfig.data, {
E
Evan You 已提交
113 114 115 116 117 118
    pages: pagesData
  })

  return options
}

E
Evan You 已提交
119
async function genComponentRegistrationFile ({ sourceDir, pageFiles }) {
E
Evan You 已提交
120 121 122 123
  function genImport (file) {
    const name = toComponentName(file)
    const baseDir = /\.md$/.test(file)
      ? sourceDir
E
Evan You 已提交
124
      : path.resolve(sourceDir, '.vuepress/components')
E
Evan You 已提交
125 126 127 128 129 130
    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 已提交
131
  const all = [...pageFiles, ...components]
E
tweaks  
Evan You 已提交
132
  return `import Vue from 'vue'\n` + all.map(genImport).join('\n')
E
Evan You 已提交
133 134
}

E
Evan You 已提交
135 136
function toComponentName (file) {
  const isPage = /\.md$/.test(file)
E
Evan You 已提交
137 138 139 140 141 142 143 144 145
  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 已提交
146 147
}

E
Evan You 已提交
148
async function resolveComponents (sourceDir) {
E
Evan You 已提交
149
  const componentDir = path.resolve(sourceDir, '.vuepress/components')
E
Evan You 已提交
150 151 152
  if (!fs.existsSync(componentDir)) {
    return
  }
E
tweaks  
Evan You 已提交
153
  return await globby(['**/*.vue'], { cwd: componentDir })
E
Evan You 已提交
154 155
}

E
Evan You 已提交
156
async function genRoutesFile ({ siteData: { pages }}) {
E
tweaks  
Evan You 已提交
157
  function genRoute ({ path }) {
E
Evan You 已提交
158 159
    const code = `
    {
E
Evan You 已提交
160
      path: ${JSON.stringify(path)},
E
Evan You 已提交
161 162 163 164 165
      component: Theme
    }`
    return code
  }

E
tweaks  
Evan You 已提交
166
  return (
E
Evan You 已提交
167
    `import Theme from '~theme'\n` +
E
tweaks  
Evan You 已提交
168 169
    `export const routes = [${pages.map(genRoute).join(',')}\n]`
  )
E
Evan You 已提交
170
}