1. 程式人生 > 實用技巧 >Vue專案優化上線

Vue專案優化上線

專案優化上線

1.專案優化

①頁面進度條效果

執行依賴->nprogress

  1. 匯入包和樣式
// [main.js]
// 載入進度條包對應js和css
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
  1. 請求攔截器中配置進度條
// [main.js]
// axios請求攔截
axios.interceptors.request.use(config => {
  NProgress.start() // 在request中展示進度條
  // ......
})

axios.interceptors.request.use(config => {
  NProgress.done() // 在response中隱藏進度
  // ......
})

②移除console

在專案釋出build階段移除console

開發依賴->babel-plugin-transform-remove-console

babel.config.js全域性共享

// [babel.config.js]
// 專案釋出階段需要用到的bable外掛
const prodPlugins=[]


if (process.env.NODE_ENV ==='production'){
  prodPlugins.push('transform-remove-console')
}

module.exports = {
    // ......
    // 釋出產品時的外掛
    ...prodPlugins,
    // ......
  ]
}

③生成打包報告

  • 通過命令列引數的形式生成報告

    //通過vue-cli 的命令選項可以生成打包報告
    // --report選項可以生成report.html以幫助分析包內容
    vue-cli-service build --rport
    
  • 通過視覺化的UI面板直接檢視報告(推薦)

    在視覺化的UI面板中,通過控制檯和分析面板,可以方便地看到專案中所存在的問題。

④修改webpack的預設配置

在專案根目錄建立vue.config.js,匯出自定義配置選項的物件

// [vue.config.js]
module.exports={
    // 配置選項
}

⑤開發模式和釋出模式指定不同打包入口

在vue.config.js匯出的配置物件中,新增configureWebpack或chainWebpack節點,來自定義webpack的打包配置。
在這裡,configureWebpack和chainWebpack的作用相同,唯一的區別就是它們修改webpack配置的方式不同:

chainWebpac通過鏈式程式設計的形式,來修改預設的webpack配置

configureWebpack通過操作物件的形式,來修改預設的webpack配置

// [vue.config.js]
module.exports = {
    chainWebpack: config => {
        config.when(process.env.NODE_ENV === 'production', config => {
            config.entry('app').clear().add('./src/main-prod.js')
        })
        config.when(process.env.NODE_ENV === 'development', config => {
            config.entry('app').clear().add('./src/main-dev.js')
        })
    }
}

⑥第三方庫啟用CDN

通過externals載入外部 CDN資下,通過import語法匯入的第三方依賴包,最終會被打包合併到同一個檔案中,從而導致打包成功後,單檔案體積過大的問題。

為了解決上述問題,可以通過webpack的externals節點,來配置並載入外部的CDN資源。凡是宣告在externals中的第三方依賴包,都不會被打包。

  1. 配置資源,只要使用了指定包,就到全域性查詢對應資源
// [vue.config.js->釋出模式]
config.set('externals', {
    vue: 'Vue',
    // 'vue-router': 'VueRouter',
    axios: 'axios',
    lodash: '_',
    echarts: 'echarts',
    nprogress: 'NProgress',
    'vue-quill-editor': 'VueQuillEditor'
})
  1. 在index.html中新增樣式表資源,刪除main-prod.js中的樣式表
<!-- [public/index.html] -->
<!-- nprogress 的樣式表文件 -->
<link rel="stylesheet" href="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.css" />
<!-- 富文字編輯器的樣式表文件 -->
<link rel="stylesheet" href="https://cdn.staticfile.org/quill/1.3.4/quill.core.min.css" />
<link rel="stylesheet" href="https://cdn.staticfile.org/quill/1.3.4/quill.snow.min.css" />
<link rel="stylesheet" href="https://cdn.staticfile.org/quill/1.3.4/quill.bubble.min.css" />
  1. 在index.html中新增js檔案資源,刪除main-prod.js中的js資源
<!-- [public/index.html] -->
<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/[email protected]/dist/vue-quill-editor.js"></script>

Vue 打包後報錯 Uncaught TypeError: Cannot redefine property: $router

https://www.cnblogs.com/mengyouyouyou/p/10936171.html

⑦Element-U元件按需載入

雖然在開發階段,我們啟用了element-ui元件的按需載入,儘可能的減少了打包的體積,但是那些被按需載入的元件,還是佔用了較大的檔案體積。此時,我們可以將element-ui中的元件,也通過CDN的形式來載入,這樣能夠進一步減小打包後的檔案體積。

具體操作流程如下:

①在main-prod.js中,註釋掉element-ui按需載入的程式碼

②在index.html的頭部區域中,通過CDN載入element-ui的js和css樣式

