• vue项目打包优化的方法


    1.按需加载第三方库

    例如 ElementUI、lodash 等

    a, 装包

    npm install babel-plugin-component -D

    b, babel.config.js

    1. module.exports = {
    2. "presets": [
    3. "@vue/cli-plugin-babel/preset"
    4. ],
    5. "plugins": [
    6. [
    7. "component",
    8. {
    9. "libraryName": "element-ui",
    10. "styleLibraryName": "theme-chalk"
    11. }
    12. ]
    13. ]
    14. }

    c, main.js

    1. import ElementUI from 'element-ui'
    2. import 'element-ui/lib/theme-chalk/index.css'
    3. Vue.use(ElementUI)

    换成

    import './plugins/element.js'

    element.js

    1. import Vue from 'vue'
    2. 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'
    3. Vue.use(Button)
    4. Vue.use(Form)
    5. Vue.use(FormItem)
    6. Vue.use(Input)
    7. Vue.use(Header)
    8. Vue.use(Container)
    9. Vue.use(Aside)
    10. Vue.use(Main)
    11. Vue.use(Menu)
    12. Vue.use(Submenu)
    13. Vue.use(MenuItemGroup)
    14. Vue.use(MenuItem)
    15. Vue.use(Breadcrumb)
    16. Vue.use(BreadcrumbItem)
    17. Vue.use(Card)
    18. Vue.use(Row)
    19. Vue.use(Col)
    20. Vue.use(Table)
    21. Vue.use(TableColumn)
    22. Vue.use(Switch)
    23. Vue.use(Tooltip)
    24. Vue.use(Pagination)
    25. Vue.use(Dialog)
    26. Vue.use(Tag)
    27. Vue.use(Tree)
    28. Vue.use(Select)
    29. Vue.use(Option)
    30. Vue.use(Cascader)
    31. Vue.use(Alert)
    32. Vue.use(Tabs)
    33. Vue.use(TabPane)
    34. Vue.use(Steps)
    35. Vue.use(Step)
    36. Vue.use(CheckboxGroup)
    37. Vue.use(Checkbox)
    38. Vue.use(Upload)
    39. Vue.use(Timeline)
    40. Vue.use(TimelineItem)
    41. // 把弹框组件挂着到了 vue 的原型对象上,这样每一个组件都可以直接通过 this 访问
    42. Vue.prototype.$message = Message
    43. 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

    1. const prodPlugins = []
    2. if (process.env.NODE_ENV === 'production') {
    3. prodPlugins.push('transform-remove-console')
    4. }
    5. module.exports = {
    6. presets: ['@vue/cli-plugin-babel/preset'],
    7. plugins: [
    8. [
    9. 'component',
    10. {
    11. libraryName: 'element-ui',
    12. styleLibraryName: 'theme-chalk'
    13. }
    14. ],
    15. ...prodPlugins
    16. ]
    17. }

     效果图

    3. Close SourceMap

    生产环境关闭 功能

    vue.config.js

    1. module.exports = {
    2. productionSourceMap: false
    3. }

     效果图

     

    4. Externals && CDN

    通过 externals 排除第三方 JS 和 CSS 文件打包,使用 CDN 加载。

    vue.config.js

    1. module.exports = {
    2. productionSourceMap: false,
    3. chainWebpack: (config) => {
    4. config.when(process.env.NODE_ENV === 'production', (config) => {
    5. const cdn = {
    6. js: [
    7. 'https://cdn.staticfile.org/vue/2.6.11/vue.min.js',
    8. 'https://cdn.staticfile.org/vue-router/3.1.3/vue-router.min.js',
    9. 'https://cdn.staticfile.org/axios/0.18.0/axios.min.js',
    10. 'https://cdn.staticfile.org/echarts/4.1.0/echarts.min.js',
    11. 'https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.js',
    12. 'https://cdn.staticfile.org/quill/1.3.4/quill.min.js',
    13. 'https://cdn.jsdelivr.net/npm/vue-quill-editor@3.0.4/dist/vue-quill-editor.js'
    14. ],
    15. css: [
    16. 'https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.css',
    17. 'https://cdn.staticfile.org/quill/1.3.4/quill.core.min.css',
    18. 'https://cdn.staticfile.org/quill/1.3.4/quill.snow.min.css',
    19. 'https://cdn.staticfile.org/quill/1.3.4/quill.bubble.min.css'
    20. ]
    21. }
    22. config.set('externals', {
    23. vue: 'Vue',
    24. 'vue-router': 'VueRouter',
    25. axios: 'axios',
    26. echarts: 'echarts',
    27. nprogress: 'NProgress',
    28. 'nprogress/nprogress.css': 'NProgress',
    29. 'vue-quill-editor': 'VueQuillEditor',
    30. 'quill/dist/quill.core.css': 'VueQuillEditor',
    31. 'quill/dist/quill.snow.css': 'VueQuillEditor',
    32. 'quill/dist/quill.bubble.css': 'VueQuillEditor'
    33. })
    34. config.plugin('html').tap((args) => {
    35. args[0].isProd = true
    36. args[0].cdn = cdn
    37. return args
    38. })
    39. })
    40. }
    41. }

    public/index.html

    1. DOCTYPE html>
    2. </div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="10"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line"> <%= htmlWebpackPlugin.options.title %></div></div></li><li><div class="hljs-ln-numbers"><div class="hljs-ln-line hljs-ln-n" data-line-number="11"></div></div><div class="hljs-ln-code"><div class="hljs-ln-line">
    3. <% if(htmlWebpackPlugin.options.isProd){ %>
    4. <% for(var css of htmlWebpackPlugin.options.cdn.css) { %>
    5. <% } %>
    6. <% } %>
    7. We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
    8. Please enable it to continue.
    9. <% if(htmlWebpackPlugin.options.isProd){ %>
    10. <% for(var js of htmlWebpackPlugin.options.cdn.js) { %>
    11. <% } %>
    12. <% } %>

    效果图

     

    继续对 ElementUI 的加载方式进行优化 

    vue.config.js

    1. module.exports = {
    2. chainWebpack: config => {
    3. config.when(process.env.NODE_ENV === 'production', config => {
    4. config.set('externals', {
    5. './plugins/element.js': 'ELEMENT'
    6. })
    7. config.plugin('html').tap(args => {
    8. args[0].isProd = true
    9. return args
    10. })
    11. })
    12. }
    13. }

     public/index.html

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="utf-8">
    5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
    6. <meta name="viewport" content="width=device-width,initial-scale=1.0">
    7. <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    8. <title>
    9. <%= htmlWebpackPlugin.options.isProd ? '' : 'dev - ' %>电商后台管理系统
    10. title>
    11. <% if(htmlWebpackPlugin.options.isProd){ %>
    12. <link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.13.0/theme-chalk/index.css" />
    13. <script src="https://cdn.staticfile.org/element-ui/2.13.0/index.js">script>
    14. <% } %>
    15. head>
    16. <body>
    17. <noscript>
    18. <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
    19. Please enable it to continue.strong>
    20. noscript>
    21. <div id="app">div>
    22. body>
    23. html>

    效果图

    5.路由懒加载的方式

    1. import Vue from 'vue'
    2. import VueRouter from 'vue-router'
    3. import Login from '../components/Login.vue'
    4. Vue.use(VueRouter)
    5. const routes = [
    6. {
    7. path: '/',
    8. redirect: '/login'
    9. },
    10. {
    11. path: '/login',
    12. component: Login
    13. },
    14. {
    15. path: '/Home',
    16. component: () => import('../components/Home.vue'),
    17. redirect: '/welcome',
    18. children: [
    19. {
    20. path: '/welcome',
    21. component: () => import('../components/Welcome.vue')
    22. },
    23. {
    24. path: '/users',
    25. component: () => import('../components/user/Users.vue')
    26. },
    27. {
    28. path: '/rights',
    29. component: () => import('../components/power/Rights.vue')
    30. },
    31. {
    32. path: '/roles',
    33. component: () => import('../components/power/Roles.vue')
    34. },
    35. {
    36. path: '/categories',
    37. component: () => import('../components/goods/Cate.vue')
    38. },
    39. {
    40. path: '/params',
    41. component: () => import('../components/goods/Params.vue')
    42. },
    43. {
    44. path: '/goods',
    45. component: () => import('../components/goods/List.vue')
    46. },
    47. {
    48. path: '/goods/add',
    49. component: () => import('../components/goods/Add.vue')
    50. },
    51. {
    52. path: '/orders',
    53. component: () => import('../components/order/Order.vue')
    54. },
    55. {
    56. path: '/reports',
    57. component: () => import('../components/report/Report.vue')
    58. }
    59. ]
    60. }
    61. ]
    62. const router = new VueRouter({
    63. routes
    64. })
    65. router.beforeEach((to, from, next) => {
    66. // to 要访问的路径
    67. // from 从哪里来的
    68. // next() 直接放行,next('/login') 表示跳转
    69. // 要访问 /login 的话那直接放行
    70. if (to.path === '/login') return next()
    71. const tokenStr = window.sessionStorage.getItem('token')
    72. // token 不存在那就跳转到登录页面
    73. if (!tokenStr) return next('/login')
    74. // 否则 token 存在那就放行
    75. next()
    76. })
    77. export default router

    其他:图片压缩、CSS 压缩和提取、JS 提取...

    1. 部署到 Nginx

    下载 Nginx,双击运行 nginx.exe,浏览器输入 localhost 能看到界面表示服务启动成功!

    前端 axios 中的 baseURL 指定为 /api,配置 vue.config.js 代理如下

    1. module.exports = {
    2. devServer: {
    3. proxy: {
    4. '/api': {
    5. target: 'http://127.0.0.1:8888',
    6. changeOrigin: true
    7. }
    8. }
    9. }
    10. }

    路由模式、基准地址、404 记得也配置一下

    1. const router = new VueRouter({
    2. mode: 'history',
    3. base: '/shop/',
    4. routes: [
    5. // ...
    6. {
    7. path: '*',
    8. component: NotFound
    9. }
    10. ]
    11. })

    执行 npm run build 打包,把 dist 中的内容拷贝到 Nginx 的 html 文件夹中

    修改 Nginx 配置

    1. http {
    2. server {
    3. listen 80;
    4. location / {
    5. # proxy_pass https://www.baidu.com;
    6. root html;
    7. index index.html index.htm;
    8. try_files $uri $uri/ /index.html;
    9. }
    10. location /api {
    11. # 重写地址
    12. # rewrite ^.+api/?(.*)$ /$1 break;
    13. # 代理地址
    14. proxy_pass http://127.0.0.1:8888;
    15. # 不用管
    16. proxy_redirect off;
    17. proxy_set_header Host $host;
    18. proxy_set_header X-Real-IP $remote_addr;
    19. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    20. }
    21. }
    22. }

    重启服务

    nginx -s reload

    访问 localhost 查看下效果吧

    1. 开启 Gzip 压缩

    前端通过 vue.config.js 配置,打包成带有 gzip 的文件

    1. const CompressionWebpackPlugin = require('compression-webpack-plugin')
    2. module.exports = {
    3. configureWebpack: config => {
    4. if (process.env.NODE_ENV === 'production') {
    5. config.plugins = [...config.plugins, new CompressionWebpackPlugin()]
    6. }
    7. }
    8. }

    Nginx 中开启 gzip 即可

     

  • 相关阅读:
    基于Springboot的特产销售平台设计与实现毕业设计源码091036
    《计算几何》学习笔记
    SSM框架具体功能实现
    存储器的分类
    CMU15-445 format\clang-format\clang-tidy 失败
    [C++] 哈希的模拟实现---闭散列法、开散列法(上)
    竞赛 车道线检测(自动驾驶 机器视觉)
    【node进阶】深度解析Koa框架---路由|静态资源|获取请求参数
    dubbo漫谈(一)
    NLP(2)--Transformer
  • 原文地址:https://blog.csdn.net/weixin_68531033/article/details/126342877