Skip to content

Commit

Permalink
refactor: upgrade vite & vue + refactor asset related logic
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed May 3, 2020
1 parent 57d900d commit a3df035
Show file tree
Hide file tree
Showing 6 changed files with 129 additions and 219 deletions.
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@
"author": "Evan You",
"license": "MIT",
"dependencies": {
"@vue/compiler-sfc": "^3.0.0-beta.5",
"@vue/server-renderer": "^3.0.0-beta.5",
"@vue/compiler-sfc": "^3.0.0-beta.6",
"@vue/server-renderer": "^3.0.0-beta.6",
"debug": "^4.1.1",
"diacritics": "^1.3.0",
"escape-html": "^1.0.3",
Expand All @@ -64,8 +64,8 @@
"minimist": "^1.2.5",
"prismjs": "^1.20.0",
"slash": "^3.0.0",
"vite": "^0.8.1",
"vue": "^3.0.0-beta.5"
"vite": "^0.9.1",
"vue": "^3.0.0-beta.6"
},
"devDependencies": {
"@types/lru-cache": "^5.1.0",
Expand Down
3 changes: 2 additions & 1 deletion src/build/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ export type BuildOptions = Pick<
'root' | 'rollupInputOptions' | 'rollupOutputOptions'
>

export const ASSETS_DIR = '_assets/'

export async function build(buildOptions: BuildOptions = {}) {
const siteConfig = await resolveConfig(buildOptions.root)
try {
const [clientResult] = await bundle(siteConfig, buildOptions)

console.log('rendering pages...')
for (const page of siteConfig.pages) {
await renderPage(siteConfig, page, clientResult)
Expand Down
59 changes: 24 additions & 35 deletions src/build/bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import slash from 'slash'
import { promises as fs } from 'fs'
import { APP_PATH, createResolver } from '../utils/pathResolver'
import { build, BuildOptions as ViteBuildOptions, BuildResult } from 'vite'
import { BuildOptions } from './build'
import { BuildOptions, ASSETS_DIR } from './build'
import { SiteConfig } from '../config'
import { Plugin } from 'rollup'
import { createMarkdownToVueRenderFn } from '../markdownToVue'
Expand Down Expand Up @@ -43,82 +43,71 @@ export async function bundle(
// for each .md entry chunk, adjust its name to its correct path.
for (const name in bundle) {
const chunk = bundle[name]
if (chunk.type === 'chunk') {
if (
chunk.isEntry &&
chunk.facadeModuleId &&
chunk.facadeModuleId.endsWith('.md')
) {
// foo/bar.md -> _assets/foo_bar.md.js
chunk.fileName = path.join(
'_assets/',
slash(path.relative(root, chunk.facadeModuleId)).replace(
/\//g,
'_'
) + '.js'
)
} else {
chunk.fileName = path.join('_assets/', chunk.fileName)
}
if (
chunk.type === 'chunk' &&
chunk.isEntry &&
chunk.facadeModuleId &&
chunk.facadeModuleId.endsWith('.md')
) {
// foo/bar.md -> foo_bar.md.js
chunk.fileName =
slash(path.relative(root, chunk.facadeModuleId)).replace(
/\//g,
'_'
) + '.js'
}
}
}
}

// convert page files to absolute paths
const pages = config.pages.map(file => path.resolve(root, file))
const pages = config.pages.map((file) => path.resolve(root, file))

// let rollup-plugin-vue compile .md files as well
const rollupPluginVueOptions = {
include: /\.(vue|md)$/
}

const sharedOptions: ViteBuildOptions = {
const clientOptions: ViteBuildOptions = {
...options,
cdn: false,
silent: true,
resolvers: [resolver],
srcRoots: [APP_PATH, config.themeDir],
cssFileName: '_assets/style.css',
outDir: config.outDir,
assetsDir: ASSETS_DIR,
rollupPluginVueOptions,
rollupInputOptions: {
...rollupInputOptions,
input: [path.resolve(APP_PATH, 'index.js'), ...pages],
plugins: [VitePressPlugin, ...(rollupInputOptions.plugins || [])]
},
rollupOutputOptions: {
...rollupOutputOptions,
dir: config.outDir
},
rollupOutputOptions,
minify: !process.env.DEBUG
}

console.log('building client bundle...')
const clientResult = await build({
...sharedOptions,
rollupOutputOptions: {
...rollupOutputOptions,
dir: config.outDir
}
})
const clientResult = await build(clientOptions)

console.log('building server bundle...')
const serverResult = await build({
...sharedOptions,
...clientOptions,
outDir: config.tempDir,
rollupPluginVueOptions: {
...rollupPluginVueOptions,
target: 'node'
},
rollupInputOptions: {
...sharedOptions.rollupInputOptions,
...clientOptions.rollupInputOptions,
external: ['vue', '@vue/server-renderer']
},
rollupOutputOptions: {
...rollupOutputOptions,
dir: config.tempDir,
format: 'cjs',
exports: 'named'
},
// server build doesn't need to emit static assets
emitAssets: false,
// server build doesn't need minification
minify: false
})
Expand Down
21 changes: 13 additions & 8 deletions src/build/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { SiteConfig, HeadConfig } from '../config'
import { BuildResult } from 'vite'
import { renderToString } from '@vue/server-renderer'
import { OutputChunk } from 'rollup'
import { ASSETS_DIR } from './build'

const escape = require('escape-html')

Expand All @@ -12,7 +13,11 @@ export async function renderPage(
page: string, // foo.md
result: BuildResult
) {
const { createApp } = require(path.join(config.tempDir, '_assets/index.js'))
const { createApp } = require(path.join(
config.tempDir,
ASSETS_DIR,
'index.js'
))
const { app, router } = createApp()
const routePath = `/${page.replace(/\.md$/, '')}`
router.go(routePath)
Expand All @@ -23,14 +28,14 @@ export async function renderPage(
// resolve page data so we can render head tags
const { __pageData } = require(path.join(
config.tempDir,
'_assets',
ASSETS_DIR,
pageJsFileName
))
const pageData = JSON.parse(__pageData)

const assetPath = `${config.site.base}_assets`
const assetPath = `${config.site.base}${ASSETS_DIR}`
const renderScript = (file: string) => {
return `<script type="module" async src="${assetPath}/${file}"></script>`
return `<script type="module" async src="${assetPath}${file}"></script>`
}

// resolve imports for index.js + page.md.js and inject script tags for
Expand All @@ -48,7 +53,7 @@ export async function renderPage(
config.site.title
}</title>
<meta name="description" content="${config.site.description}">
<link rel="stylesheet" href="${assetPath}/style.css">${renderHead(
<link rel="stylesheet" href="${assetPath}style.css">${renderHead(
config.site.head
)}${renderHead(pageData.frontmatter.head)}
</head>
Expand All @@ -70,11 +75,11 @@ function resolvePageImports(
) {
// find the page's js chunk and inject script tags for its imports so that
// they are start fetching as early as possible
const indexChunk = result.js.find(
(chunk) => chunk.type === 'chunk' && chunk.fileName === `_assets/index.js`
const indexChunk = result.assets.find(
(chunk) => chunk.type === 'chunk' && chunk.fileName === `index.js`
) as OutputChunk
const srcPath = path.join(config.root, page)
const pageChunk = result.js.find(
const pageChunk = result.assets.find(
(chunk) => chunk.type === 'chunk' && chunk.facadeModuleId === srcPath
) as OutputChunk
return Array.from(new Set([...indexChunk.imports, ...pageChunk.imports]))
Expand Down
25 changes: 7 additions & 18 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,11 @@ import { APP_PATH, SITE_DATA_REQUEST_PATH } from './utils/pathResolver'
const debug = require('debug')('vitepress:serve')
const debugHmr = require('debug')('vitepress:hmr')

function createVitePressPlugin(config: SiteConfig): Plugin {
const {
themeDir,
site: initialSiteData,
resolver: vitepressResolver
} = config

function createVitePressPlugin({
themeDir,
configPath,
site: initialSiteData
}: SiteConfig): Plugin {
return ({ app, root, watcher, resolver }) => {
const markdownToVue = createMarkdownToVueRenderFn(root)

Expand Down Expand Up @@ -72,9 +70,9 @@ function createVitePressPlugin(config: SiteConfig): Plugin {
// parsing the object literal as JavaScript.
let siteData = initialSiteData
let stringifiedData = JSON.stringify(JSON.stringify(initialSiteData))
watcher.add(config.configPath)
watcher.add(configPath)
watcher.on('change', async (file) => {
if (file === config.configPath) {
if (file === configPath) {
const newData = await resolveSiteData(root)
stringifiedData = JSON.stringify(JSON.stringify(newData))
if (newData.base !== siteData.base) {
Expand Down Expand Up @@ -126,15 +124,6 @@ function createVitePressPlugin(config: SiteConfig): Plugin {
return
}

// detect and serve vitepress @app / @theme files
const file = vitepressResolver.requestToFile(ctx.path, root)
if (file) {
await cachedRead(ctx, file)
debug(ctx.url, ctx.status)
await next()
return
}

await next()

// serve our index.html after vite history fallback
Expand Down
Loading

0 comments on commit a3df035

Please sign in to comment.