参考 koa-static 实现静态资源的处理, config/koa/static.js :
'use strict'/**
* From koa-static
*/
const { resolve } = require('path')
const assert = require('assert')
const send = require('koa-send')
/**
* Expose `serve()`.
*/
module.exports = serve
/**
* Serve static files from `root`.
*
* @param {String} root
* @param {Object} [opts] * @return {Function}
* @api public
*/
function serve (root, opts) {
opts = Object.assign({}, opts)
assert(root, 'root directory is required to serve files')
// options
opts.root = resolve(root)
if (opts.index !== false) opts.index = opts.index || 'index.html'
if (!opts.defer) {
return async function serve (ctx, next) {
let done = false
if (ctx.method === 'HEAD' || ctx.method === 'GET') {
if (ctx.path === '/' || ctx.path === '/index.html') { // exclude index.html file
await next()
return
}
try {
done = await send(ctx, ctx.path, opts)
} catch (err) {
if (err.status !== 404) {
throw err
}
}
}
if (!done) {
await next()
}
}
}
return async function serve (ctx, next) {
await next()
if (ctx.method !== 'HEAD' && ctx.method !== 'GET') return
// response is already handled
if (ctx.body != null || ctx.status !== 404) return // eslint-disable-line
try {
await send(ctx, ctx.path, opts)
} catch (err) {
if (err.status !== 404) {
throw err
}
}
}
}
我们可以看到, koa-static 仅仅是对 koa-send 进行了简单封装( yarn add koa-send )。接下来就是重头戏SSR相关的配置了, config/ssr.js :
const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const LRU = require('lru-cache')
const {
createBundleRenderer
} = require('vue-server-renderer')
const isProd = process.env.NODE_ENV === 'production'
const setUpDevServer = require('./setup-dev-server')
const HtmlMinifier = require('html-minifier').minifyconst pathResolve = file => path.resolve(__dirname, file)
module.exports = app => {
return new Promise((resolve, reject) => {
const createRenderer = (bundle, options) => {
return createBundleRenderer(bundle, Object.assign(options, {
cache: LRU({
max: 1000,
maxAge: 1000 * 60 * 15
}),
basedir: pathResolve('../dist/web'),
runInNewContext: false
}))
}
let renderer = null
if (isProd) {
// prod mode
const template = HtmlMinifier(fs.readFileSync(pathResolve('../public/index.html'), 'utf-8'), {
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: false
})










