prepare.js 7.6 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 { promisify } = require('util')
const readFile = promisify(fs.readFile)
const writeFile = promisify(fs.writeFile)
E
Evan You 已提交
8 9
const yaml = require('yaml-front-matter')
const tempPath = path.resolve(__dirname, 'app/.temp')
E
Evan You 已提交
10
const { inferTitle, extractHeaders } = require('./util')
E
Evan You 已提交
11

E
Evan You 已提交
12 13
mkdirp(tempPath)

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

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

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

E
Evan You 已提交
32
  await writeTemp('routes.js', [
E
Evan You 已提交
33 34 35
    componentCode,
    routesCode
  ].join('\n\n'))
E
tweaks  
Evan You 已提交
36

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

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

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

E
Evan You 已提交
57 58 59 60
  return options
}

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

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

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

E
Evan You 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
  // 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 已提交
92 93 94 95 96 97
  // resolve theme
  const useDefaultTheme = (
    !siteConfig.theme &&
    !fs.existsSync(path.resolve(vuepressDir, 'theme'))
  )

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

E
Evan You 已提交
112
  if (useDefaultTheme) {
E
Evan You 已提交
113 114 115 116
    // 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 已提交
117 118
    let themeDir
    let themePath
E
Evan You 已提交
119
    // resolve custom theme
E
Evan You 已提交
120 121 122 123 124 125 126 127 128
    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 已提交
129
    } else {
E
Evan You 已提交
130 131 132 133 134
      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 已提交
135
    }
E
Evan You 已提交
136
    options.themePath = themePath
E
Evan You 已提交
137 138 139 140 141

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

E
Evan You 已提交
146
  // resolve pages
E
Evan You 已提交
147
  const pagesData = await Promise.all(options.pageFiles.map(async (file) => {
E
tweaks  
Evan You 已提交
148
    const data = {
E
Evan You 已提交
149
      path: fileToPath(file)
E
Evan You 已提交
150
    }
E
Evan You 已提交
151 152

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

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

  return options
}

E
Evan You 已提交
183
async function genComponentRegistrationFile ({ sourceDir }) {
E
Evan You 已提交
184
  function genImport (file) {
E
Evan You 已提交
185
    const name = fileToComponentName(file)
E
Evan You 已提交
186
    const baseDir = path.resolve(sourceDir, '.vuepress/components')
E
Evan You 已提交
187 188 189 190 191
    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 已提交
192
  return `import Vue from 'vue'\n` + components.map(genImport).join('\n')
E
Evan You 已提交
193 194
}

195
const indexRE = /\b(index|readme)\.md$/i
E
Evan You 已提交
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
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 已提交
219 220 221
}

function isIndexFile (file) {
E
Evan You 已提交
222
  return indexRE.test(file)
E
Evan You 已提交
223 224
}

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

E
Evan You 已提交
233 234 235 236
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 已提交
237 238
    const code = `
    {
E
Evan You 已提交
239 240 241 242 243 244 245 246
      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 已提交
247 248 249 250
    }`
    return code
  }

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

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