vue项目打包优化的方法实战记录
作者:一只小菜鸡111 发布时间:2024-04-26 17:39:50
1.按需加载第三方库
例如 ElementUI、lodash 等
a, 装包
npm install babel-plugin-component -D
b, babel.config.js
module.exports = {
"presets": [
"@vue/cli-plugin-babel/preset"
],
"plugins": [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
}
c, main.js
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
换成
import './plugins/element.js'
element.js
import Vue from 'vue'
import { Button, Form, FormItem, Input, Message, Header, Container, Aside, Main, Menu, Submenu, MenuItemGroup, MenuItem, Breadcrumb, BreadcrumbItem, Card, Row, Col, Table, TableColumn, Switch, Tooltip, Pagination, Dialog, MessageBox, Tag, Tree, Select, Option, Cascader, Alert, Tabs, TabPane, Steps, Step, CheckboxGroup, Checkbox, Upload, Timeline, TimelineItem } from 'element-ui'
Vue.use(Button)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(Input)
Vue.use(Header)
Vue.use(Container)
Vue.use(Aside)
Vue.use(Main)
Vue.use(Menu)
Vue.use(Submenu)
Vue.use(MenuItemGroup)
Vue.use(MenuItem)
Vue.use(Breadcrumb)
Vue.use(BreadcrumbItem)
Vue.use(Card)
Vue.use(Row)
Vue.use(Col)
Vue.use(Table)
Vue.use(TableColumn)
Vue.use(Switch)
Vue.use(Tooltip)
Vue.use(Pagination)
Vue.use(Dialog)
Vue.use(Tag)
Vue.use(Tree)
Vue.use(Select)
Vue.use(Option)
Vue.use(Cascader)
Vue.use(Alert)
Vue.use(Tabs)
Vue.use(TabPane)
Vue.use(Steps)
Vue.use(Step)
Vue.use(CheckboxGroup)
Vue.use(Checkbox)
Vue.use(Upload)
Vue.use(Timeline)
Vue.use(TimelineItem)
// 把弹框组件挂着到了 vue 的原型对象上,这样每一个组件都可以直接通过 this 访问
Vue.prototype.$message = Message
Vue.prototype.$confirm = MessageBox.confirm
效果图
优化 按需加载第三方工具包(例如 lodash)或者使用 CDN 的方式进行处理。
按需加载使用的工具方法 (当用到的工具方法少时按需加载打包) 用到的较多通过cdn
通过form lodash 搜索 哪处用到
例如此处的 1.
换成
按需导入
效果图
2.移除console.log
npm i babel-plugin-transform-remove-console -D
babel.config.js
const prodPlugins = []
if (process.env.NODE_ENV === 'production') {
prodPlugins.push('transform-remove-console')
}
module.exports = {
presets: ['@vue/cli-plugin-babel/preset'],
plugins: [
[
'component',
{
libraryName: 'element-ui',
styleLibraryName: 'theme-chalk'
}
],
...prodPlugins
]
}
效果图
3. Close SourceMap
生产环境关闭 功能
vue.config.js
module.exports = {
productionSourceMap: false
}
效果图
4. Externals && CDN
通过 externals 排除第三方 JS 和 CSS 文件打包,使用 CDN 加载。
vue.config.js
module.exports = {
productionSourceMap: false,
chainWebpack: (config) => {
config.when(process.env.NODE_ENV === 'production', (config) => {
const cdn = {
js: [
'https://cdn.staticfile.org/vue/2.6.11/vue.min.js',
'https://cdn.staticfile.org/vue-router/3.1.3/vue-router.min.js',
'https://cdn.staticfile.org/axios/0.18.0/axios.min.js',
'https://cdn.staticfile.org/echarts/4.1.0/echarts.min.js',
'https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.js',
'https://cdn.staticfile.org/quill/1.3.4/quill.min.js',
'https://cdn.jsdelivr.net/npm/vue-quill-editor@3.0.4/dist/vue-quill-editor.js'
],
css: [
'https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.css',
'https://cdn.staticfile.org/quill/1.3.4/quill.core.min.css',
'https://cdn.staticfile.org/quill/1.3.4/quill.snow.min.css',
'https://cdn.staticfile.org/quill/1.3.4/quill.bubble.min.css'
]
}
config.set('externals', {
vue: 'Vue',
'vue-router': 'VueRouter',
axios: 'axios',
echarts: 'echarts',
nprogress: 'NProgress',
'nprogress/nprogress.css': 'NProgress',
'vue-quill-editor': 'VueQuillEditor',
'quill/dist/quill.core.css': 'VueQuillEditor',
'quill/dist/quill.snow.css': 'VueQuillEditor',
'quill/dist/quill.bubble.css': 'VueQuillEditor'
})
config.plugin('html').tap((args) => {
args[0].isProd = true
args[0].cdn = cdn
return args
})
})
}
}
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>
<%= htmlWebpackPlugin.options.title %>
</title>
<% if(htmlWebpackPlugin.options.isProd){ %>
<% for(var css of htmlWebpackPlugin.options.cdn.css) { %>
<link rel="stylesheet" href="<%=css%>">
<% } %>
<% } %>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
<% if(htmlWebpackPlugin.options.isProd){ %>
<% for(var js of htmlWebpackPlugin.options.cdn.js) { %>
<script src="<%=js%>"></script>
<% } %>
<% } %>
</body>
</html>
效果图
继续对 ElementUI 的加载方式进行优化
vue.config.js
module.exports = {
chainWebpack: config => {
config.when(process.env.NODE_ENV === 'production', config => {
config.set('externals', {
'./plugins/element.js': 'ELEMENT'
})
config.plugin('html').tap(args => {
args[0].isProd = true
return args
})
})
}
}
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>
<%= htmlWebpackPlugin.options.isProd ? '' : 'dev - ' %>电商后台管理系统
</title>
<% if(htmlWebpackPlugin.options.isProd){ %>
<!-- element-ui 的样式表文件 -->
<link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.13.0/theme-chalk/index.css" />
<!-- element-ui 的 js 文件 -->
<script src="https://cdn.staticfile.org/element-ui/2.13.0/index.js"></script>
<% } %>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
效果图
5.路由懒加载的方式
import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
redirect: '/login'
},
{
path: '/login',
component: Login
},
{
path: '/Home',
component: () => import('../components/Home.vue'),
redirect: '/welcome',
children: [
{
path: '/welcome',
component: () => import('../components/Welcome.vue')
},
{
path: '/users',
component: () => import('../components/user/Users.vue')
},
{
path: '/rights',
component: () => import('../components/power/Rights.vue')
},
{
path: '/roles',
component: () => import('../components/power/Roles.vue')
},
{
path: '/categories',
component: () => import('../components/goods/Cate.vue')
},
{
path: '/params',
component: () => import('../components/goods/Params.vue')
},
{
path: '/goods',
component: () => import('../components/goods/List.vue')
},
{
path: '/goods/add',
component: () => import('../components/goods/Add.vue')
},
{
path: '/orders',
component: () => import('../components/order/Order.vue')
},
{
path: '/reports',
component: () => import('../components/report/Report.vue')
}
]
}
]
const router = new VueRouter({
routes
})
router.beforeEach((to, from, next) => {
// to 要访问的路径
// from 从哪里来的
// next() 直接放行,next('/login') 表示跳转
// 要访问 /login 的话那直接放行
if (to.path === '/login') return next()
const tokenStr = window.sessionStorage.getItem('token')
// token 不存在那就跳转到登录页面
if (!tokenStr) return next('/login')
// 否则 token 存在那就放行
next()
})
export default router
其他:图片压缩、CSS 压缩和提取、JS 提取...
1.部署到 Nginx
下载 Nginx,双击运行 nginx.exe,浏览器输入 localhost 能看到界面表示服务启动成功!
前端 axios 中的 baseURL 指定为 /api,配置 vue.config.js 代理如下
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://127.0.0.1:8888',
changeOrigin: true
}
}
}
}
路由模式、基准地址、404 记得也配置一下
const router = new VueRouter({
mode: 'history',
base: '/shop/',
routes: [
// ...
{
path: '*',
component: NotFound
}
]
})
执行 npm run build 打包,把 dist 中的内容拷贝到 Nginx 的 html 文件夹中
修改 Nginx 配置
http {
server {
listen 80;
location / {
# proxy_pass https://www.baidu.com;
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /api {
# 重写地址
# rewrite ^.+api/?(.*)$ /$1 break;
# 代理地址
proxy_pass http://127.0.0.1:8888;
# 不用管
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
重启服务
nginx -s reload
访问 localhost 查看下效果吧
开启 Gzip 压缩
前端通过 vue.config.js 配置,打包成带有 gzip 的文件
const CompressionWebpackPlugin = require('compression-webpack-plugin')
module.exports = {
configureWebpack: config => {
if (process.env.NODE_ENV === 'production') {
config.plugins = [...config.plugins, new CompressionWebpackPlugin()]
}
}
}
Nginx 中开启 gzip 即可
来源:https://blog.csdn.net/weixin_68531033/article/details/126342877
猜你喜欢
- 一、前言数据库的数据量达到一定程度之后,为避免带来系统性能上的瓶颈。需要进行数据的处理,采用的手段是分区、分片、分库、分表。二、分片(类似分
- 如果你的网站涉及个人隐私或者机密性非公开的网页,怎样告诉禁止搜索引擎收录抓取,下面侯庆龙说下以下方法,希望对不想被搜索引擎收录抓取网站有所帮
- 1、要点 (1) 在C语言中没有字符串,只有字符, 在python中的字符串hello,在C
- 1.背景项目需求,要求获得github的repo的api,以便可以提取repo的数据进行分析。研究了一天,终于解决了这个问题,虽然效率还是比
- Confusion Matrix在机器学习领域,混淆矩阵(confusion matrix),又称为可能性表格或是错误矩阵。它是一种特定的矩
- 我们按照面向过程程序设计的思想,使用python编写了程序,追踪铅球在运行过程中的位置信息。下面,修改程序代码,导入turtle模块,将铅球
- 本文实例讲述了python面试题之列表声明。分享给大家供大家参考,具体如下:下面程序输出的结果为?val = [['a']*
- 看了下传统的方法,觉得不好,太麻烦。自己重写了个,思路比较新。这个函数的优点是html代码可以很简洁,使用图片也可以很少,只需要两张图片。事
- 本篇文章主要基于python语言和OpenCV库(cv2)进行车牌区域识别和字符分割,开篇之前针对在python中安装opencv的环境这里
- 最近在做一个项目,用双通道神经网络,每个通道输入不同数据训练,具有相同label。开始没想到如何实现,网上很多例子都是单通道,即便找到双通道
- 目录1.简介2.如何解决3.虚线框类代码4.测试UI界面如下图所示5.拖动时的效果图如下所示1.简介看到很多才学QT的人都会问为啥无边框拖动
- 在实际工作或面试中,我们经常会遇到“数组去重”问题,接下来就是使用js实现的数组去重的多种方法:1.将数组的每一个元素依次与其他元素做比较,
- 本文实例为大家分享了python实现名片管理系统源代码,供大家参考,具体内容如下import osdef print_menu(): pri
- 1.Cuda的下载安装及配置 首先我们要确定本机是否有独立显卡。在计算机-管理-设备管
- 这个语法是用来代替传统的try...finally语法的。 with EXPRESSION [ as VARIABLE] WITH-BLOC
- 在研究ezSQL的时候就看到了mssql_connect()等一些php提供的连接MSSQL的函数,本以为php这个开源的风靡世界的编程语言
- 第一种: <script language=”javascript” type=”text/javascript”> windo
- Pandas中的resample,重新采样,是对原样本重新处理的一个方法,是一个对常规时间序列数据重新采样和频率转换的便捷的方法。方法的格式
- 之前用Class类来搭建神经网络class Neuro_net(torch.nn.Module): ""&q
- 前言开始几天,我是使用很原始的方法,自己去获取天气预报截图,再手动发送给小姐姐。连续几天之后我一想:不对呀,我怎么说也是一个程序猿,怎么能用