预渲染
# 优点:
- 无需使用web服务器实时动态编译HTML
- 改善少数页面的SEO,可采用预渲染
# 缺点:
- 若网站有成百上千条路线,预编译会非常缓慢(此情况慎用)
# 安装
预渲染核心:
prerender-spa-plugin安装:
npm install prerender-spa-plugin --save-dev
如果安装出现报错
ERROR: Failed to download Chromium r609904! Set "PUPPETEER_SKIP_CHROMIUM_DOWNLOAD" env variable t...
1
解决
npm config set puppeteer_download_host=https://npm.taobao.org/mirrors
npm install prerender-spa-plugin --save-dev
1
2
3
2
3
# 配置
# 为自定义预渲染页面添加自定义 title、description、content
- 删除 public/index.html 中关于 description、content 的 meta 标签。保留 title 标签
- 配置 router-config.js
module.exports = {
"/": {
title: "首页",
keywords: "首页关键词",
description: "这是首页描述"
},
"/about": {
title: "关于我们",
keywords: "关于我们页面关键词",
description: "关于我们页面关键词描述"
}
};
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
- vue.config.js
const path = require("path");
const PrerenderSpaPlugin = require("prerender-spa-plugin");
const routesConfig = require("./router-config");
const resolve = dir => path.join(__dirname, dir);
const IS_PROD = ["production", "prod"].includes(process.env.NODE_ENV);
module.exports = {
configureWebpack: config => {
const plugins = [];
if (IS_PROD) {
// 预加载
plugins.push(
new PrerenderSpaPlugin({
staticDir: resolve("dist"),
routes: Object.keys(routesConfig),
postProcess(ctx) {
ctx.route = ctx.originalRoute;
ctx.html = ctx.html.split(/>[\s]+</gim).join("><");
ctx.html = ctx.html.replace(
/<title>(.*?)<\/title>/gi,
`<title>${
routesConfig[ctx.route].title
}</title><meta name="keywords" content="${
routesConfig[ctx.route].keywords
}" /><meta name="description" content="${
routesConfig[ctx.route].description
}" />`
);
if (ctx.route.endsWith(".html")) {
ctx.outputPath = path.join(__dirname, "dist", ctx.route);
}
return ctx;
},
minify: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
decodeEntities: true,
keepClosingSlash: true,
sortAttributes: true
},
renderer: new PrerenderSpaPlugin.PuppeteerRenderer({
// 需要注入一个值,这样就可以检测页面当前是否是预渲染的
inject: {},
headless: false,
// 视图组件是在API请求获取所有必要数据后呈现的,因此我们在dom中存在“data view”属性后创建页面快照
// 在 main.js 中 document.dispatchEvent(new Event('render-event')),两者的事件名称要对应上。
renderAfterDocumentEvent: "render-event"
})
})
);
}
config.plugins = [...config.plugins, ...plugins];
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
- main.js
new Vue({
router,
store,
render: h => h(App),
mounted() {
document.dispatchEvent(new Event("render-event"));
}
}).$mount("#app");
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
- index.html 如果页面中存在需要执行交互操作
<div id="app" data-server-rendered="true">
1
上次更新: 2022/05/05, 17:47:41