vue mode: history 链接刷新报错_基于prerenderspaplugin的Vue.js预渲染实践

作者:-mxin

来源:SegmentFault 思否社区


插件配置

1.路由模式

  • 路由模式切换为history模式,去除URL中的#
const router = new VueRouter({
  mode: 'history',
  routes: [...]
})
  • 路由懒加载,配合预渲染更好做到按需加载
{
    path: "/about",
    name: "About",
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/About.vue")
}

js
├── about.95b9e039.js   ├── app.7be39401.js
└── chunk-vendors.9cd40e36.js
  • 服务端配置覆盖无静态资源情况下返回的页面,避免直接访问或刷新404

预渲染页面访问路径指向其对应目录下的index.html,其他情况直接指向打包输出根目录下的主入口index.html。

/**
 * 创建本地服务
 */
http
  .createServer((req, res) => {
    const filePath = getFilePath(req);
    const indexFilePath = path.join(__dirname, "/dist/index.html");
    const exists = fs.existsSync(filePath);
    const data = fs.readFileSync(exists ? filePath : indexFilePath);
    writeHead(res, filePath);
    res.end(data);
  })
  .listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
  });

dist
├── favicon.ico
├── home
│   └── index.html  ├── index.html      └── static

2.prerender-spa-plugin使用

  • 安装依赖
 npm install prerender-spa-plugin --save-dev
 or
 --registry https://registry.npm.taobao.org  使用镜像安装
 or
 cnpm
  • 添加 vue.config.js 配置
``const path = require("path");
const PrerenderSpaPlugin = require("prerender-spa-plugin");
const isProduction = process.env.NODE_ENV === "production";

module.exports = {
  publicPath: "/",
  outputDir: "dist",
  assetsDir: "static",
  productionSourceMap: false,
  configureWebpack: config => {
    if (isProduction) {
      config.plugins.push(
        // 预渲染插件配置
        new PrerenderSpaPlugin({
          // 静态资源路径
          staticDir: path.join(__dirname, "dist"),
          // 预渲染路由
          routes: ["/home"]
        })
      );
    }
  }
};
  • build后生成dist目录,结构如下:
dist
├── favicon.ico
├── home
│   └── index.html   ├── index.html       └── static
    ├── css
    ├── img
    └── js

3.vue-meta-info 使用

  • 安装依赖
npm install vue-meta-info --save-dev
  • 全局注册
import Vue from 'vue'
import MetaInfo from 'vue-meta-info'

Vue.use(MetaInfo)

  • 组件中静态用法,定制的meta信息在预渲染时也会写入页面
`
  ...




19c125780015186bb40906c7890b2d49.png

4.试试效果

完整示例地址

示例工程中内置了命令,打包输出dist目录后自动运行本地服务进行预览。

6be8de02e1c00784277175d710ec2203.png


总结

  • 对比服务端渲染,简单易上手
  • 适用于页面数量少且偏静态的页面
  • 预渲染页面数据异步加载会有空白期,先加载预渲染部分;此时可以适当加入加载状态或骨架屏避免尴尬

- END -

1abf470a9ff7e6fbe47931fb6ccaea99.png

9b0e45542ef154cc3d82a044be3e5b9e.gif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值