vue项目打包怎么优化
导读:本文共7659.5字符,通常情况下阅读需要26分钟。同时您也可以点击右侧朗读,来听本文内容。按键盘←(左) →(右) 方向键可以翻页。
摘要:1.按需加载第三方库例如 ElementUI、lodash 等a, 装包npminstallbabel-plugin-component-Db, babel.config.jsmodule.exports={"presets":["@vue/cli-plugin-babel/preset"],"plugins":[["... ...
目录
(为您整理了一些要点),点击可以直达。1.按需加载第三方库
例如 ElementUI、lodash 等
a, 装包
npminstallbabel-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
importElementUIfrom'element-ui'
import'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
换成
import'./plugins/element.js'
element.js
importVuefrom'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
npmibabel-plugin-transform-remove-console-D
babel.config.js
constprodPlugins=[]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)=>{
constcdn={
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
returnargs
})
})
}
}
public/index.html
<!DOCTYPEhtml>
<htmllang="en"><head>
<metacharset="utf-8">
<metahttp-equiv="X-UA-Compatible"content="IE=edge">
<metaname="viewport"content="width=device-width,initial-scale=1.0">
<linkrel="icon"href="<%=BASE_URL%>favicon.ico">
<title>
<%=htmlWebpackPlugin.options.title%>
</title>
<%if(htmlWebpackPlugin.options.isProd){%>
<%for(varcssofhtmlWebpackPlugin.options.cdn.css){%>
<linkrel="stylesheet"href="<%=css%>">
<%}%>
<%}%>
</head><body>
<noscript>
<strong>We'resorrybut<%=htmlWebpackPlugin.options.title%>doesn'tworkproperlywithoutJavaScriptenabled.
Pleaseenableittocontinue.</strong>
</noscript>
<divid="app"></div>
<!--builtfileswillbeautoinjected-->
<%if(htmlWebpackPlugin.options.isProd){%>
<%for(varjsofhtmlWebpackPlugin.options.cdn.js){%>
<scriptsrc="<%=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
returnargs
})
})
}
}
public/index.html
<!DOCTYPEhtml>
<htmllang="en"><head>
<metacharset="utf-8">
<metahttp-equiv="X-UA-Compatible"content="IE=edge">
<metaname="viewport"content="width=device-width,initial-scale=1.0">
<linkrel="icon"href="<%=BASE_URL%>favicon.ico">
<title>
<%=htmlWebpackPlugin.options.isProd?'':'dev-'%>电商后台管理系统
</title>
<%if(htmlWebpackPlugin.options.isProd){%>
<!--element-ui的样式表文件-->
<linkrel="stylesheet"href="https://cdn.staticfile.org/element-ui/2.13.0/theme-chalk/index.css"/><!--element-ui的js文件-->
<scriptsrc="https://cdn.staticfile.org/element-ui/2.13.0/index.js"></script>
<%}%>
</head><body>
<noscript>
<strong>We'resorrybut<%=htmlWebpackPlugin.options.title%>doesn'tworkproperlywithoutJavaScriptenabled.
Pleaseenableittocontinue.</strong>
</noscript>
<divid="app"></div>
<!--builtfileswillbeautoinjected-->
</body></html>
效果图
5.路由懒加载的方式
importVuefrom'vue'
importVueRouterfrom'vue-router'
importLoginfrom'../components/Login.vue'
Vue.use(VueRouter)constroutes=[
{
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')
}
]
}
]constrouter=newVueRouter({
routes
})router.beforeEach((to,from,next)=>{
//to要访问的路径
//from从哪里来的
//next()直接放行,next('/login')表示跳转
//要访问/login的话那直接放行
if(to.path==='/login')returnnext()
consttokenStr=window.sessionStorage.getItem('token')
//token不存在那就跳转到登录页面
if(!tokenStr)returnnext('/login')
//否则token存在那就放行
next()
})exportdefaultrouter
其他:图片压缩、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 记得也配置一下
constrouter=newVueRouter({
mode:'history',
base:'/shop/',
routes:[
//...
{
path:'*',
component:NotFound
}
]
})
执行 npm run build 打包,把 dist 中的内容拷贝到 Nginx 的 html 文件夹中
修改 Nginx 配置
http{
server{
listen80;location/{
proxy_passhttps://www.baidu.com;
roothtml;
indexindex.htmlindex.htm;
try_files$uri$uri//index.html;
}
location/api{重写地址
rewrite^.+api/?(.*)$/$1break;
代理地址
proxy_passhttp://127.0.0.1:8888;
不用管
proxy_redirectoff;
proxy_set_headerHost$host;
proxy_set_headerX-Real-IP$remote_addr;
proxy_set_headerX-Forwarded-For$proxy_add_x_forwarded_for;
}
}
}
重启服务
nginx-sreload
访问 localhost 查看下效果吧
开启 Gzip 压缩
前端通过 vue.config.js 配置,打包成带有 gzip 的文件
constCompressionWebpackPlugin=require('compression-webpack-plugin')module.exports={
configureWebpack:config=>{
if(process.env.NODE_ENV==='production'){
config.plugins=[...config.plugins,newCompressionWebpackPlugin()]
}
}
}
Nginx 中开启 gzip 即可
vue项目打包怎么优化的详细内容,希望对您有所帮助,信息来源于网络。