<!-- [public/index.html] -->
<!--element-ui的樣式表文件-->
<link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.4.5/theme-chalk/index.css" />

<!-- element-ui的js檔案-->
<script src="https://cdn.staticfile.org/element-ui/2.4.5/index.js"></script>

if there's nested data, rowKey is required.

https://blog.csdn.net/qq_33846125/article/details/103608849

⑧路由懶載入

當打包構建專案時,JavaScript包會變得非常大,影響頁面載入。如果我們能把不同路由對應的元件分割成不同的程式碼塊,然後當路由

被訪問的時候才載入對應元件,這樣就更加高效了。

具體需要3步:

①開發依賴,安裝@babel/plugin-syntax-dynamic-import

②在babel.config.js配置檔案中宣告該外掛。

// [babel.config.js]
module.exports = {
  //......
  plugins: [
    // ......
    '@babel/plugin-syntax-dynamic-import'
  ]
}

③將路由改為按需載入的形式,示例程式碼如下:

當請求Foo時,因為在同一組中也會將Bar請求回來。

const Foo = () => import(/* webpackchunkName: "group-foo" */ './Foo.vue')
const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue')
const Baz= () => import(/* webpackchunkName: "group-boo" */ './Baz.vue ')
// [index.js]
const Login=()=>import(/* webpackChunkName:"login_home_welcome" */'../components/Login.vue')
const Home=()=>import(/* webpackChunkName:"login_home_welcome" */'../components/Home.vue')
const Welcome=()=>import(/* webpackChunkName:"login_home_welcome" */'../components/Welcome.vue')

const Users=()=>import(/* webpackChunkName:"users_rights_roles" */'../components/user/Users.vue')
const Rights=()=>import(/* webpackChunkName:"users_rights_roles" */'../components/rights/Rights.vue')
const Roles=()=>import(/* webpackChunkName:"users_rights_roles" */'../components/rights/Roles.vue')

⑨首頁內容定製

自定義首頁標題

// [vue.config.js]
//釋出模式         
config.plugin('html').tap(args => {
    args[0].isProd = true
    return args
})
// 開發模式
config.plugin('html').tap(args => {
    args[0].isProd = false
    return args
})
<!-- [public/index.html] -->
<!-- 按需渲染頁面標題 -->
<title><%= htmlWebpackPlugin.options.isProd ? '':'dev-' %><%= htmlWebpackPlugin.options.title %></title>
<!-- 按需載入外部的CDN資源 -->
<% if(htmlWebpackPlugin.options.isProd){%>
   釋出模式下載入的js和css
<%}%>

2.專案上線

①通過node建立web伺服器

資料夾vue-shop-server,建立node專案,初始化包管理檔案npm init -y,並安裝expressnpm i express -S,通過express快速建立web伺服器,將vue打包生成的dist資料夾複製貼上到vue-shop-server中,並託管為靜態資源即可,關鍵程式碼如下:

// [vue-shop-server/app.js]
const express =require ('express')
//建立web伺服器
const app = express ()
//託管靜態資源
app.use (express.static ('./dist')
//啟動web伺服器
app.listen(80,()=> {
	console.log ('web server running at http://127.0.0.1')
} )

②開啟gzip配置

使用gzip可以減小檔案體積,使傳輸速度更快。

可以通過伺服器端使用Express做gzip壓縮。其配置如下:

//安裝相應包
npm install compression -S
// [vue-shop-server/app.js]
//匯入包
const compression = require ('compression') ;
//託管靜態資源之前啟用中介軟體
app.use(compression()) ;

③配置https服務

  • 申請SSL 證書(https://freessl.org)

    ①進入https://freessl.cn/官網,輸入要申請的域名並選擇品牌。

    ②輸入自己的郵箱並選擇相關選項。

    ③驗證DNS(在域名管理後臺新增TXT記錄)。

    ④驗證通過之後,下載SSL證書( full_chain.pem 公鑰; private.key私鑰)。

  • 在後臺專案匯入證書

// [vue-shop-server/app.js]
const https = require ('https') ;
const fs = require ('fs');

const options = {
    cert: fs.readFilesync ('./full_chain.pem') ,
    key: fs.readFilesync ('./private.key')
}

https.createserver(options,app).listen (443);

④使用pm2管理應用

在伺服器中安裝pm2: npm i pm2 -g

啟動專案: pm2 start 指令碼 --name 自定義名稱

檢視執行專案:pm2 ls

重啟專案: pm2 restart 自定義名稱

停止專案: pm2 stop 自定義名稱pm2 stop 專案id

刪除專案: pm2 delete 自定義名稱

專案目錄下,啟動專案pm2 start .\app.js --name vue-shop