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

效果图 

vue项目打包优化的方法实战记录

优化 按需加载第三方工具包(例如 lodash)或者使用 CDN 的方式进行处理。

按需加载使用的工具方法  (当用到的工具方法少时按需加载打包)  用到的较多通过cdn 

通过form lodash 搜索 哪处用到

例如此处的 1.

vue项目打包优化的方法实战记录

vue项目打包优化的方法实战记录

换成 

vue项目打包优化的方法实战记录

按需导入 

效果图

vue项目打包优化的方法实战记录

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
 ]
}

 效果图

vue项目打包优化的方法实战记录

3. Close SourceMap

生产环境关闭 功能

vue.config.js

module.exports = {
 productionSourceMap: false
}

 效果图

vue项目打包优化的方法实战记录

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>

效果图

vue项目打包优化的方法实战记录

继续对 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>

效果图

vue项目打包优化的方法实战记录

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 提取...

vue项目打包优化的方法实战记录

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

标签:vue,打包,优化
0
投稿

猜你喜欢

  • 如何将计数器的值赋给一个变量?

    2009-12-03 20:02:00
  • php查找指定目录下指定大小文件的方法

    2023-09-03 17:53:36
  • PostgreSQL 如何获取当前日期时间及注意事项

    2024-01-17 12:00:10
  • python使用rsa非对称加密过程解析

    2021-06-15 00:14:51
  • win7下MySql 5.7安装配置方法图文教程

    2024-01-20 21:04:12
  • 如何在mac下配置python虚拟环境

    2023-06-16 18:09:37
  • python的setattr函数实例用法

    2023-08-17 18:49:59
  • php判断输入不超过mysql的varchar字段的长度范围

    2023-11-14 12:02:10
  • 探讨select in 在postgresql的效率问题

    2024-01-20 01:41:41
  • python实现五子棋双人对弈

    2023-11-14 05:36:10
  • Python 统计位数为偶数的数字代码详解

    2023-12-05 19:43:03
  • mysql 左连接、右连接和内连接

    2024-01-22 10:14:39
  • 让javascript加载速度倍增的方法(解决JS加载速度慢的问题)

    2024-04-19 11:03:22
  • python 用户交互输入input的4种用法详解

    2021-09-10 05:19:34
  • 解决python中导入win32com.client出错的问题

    2023-02-17 11:01:45
  • tensorflow训练中出现nan问题的解决

    2023-02-10 09:34:09
  • Python3.4学习笔记之列表、数组操作示例

    2021-04-10 10:56:11
  • vscode 配置 python3开发环境的方法

    2022-09-05 22:54:34
  • Mysql导入导出工具Mysqldump和Source命令用法详解

    2024-01-23 19:46:52
  • 连接mysql的常用工具分享

    2024-01-21 20:01:18
  • asp之家 网络编程 m.aspxhome.com