vue項目打包優化的方法實戰記錄

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/[email protected]/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="<%=%20BASE_URL%20%>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="<%=%20BASE_URL%20%>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 即可

總結

到此這篇關於vue項目打包優化的文章就介紹到這瞭,更多相關vue項目打包優化內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: