vue對(duì)于項(xiàng)目的優(yōu)化

項(xiàng)目的優(yōu)化主要有以下幾點(diǎn)方案:

只是一個(gè)參考

優(yōu)化一:執(zhí)行build的時(shí)候移除 console

安裝一個(gè)插件(babel-plugin-transform-remove-console)在項(xiàng)目build階段移除所有的console信息
打開項(xiàng)目控制臺(tái),點(diǎn)擊依賴->開發(fā)依賴,輸入babel-plugin-transform-remove-console,安裝
打開babel.config.js,編輯代碼如下:

//項(xiàng)目發(fā)布階段需要用到的babel插件
const productPlugins = []

//判斷是開發(fā)還是發(fā)布階段
if(process.env.NODE_ENV === 'production'){
  //發(fā)布階段
  productPlugins.push("transform-remove-console")
}

module.exports = {
  "presets": [
    "@vue/app"
  ],
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ],
    // 發(fā)布產(chǎn)品時(shí)候的插件數(shù)組
    ...productPlugins
  ]
}

優(yōu)化二:生成打包報(bào)告

A.命令行形式生成打包報(bào)告
vue-cli-service build --report
B.在vue控制臺(tái)生成打包報(bào)告
點(diǎn)擊“任務(wù)”=>“build”=>“運(yùn)行”
運(yùn)行完畢之后點(diǎn)擊右側(cè)“分析”,“控制臺(tái)”面板查看報(bào)告

優(yōu)化三:修改webpack的默認(rèn)配置

默認(rèn)情況下,vue-cli 3.0生成的項(xiàng)目,隱藏了webpack配置項(xiàng),如果我們需要配置webpack
需要通過vue.config.js來配置。
具體配置參考:https://cli.vuejs.org/zh/config/#vue-config-js
在項(xiàng)目根目錄中創(chuàng)建vue.config.js文件,

module.exports = {
    chainWebpack:config=>{
        //發(fā)布模式
        config.when(process.env.NODE_ENV === 'production',config=>{
            //entry找到默認(rèn)的打包入口,調(diào)用clear則是刪除默認(rèn)的打包入口
            //add添加新的打包入口
            config.entry('app').clear().add('./src/main-prod.js')
        })
        //開發(fā)模式
        config.when(process.env.NODE_ENV === 'development',config=>{
            config.entry('app').clear().add('./src/main-dev.js')
        })
    }
}

補(bǔ)充:
chainWebpack可以通過鏈?zhǔn)骄幊痰男问剑薷膚ebpack配置
configureWebpack可以通過操作對(duì)象的形式,修改webpack配置
兩者具體的使用差異,參考vuejs的網(wǎng)址:
https://cli.vuejs.org/zh/guide/webpack.html#webpach-%E7%9B%B8%E5%85%B3

優(yōu)化四:通過externals 加載外部 CDN 資源

默認(rèn)情況下,依賴項(xiàng)的所有第三方包都會(huì)被打包到j(luò)s/chunk-vendors.******.js文件中,導(dǎo)致該js文件過大
那么我們可以通過externals排除這些包,使它們不被打包到j(luò)s/chunk-vendors.******.js文件中

module.exports = {
    chainWebpack:config=>{
        //發(fā)布模式
        config.when(process.env.NODE_ENV === 'production',config=>{
            //entry找到默認(rèn)的打包入口,調(diào)用clear則是刪除默認(rèn)的打包入口
            //add添加新的打包入口
            config.entry('app').clear().add('./src/main-prod.js')

            //使用externals設(shè)置排除項(xiàng)
            config.set('externals',{
                vue:'Vue',
                'vue-router':'VueRouter',
                axios:'axios',
                lodash:'_',
                echarts:'echarts',
                nprogress:'NProgress',
                'vue-quill-editor':'VueQuillEditor'
            })
        })
        //開發(fā)模式
        config.when(process.env.NODE_ENV === 'development',config=>{
            config.entry('app').clear().add('./src/main-dev.js')
        })
    }
}

設(shè)置好排除之后,為了使我們可以使用vue,axios等內(nèi)容,我們需要加載外部CDN的形式解決引入依賴項(xiàng)。
打開開發(fā)入口文件main-prod.js,刪除掉默認(rèn)的引入代碼

import Vue from 'vue'
import App from './App.vue'
import router from './router'
// import './plugins/element.js'
//導(dǎo)入字體圖標(biāo)
import './assets/fonts/iconfont.css'
//導(dǎo)入全局樣式
import './assets/css/global.css'
//導(dǎo)入第三方組件vue-table-with-tree-grid
import TreeTable from 'vue-table-with-tree-grid'
//導(dǎo)入進(jìn)度條插件
import NProgress from 'nprogress'
//導(dǎo)入進(jìn)度條樣式
// import 'nprogress/nprogress.css'
// //導(dǎo)入axios
import axios from 'axios'
// //導(dǎo)入vue-quill-editor(富文本編輯器)
import VueQuillEditor from 'vue-quill-editor'
// //導(dǎo)入vue-quill-editor的樣式
// import 'quill/dist/quill.core.css'
// import 'quill/dist/quill.snow.css'
// import 'quill/dist/quill.bubble.css'

axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/'
//請(qǐng)求在到達(dá)服務(wù)器之前,先會(huì)調(diào)用use中的這個(gè)回調(diào)函數(shù)來添加請(qǐng)求頭信息
axios.interceptors.request.use(config => {
  //當(dāng)進(jìn)入request攔截器,表示發(fā)送了請(qǐng)求,我們就開啟進(jìn)度條
  NProgress.start()
  //為請(qǐng)求頭對(duì)象,添加token驗(yàn)證的Authorization字段
  config.headers.Authorization = window.sessionStorage.getItem("token")
  //必須返回config
  return config
})
//在response攔截器中,隱藏進(jìn)度條
axios.interceptors.response.use(config =>{
  //當(dāng)進(jìn)入response攔截器,表示請(qǐng)求已經(jīng)結(jié)束,我們就結(jié)束進(jìn)度條
  NProgress.done()
  return config
})
Vue.prototype.$http = axios

Vue.config.productionTip = false

//全局注冊(cè)組件
Vue.component('tree-table', TreeTable)
//全局注冊(cè)富文本組件
Vue.use(VueQuillEditor)

//創(chuàng)建過濾器將秒數(shù)過濾為年月日,時(shí)分秒
Vue.filter('dateFormat',function(originVal){
  const dt = new Date(originVal)
  const y = dt.getFullYear()
  const m = (dt.getMonth()+1+'').padStart(2,'0')
  const d = (dt.getDate()+'').padStart(2,'0')

  const hh = (dt.getHours()+'').padStart(2,'0')
  const mm = (dt.getMinutes()+'').padStart(2,'0')
  const ss = (dt.getSeconds()+'').padStart(2,'0')

  return `${y}-${m}-$u0z1t8os ${hh}:${mm}:${ss}`
})

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

然后打開public/index.html添加外部cdn引入代碼

<!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>電商后臺(tái)管理系統(tǒng)</title>

    <!-- nprogress 的樣式表文件 -->
    <link rel="stylesheet"  />
    <!-- 富文本編輯器 的樣式表文件 -->
    <link rel="stylesheet"  />
    <link rel="stylesheet"  />
    <link rel="stylesheet"  />
    <!-- element-ui 的樣式表文件 -->
    <link rel="stylesheet"  />

    <script src="https://cdn.staticfile.org/vue/2.5.22/vue.min.js"></script>
    <script src="https://cdn.staticfile.org/vue-router/3.0.1/vue-router.min.js"></script>
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
    <script src="https://cdn.staticfile.org/lodash.js/4.17.11/lodash.min.js"></script>
    <script src="https://cdn.staticfile.org/echarts/4.1.0/echarts.min.js"></script>
    <script src="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.js"></script>
    <!-- 富文本編輯器的 js 文件 -->
    <script src="https://cdn.staticfile.org/quill/1.3.4/quill.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue-quill-editor@3.0.4/dist/vue-quill-editor.js"></script>

    <!-- element-ui 的 js 文件 -->
    <script src="https://cdn.staticfile.org/element-ui/2.8.2/index.js"></script>

  </head>
  <body>
    <noscript>
      <strong>We're sorry but vue_shop 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>

優(yōu)化五:定制首頁內(nèi)容

開發(fā)環(huán)境的首頁和發(fā)布環(huán)境的首頁展示內(nèi)容的形式有所不同
如開發(fā)環(huán)境中使用的是import加載第三方包,而發(fā)布環(huán)境則是使用CDN,那么首頁也需根據(jù)環(huán)境不同來進(jìn)行不同的實(shí)現(xiàn)
我們可以通過插件的方式來定制首頁內(nèi)容,打開vue.config.js,編寫代碼如下:

module.exports = {
    chainWebpack:config=>{
        config.when(process.env.NODE_ENV === 'production',config=>{
            ......
            
            //使用插件
            config.plugin('html').tap(args=>{
                //添加參數(shù)isProd
                args[0].isProd = true
                return args
            })
        })

        config.when(process.env.NODE_ENV === 'development',config=>{
            config.entry('app').clear().add('./src/main-dev.js')

            //使用插件
            config.plugin('html').tap(args=>{
                //添加參數(shù)isProd
                args[0].isProd = false
                return args
            })
        })
    }
}

然后在public/index.html中使用插件判斷是否為發(fā)布環(huán)境并定制首頁內(nèi)容

<!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 - ' %>電商后臺(tái)管理系統(tǒng)</title>

    <% if(htmlWebpackPlugin.options.isProd){ %>
    <!-- nprogress 的樣式表文件 -->
    <link rel="stylesheet"  />
    ........
    <!-- element-ui 的 js 文件 -->
    <script src="https://cdn.staticfile.org/element-ui/2.8.2/index.js"></script>
    <% } %>
  </head>
  .......

優(yōu)化六:路由懶加載

當(dāng)路由被訪問時(shí)才加載對(duì)應(yīng)的路由文件,就是路由懶加載。
路由懶加載實(shí)現(xiàn)步驟:
1.安裝 @babel/plugin-syntax-dynamic-import
打開vue控制臺(tái),點(diǎn)擊依賴->安裝依賴->開發(fā)依賴->搜索@babel/plugin-syntax-dynamic-import
點(diǎn)擊安裝。

2.在babel.config.js中聲明該插件,打開babel.config.js

//項(xiàng)目發(fā)布階段需要用到的babel插件
const productPlugins = []

//判斷是開發(fā)還是發(fā)布階段
if(process.env.NODE_ENV === 'production'){
  //發(fā)布階段
  productPlugins.push("transform-remove-console")
}

module.exports = {
  "presets": [
    "@vue/app"
  ],
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ],
    ...productPlugins,
    //配置路由懶加載插件
    "@babel/plugin-syntax-dynamic-import"
  ]
}

3.將路由更改為按需加載的形式,打開router.js,更改引入組件代碼如下:

import Vue from 'vue'
import Router from 'vue-router'
const Login = () => import(/* webpackChunkName:"login_home_welcome" */ './components/Login.vue')
// import Login from './components/Login.vue'
const Home = () => import(/* webpackChunkName:"login_home_welcome" */ './components/Home.vue')
// import Home from './components/Home.vue'
const Welcome = () => import(/* webpackChunkName:"login_home_welcome" */ './components/Welcome.vue')
// import Welcome from './components/Welcome.vue'
const Users = () => import(/* webpackChunkName:"user" */ './components/user/Users.vue')
// import Users from './components/user/Users.vue'
const Rights = () => import(/* webpackChunkName:"power" */ './components/power/Rights.vue')
// import Rights from './components/power/Rights.vue'
const Roles = () => import(/* webpackChunkName:"power" */ './components/power/Roles.vue')
// import Roles from './components/power/Roles.vue'
const Cate = () => import(/* webpackChunkName:"goods" */ './components/goods/Cate.vue')
// import Cate from './components/goods/Cate.vue'
const Params = () => import(/* webpackChunkName:"goods" */ './components/goods/Params.vue')
// import Params from './components/goods/Params.vue'
const GoodList = () => import(/* webpackChunkName:"goods" */ './components/goods/List.vue')
// import GoodList from './components/goods/List.vue'
const GoodAdd = () => import(/* webpackChunkName:"goods" */ './components/goods/Add.vue')
// import GoodAdd from './components/goods/Add.vue'
const Order = () => import(/* webpackChunkName:"order" */ './components/order/Order.vue')
// import Order from './components/order/Order.vue'
const Report = () => import(/* webpackChunkName:"report" */ './components/report/Report.vue')
// import Report from './components/report/Report.vue'

優(yōu)化七:開啟gzip壓縮

打開vue_shop_server文件夾的終端,輸入命令:npm i compression -D
打開app.js,編寫代碼:

const express = require('express')

const compression = require('compression')

const app = express()

app.use(compression())
app.use(express.static('./dist'))

app.listen(8998,()=>{
    console.log("server running at http://127.0.0.1:8998")
})

配置https服務(wù)

配置https服務(wù)一般是后臺(tái)進(jìn)行處理,前端開發(fā)人員了解即可。
首先,需要申請(qǐng)SSL證書,進(jìn)入https://freessl.cn官網(wǎng)
在后臺(tái)導(dǎo)入證書,打開今天資料/素材,復(fù)制素材中的兩個(gè)文件到vue_shop_server中
打開app.js文件,編寫代碼導(dǎo)入證書,并開啟https服務(wù)

const express = require('express')
const compression = require('compression')
const https = require('https')
const fs = require('fs')

const app = express()
//創(chuàng)建配置對(duì)象設(shè)置公鑰和私鑰
const options = {
    cert:fs.readFileSync('./full_chain.pem'),
    key:fs.readFileSync('./private.key')
}

app.use(compression())
app.use(express.static('./dist'))

// app.listen(8998,()=>{
//     console.log("server running at http://127.0.0.1:8998")
// })

//啟動(dòng)https服務(wù)
https.createServer(options,app).listen(443)

注意:因?yàn)槲覀兪褂玫淖C書有問題,所以無法正常使用https服務(wù)

使用pm2管理應(yīng)用

打開vue_shop_server文件夾的終端,輸入命令:npm i pm2 -g
使用pm2啟動(dòng)項(xiàng)目,在終端中輸入命令:pm2 start app.js --name 自定義名稱
查看項(xiàng)目列表命令:pm2 ls
重啟項(xiàng)目:pm2 restart 自定義名稱
停止項(xiàng)目:pm2 stop 自定義名稱
刪除項(xiàng)目:pm2 delete 自定義名稱

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容