前端如何进行优化性能,让用户体验更加顺畅?
前言
现在很多产品都是C端的产品,而大部分公司的核心业务就是C端的客户群体,个别的公司的核心是B端,那么C端的客户就是他们为B端客户最好的贡献者,至于其中奥秘懂得自然懂。
那么既然大部分公司的核心是C端,C端又分为很多产品比如WEB网址,小程序,APP,Windows应用等等。而现在WEB产品还是大部分的主流产品,使用很多的前端框架就是VUE,UIAPP,REACT。而现在的开发模式都是前后端分离开发,那么今天我就为大家分享一下我对VUE项目的前端的性能优化方案。
为什么要优化呢?
玩过服务器的小伙伴们应该知道服务的带宽是有限制,而很多公司会去选择轻量云服务器,这里简单介绍一下什么是轻量云服务器。轻量云服务器的带宽流量就是有限制的,而服务器的配置不能进行单一升级,比如我想升级一下带宽这样就是不可以的,但是在服务器中就是可以,可以进行单一配置升级。而且服务器的带宽是非常的昂贵的,比如1M的带宽这样用户访问你的网站的时候速度就会很慢很慢,如果是动态网站的话等完整的页面渲染出来估计大概要10秒以上。那么我们就可以对其前端的build生成代码进行压缩,配置nginx的压缩率。对资源进行压缩已达到提升前端用户访问页面的速度,减少页面的渲染时间。
废话就不多说了,直接开始上代码
VUE项目优化
相信大家搞VUE开发的应该都知道webpack这个东西吧,现在vue的脚手架的最新版本就是5.0.3版本
使用命令
vue create app
创建的项目目录就会简单很多很多,
目录就是public src没了
所有的vue配置都集成到了vue.config.js中,在这里可以配置整个项目的所有配置包括webpack
详细配置可以参考我的上一篇文章,vue.config.js配置注释详解
今天就介绍一下几个对前端项目的优化的小中间件,
第一就是uglifyjs-webpack-plugin,它是用来干嘛的呢?它是用来对代码进行压缩的,并可以配置在生产模式下取消项目中的console.log打印
安装命令:
yarn add -D uglifyjs-webpack-plugin 或 npm install uglifyjs-webpack-plugin -save -dev
在项目中引入和使用
//打包配置自动忽略console.log等const UglifyJsPlugin = require('uglifyjs-webpack-plugin')//启用代码压缩 plugins.push( new UglifyJsPlugin({ uglifyOptions: { compress: { warnings: false, drop_console: true, drop_debugger: false, pure_funcs: ["console.log"] //移除console } }, sourceMap: false, parallel: true }) ),
详细使用说明:uglifyjs-webpack-plugin - npm (npmjs.com)
但是这个插件好像挺久的了,推荐一个新的terser-webpack-plugin
const Webpack = require('webpack')// 引入该插件const CompressionWebpackPlugin = require('compression-webpack-plugin')// 引入压缩插件const TerserPlugin = require('terser-webpack-plugin')// 匹配此 {RegExp} 的资源const productionGzipExtensions = /\.(js|css|json|ttf)(\?.*)?$/imodule.exports = { transpileDependencies: ['vuetify'], assetsDir: 'assets', // 静态资源目录(js,css,img,fonts)这些文件都可以写里面 productionSourceMap: false, configureWebpack: { plugins: [ new CompressionWebpackPlugin({ filename: '[path][name].gz[query]', algorithm: 'gzip', test: productionGzipExtensions, threshold: 0, minRatio: 0.8, }), new Webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), ], optimization: { minimizer: [ new TerserPlugin({ terserOptions: { ecma: undefined, warnings: false, parse: {}, compress: {drop_console: true,drop_debugger: false,pure_funcs: ['console.log'], // 移除console }, }, }), ], }, },}
详细使用说明:terser-webpack-plugin - npm (npmjs.com)
第二个就是 compression-webpack-plugin,对资源进行压缩
安装命令:
yarn add -D compression-webpack-plugin 或 npm install compression-webpack-plugin -save -dev
在项目中引入和使用:
const CompressionWebpackPlugin = require("compression-webpack-plugin"); // 开启gzip压缩, 按需引用plugins.push( new CompressionWebpackPlugin({ filename: '[path].gz[query]', algorithm: 'gzip', test: productionGzipExtensions, threshold: 10240,//大于10k的进行压缩 minRatio: 0.8, }) );
第三个就是html-webpack-plugin对面的html进行处理,对seo比较友好一点点
安装命令:
yarn add --dev html-webpack-plugin 或 npm i --save-dev html-webpack-plugin
在项目中引用
const { resolve } = require('path')//nodejs 方法const HtmlWebpackPlugin = require('html-webpack-plugin') export.moduls= { entry: { one: ['./src/index1.js', './src/index2.js'], two:'./src/indexTwo.js' }, mode: 'development', output: { filename: '[name].js', path: resole(_dirname, 'build') }, module: { rules: [] }, plugins: [ //默认:创建空的html 自动引入打包的资源(js css) // template 自定义设置入口html filename 自定义文件名 new HtmlWebpackPlugin({ template: './src/index.html', filename: 'index.html', minify: { collapseWhitespace: true, //html打包去除空格 removeComments: true // 移除注释 }, chunks:['one'], //指定引用的js }) ]}
第四个就是purgecss-webpack-plugin移除多余没有使用的css样式代码
安装命令:
yarn add -D purgecss-webpack-plugin 或 npm install purgecss-webpack-plugin -save -dev
在项目中引用
//用于生产环境去除多余的cssconst PurgecssPlugin = require("purgecss-webpack-plugin")//去掉不用的css 多余的css plugins.push( new PurgecssPlugin({ paths: glob.sync([path.join(__dirname, "./**/*.vue")]), extractors: [ { extractor: class Extractor {static extract(content) { const validSection = content.replace( /<style([\s\S]*?)+/gim, "" ); return validSection.match(/[A-Za-z0-9-_:/]+/g) || [];} }, extensions: ["html", "vue"] } ], whitelist: ["html", "body"], whitelistPatterns: [/el-.*/], whitelistPatternsChildren: [/^token/, /^pre/, /^code/] }) );
这个插件我个人是感觉不怎么好用,所以推荐大家另外一款插件 optimize-css-assets-webpack-plugin webpack5.0以上的高版本用 css-minimizer-webpack-plugin
由于我的webpack是5.x的高版本我就使用 css-minimizer-webpack-plugin来处理css代码
安装命令:
yarn add -D purgecss-webpack-plugin 或 npm install css-minimizer-webpack-plugin --save-dev
在项目中引用
const CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin"); // 使用css-minimizer-webpack-pluginplugins.push( new CssMinimizerWebpackPlugin() )//我这里使用了默认配置,个人感觉默认的就够用了
更多使用说明:css-minimizer-webpack-plugin - npm (npmjs.com)
第五个就是mini-css-extract-plugin它为每个包含 CSS 的 JS 文件创建一个 CSS 文件。它支持CSS和SourceMaps的按需加载。
安装命令:
yarn add -D mini-css-extract-plugin 或 npm install --save-dev mini-css-extract-plugin
项目中应用:
const MiniCssExtractPlugin = require("mini-css-extract-plugin");plugins.push( new MiniCssExtractPlugin({ linkType: "text/css", }) )//这里我也使用了默认配置
更多使用说明:mini-css-extract-plugin - npm (npmjs.com)
最后上一张完成的优化过程截图
最后附上完整的vue.config.js代码
const { defineConfig } = require('@vue/cli-service')const path = require('path');const CompressionWebpackPlugin = require("compression-webpack-plugin"); // 开启gzip压缩, 按需引用const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i; // 开启gzip压缩, 按需写入const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV);const resolve = (dir) => path.join(__dirname, dir);const TerserPlugin = require('terser-webpack-plugin')//去除多余的console.logconst CssMinimizerWebpackPlugin = require("css-minimizer-webpack-plugin"); // 使用css-minimizer-webpack-pluginconst MiniCssExtractPlugin = require("mini-css-extract-plugin");//为每个css生成一个单独css文件,俗称分片module.exports = defineConfig({ transpileDependencies: true, assetsDir: 'static', productionSourceMap: false, integrity: true, crossorigin: undefined, chainWebpack: config => { config.resolve.symlinks(true); // 修复热更新失效 // 如果使用多页面打包,使用vue inspect --plugins查看html是否在结果数组中 config.plugin("html").tap(args => { // 修复 Lazy loading routes Error args[0].chunksSortMode = "none"; return args; }); config.resolve.alias // 添加别名 .set('@', resolve('src')) .set('@assets', resolve('src/assets')) .set('@components', resolve('src/components')) .set('@views', resolve('src/views')) .set('@store', resolve('src/store')); // 压缩图片 // 需要 npm i -D image-webpack-loader config.module .rule("images") .use("image-webpack-loader") .loader("image-webpack-loader") .options({ mozjpeg: { progressive: true, quality: 65 }, optipng: { enabled: false }, pngquant: { quality: [0.65, 0.9], speed: 4 }, gifsicle: { interlaced: false }, webp: { quality: 75 } }); }, configureWebpack: (config) => { // 开启 gzip 压缩 // 需要 npm i -D compression-webpack-plugin const plugins = []; if (IS_PROD) { plugins.push( new CompressionWebpackPlugin({ filename: '[path].gz[query]', algorithm: 'gzip', test: productionGzipExtensions, threshold: 10240,//大于10k的进行压缩 minRatio: 0.8, }) ); plugins.push( //打包环境去掉console.log等 new TerserPlugin({ terserOptions: { ecma: undefined, warnings: false, parse: {}, compress: {drop_console: true,drop_debugger: false,pure_funcs: ['console.log'], // 移除console }, }, }), ); plugins.push( new CssMinimizerWebpackPlugin({ minify: CssMinimizerWebpackPlugin.cleanCssMinify, test: /\.foo\.css$/i, include: /\/includes/, exclude: /\/excludes/, parallel: true, parallel: 4, minimizerOptions: { level: {1: { roundingPrecision: "all=3,px=5",}, }, //删除所有注释 preset: ["default",{ discardComments: { removeAll: true },}, ], }, warningsFilter: (warning, file, source) => { if (/Dropping unreachable code/i.test(warning)) {return true; } if (/file\.css/i.test(file)) {return true; } if (/source\.css/i.test(source)) {return true; } return false; }, }) ); plugins.push( new MiniCssExtractPlugin({ linkType: "text/css", runtime: false, experimentalUseImportModule: true, filename: "[name].css", chunkFilename: "[id].css", ignoreOrder: false, }) ) } config.plugins = [...config.plugins, ...plugins]; },})
如果本篇文章对您有帮助请点个赞或者关注一下我