Vue3 通过打包上传到七牛CDN,实现首页加速

Vue3 通过打包上传到七牛CDN,实现首页加速
前端技术

背景

js文件将近了2MB,由于每次打包的文件都不一样,每当网站又修改就需要重新下载,打包时间也40多秒,对于首次访问的网站,特别不友好,严重影响用户的体验,下载文件js文件将近7秒

打包

 warning  

asset size limit: The following asset(s) exceed the recommended size limit (244 KiB). This can impact web performance. Assets: css/chunk-vendors.2023659.css (306 KiB) js/chunk-vendors.2023659.js (1.82 MiB) js/chunk-vendors.2023659.js.gz (521 KiB)

webpack performance recommendations: 
You can limit the size of your bundles by using import() or require.ensure to lazy load some parts of your application.
For more info visit https://webpack.js.org/guides/code-splitting/

File Size Gzipped

dist/js/chunk-vendors.2023659.js 1860.53 KiB 523.31 KiB dist/js/app.2023659.js 59.77 KiB 17.15 KiB dist/css/chunk-vendors.2023659.css 305.70 KiB 42.05 KiB dist/css/app.2023659.css 34.81 KiB 5.62 KiB

Images and other types of assets omitted. Build at: 2023-07-07T01:47:55.227Z - Hash: fa300f3c0da7dfde - Time: 40546ms

首页加载

Description

有问题的方案

这个方案,会造成CSS样式错乱,ICO图标不正确等等,总之,把CSS放到CDN,出现了各种各样的问题,苦寻无果,只好放弃CSS,CSS文件比较小,所以采用折中方案

修改Vue.config.js

增加publicPath

publicPath: process.env.NODE_ENV === "production" ? "https://CDN域名/" : "/",

全部


const {defineConfig} = require('@vue/cli-service')
const path = require("path")
const CompressionPlugin = require("compression-webpack-plugin")
const Timestamp = '' + new Date().getFullYear() + new Date().getMonth() + new Date().getDay() + new Date().getHours();

function resolve(dir) { return path.join(__dirname, dir); }

module.exports = defineConfig({ transpileDependencies: true, publicPath: process.env.NODE_ENV === "production" ? "https://CDN域名/" : "/",

chainWebpack: (config) => {
    config.plugins.delete("prefetch");
    // set svg-sprite-loader
    config.module
        .rule("svg")
        .exclude.add(resolve("src/icons"))
        .end();
    config.module
        .rule("icons")
        .test(/\.svg$/)
        .include.add(resolve("src/icons"))
        .end()
        .use("svg-sprite-loader")
        .loader("svg-sprite-loader")
        .options({
            symbolId: "icon-[name]",
        })
        .end();
},
css: {
    extract: {
        ignoreOrder: true,
        filename: `css/[name].${Timestamp}.css`,
        chunkFilename: `css/[name].${Timestamp}.css`,
    }
},
configureWebpack: {
    output: {
        filename: `js/[name].${Timestamp}.js`,
        chunkFilename: `js/[name].${Timestamp}.js`
    },
    plugins: [
        new CompressionPlugin({
            algorithm: 'gzip', // 使用gzip压缩
            test: /\.js$|\.html$|\.css$/, // 匹配文件名
            filename: '[path][base].gz[query]', // 压缩后的文件名(保持原文件名,后缀加.gz)
            minRatio: 1, // 压缩率小于1才会压缩
            threshold: 10240, // 对超过10k的数据压缩
            deleteOriginalAssets: false, // 是否删除未压缩的源文件,谨慎设置,如果希望提供非gzip的资源,可不设置或者设置为false(比如删除打包后的gz后还可以加载到原始资源文件)
        }),
    ]
}

})

修改router下的index.js

import {createRouter, createWebHistory} from 'vue-router'
import routes from './routes' // 导入 router 目录下的 router.js

const router = createRouter({ history: createWebHistory(''), routes }) export default router;

打包之后上传JS和CSS

折中解决方案,放弃CSS

查看的打包之后index.html

打包之后把比较大的js文件,上传到CDN,然后替换成CDN路径

<!doctype html>
<html lang="">
<head>
    <meta charset="utf-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta content="width=device-width,initial-scale=1" name="viewport">
    <link href="/favicon.ico" rel="icon">
    <title>spectre</title>
    <script defer="defer" src="/js/chunk-vendors.e49d683a.js"></script>
    <script defer="defer" src="/js/app.663c72f3.js"></script>
    <link href="/css/chunk-vendors.e3c32225.css" rel="stylesheet">
    <link href="/css/app.9d3e7f52.css" rel="stylesheet">
</head>
<body>
<noscript><strong>We're sorry but spectre doesn't work properly without JavaScript enabled. Please enable it to
    continue.</strong></noscript>
<div id="app"></div>
</body>
</html>

替换命令

sed -i "s#/js/#https://你的CDN域名/js/#g" dist/index.html

自动上传CDN,自动替换,一些法案探讨

  1. 打包上传服务器
  2. 将服务器的比较大的文件,上传的CDN,需要编写上传脚步,或者编写上传服务
  3. 把index.html, 替换成的CDN域名
bigcong