current position:Home>Vue project optimization

Vue project optimization

2022-04-29 07:33:02Zhi jiangpeng

Network request add progress bar

1. Add a progress bar effect to the project , Open the project console first , Open dependency , install nprogress

2.main.js Add code to

npm install --save nprogress
// Import progress bar plug-in 
import NProgress from 'nprogress'
// Import progress bar style ( It's in the bag )
import 'nprogress/nprogress.css'
.....
// Before the request reaches the server , I'll call use This callback function in to add request header information 
axios.interceptors.request.use(config => {
  // When entering request Interceptor , Indicates that a request was sent , Let's start the progress bar 
  NProgress.start()
  // For the request header object , add to token Verified Authorization Field 
  config.headers.Authorization = window.sessionStorage.getItem("token")
  // Must return config
  return config
})
// stay response In the interceptor , Hide progress bar 
axios.interceptors.response.use(config =>{
  // When entering response Interceptor , Indicates that the request has ended , We'll end the progress bar 
  NProgress.done()
  return config
})

Packaging warning resolution

1. The results printed on the console are displayed because there are redundant console sentence , To solve this problem , Let's look at a plug-in babel-plugin-transform-remove-console

 Insert picture description here

 Insert picture description here 1. download  

npm install babel-plugin-transform-remove-console --save-dev

2 . add to babel.config.js

//  This is needed in the project release phase  babel  plug-in unit 
//----------------------------------- Start 
const prodPlugins = []
if (process.env.NODE_ENV === 'production') {
  prodPlugins.push('transform-remove-console')
}
//----------------------------------- end 
module.exports = {
  presets: ['@vue/app'],
  plugins: [
    [
      'component',
      {
        libraryName: 'element-ui',
        styleLibraryName: 'theme-chalk'
      }
    ],
//-------------------- Start 
    //  Array of plug-ins when releasing products 
    ...prodPlugins,
//--------------------- end 
    '@babel/plugin-syntax-dynamic-import'
  ]
}

Generate packaged reports

A. Generate packaged report in command line form
vue-cli-service build --report
B. stay vue The console generates packaged reports ( recommend , Just look directly )
Click on “ Mission ”=>“build”=>“ function ”
After running, click on the right “ analysis ”,“ Console ” Panel view report  

vue-cli-service build --report

modify webpack Default configuration

1. By default ,vue-cli 3.0 Generated project , Hide the webpack Configuration item , If we need to configure webpack
Need to pass through vue.config.js To configure the .
Create... In the project root directory vue.config.js file

2.chainWebpack It can be in the form of chain programming , modify webpack To configure
3.configureWebpack It can be in the form of operation object , modify webpack To configure

4.2 and 3 Same effect

module.exports = {
    chainWebpack:config=>{
        // Release pattern 
        config.when(process.env.NODE_ENV === 'production',config=>{
            //entry Find the default packaging entry , call clear Delete the default packaging entry 
            //add Add a new packaging entry 
            config.entry('app').clear().add('./src/main-prod.js')
        })
        // Development mode 
        config.when(process.env.NODE_ENV === 'development',config=>{
            config.entry('app').clear().add('./src/main-dev.js')
        })
    }
}

Load external CDN

By default , All third-party packages of dependencies are packaged into js/chunk-vendors.******.js In file , This leads to the js File is too large.
Then we can pass externals Exclude these packages , So that they are not packaged into js/chunk-vendors.******.js In file

 main.js

module.exports = {
    chainWebpack:config=>{
        // Release pattern 
        config.when(process.env.NODE_ENV === 'production',config=>{
            //entry Find the default packaging entry , call clear Delete the default packaging entry 
            //add Add a new packaging entry 
            config.entry('app').clear().add('./src/main-prod.js')
//---------------------------------------------------------- Start 
            // Use externals Set exclusions 
            config.set('externals',{
                vue:'Vue',
                'vue-router':'VueRouter',
                axios:'axios',
                lodash:'_',
                echarts:'echarts',
                nprogress:'NProgress',
                'vue-quill-editor':'VueQuillEditor'
            })
        })
//-------------------------------------------------------------- end 
        // Development mode 
        config.when(process.env.NODE_ENV === 'development',config=>{
            config.entry('app').clear().add('./src/main-dev.js')
        })
    }

After setting the exclusion , So that we can use vue,axios The content such as , We need to load external CDN Solve the introduction of dependencies in the form of .
Open the development portal file main-prod.js, Delete the default import code

 main.js


import Vue from 'vue'
import App from './App.vue'
import router from './router'
// import './plugins/element.js'
// Import Font Icon 
import './assets/fonts/iconfont.css'
// Import global styles 
import './assets/css/global.css'
// Import third-party components vue-table-with-tree-grid
import TreeTable from 'vue-table-with-tree-grid'
// Import progress bar plug-in 
import NProgress from 'nprogress'
// Import progress bar style 
// import 'nprogress/nprogress.css'
// // Import axios
import axios from 'axios'
// // Import vue-quill-editor( Rich text editor )
import VueQuillEditor from 'vue-quill-editor'
// // Import vue-quill-editor The style of 
// 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/'
// Before the request reaches the server , I'll call use This callback function in to add request header information 
axios.interceptors.request.use(config => {
  // When entering request Interceptor , Indicates that a request was sent , Let's start the progress bar 
  NProgress.start()
  // For the request header object , add to token Verified Authorization Field 
  config.headers.Authorization = window.sessionStorage.getItem("token")
  // Must return config
  return config
})
// stay response In the interceptor , Hide progress bar 
axios.interceptors.response.use(config =>{
  // When entering response Interceptor , Indicates that the request has ended , We'll end the progress bar 
  NProgress.done()
  return config
})
Vue.prototype.$http = axios

Vue.config.productionTip = false

// Global registration component 
Vue.component('tree-table', TreeTable)
// Register rich text components globally 
Vue.use(VueQuillEditor)

// Create a filter to filter the number of seconds to mm / DD / yy , Minutes and seconds 
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}-${d} ${hh}:${mm}:${ss}`
})

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

Then open the public/index.html Add external cdn Introduce code

<!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> E-commerce background management system </title>

    <!-- nprogress  Style sheet file  -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.css" />
    <!--  Rich text editor   Style sheet file  -->
    <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" />
    <!-- element-ui  Style sheet file  -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.8.2/theme-chalk/index.css" />

    <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>
    <!--  Rich text editor  js  file  -->
    <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>

    <!-- element-ui  Of  js  file  -->
    <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>

Customize the content of the home page

The form of content displayed on the home page of the development environment is different from that of the publishing environment
For example, in the development environment import Load third party package , The publishing environment uses CDN, Then the home page also needs to be implemented differently according to different environments
We can customize the content of the home page through plug-ins , open vue.config.js, Write the code as follows

module.exports = {
    chainWebpack:config=>{
        config.when(process.env.NODE_ENV === 'production',config=>{
            ......
            
            // The use of plug-in 
            config.plugin('html').tap(args=>{
                // Add parameter isProd
                args[0].isProd = true
                return args
            })
        })

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

            // The use of plug-in 
            config.plugin('html').tap(args=>{
                // Add parameter isProd
                args[0].isProd = false
                return args
            })
        })
    }
}

And then in public/index.html Use plug-ins to determine whether it is a publishing environment and customize the content of the home page

<!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 - ' %> E-commerce background management system </title>

    <% if(htmlWebpackPlugin.options.isProd){ %>
    <!-- nprogress  Style sheet file  -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.css" />
    ........
    <!-- element-ui  Of  js  file  -->
    <script src="https://cdn.staticfile.org/element-ui/2.8.2/index.js"></script>
    <% } %>
  </head>

Road load by lazy

1. install @babel/plugin-syntax-dynamic-import
open vue Console , Click dependency -> Installation dependency -> Development depends on -> Search for @babel/plugin-syntax-dynamic-import
Click on the install .

2. stay babel.config.js Declare the plug-in in , open babel.config.js

3. Use , If you don't install the plug-in, you will report an error

import(/* :"login_home_welcome" */ './components/Login.vue')

4.webpackChunkName Group name , Request to group one of the components , Other components under this group will be requested back

// Project release phase needs to use babel plug-in unit 
const productPlugins = []

// Determine whether it is the development or release stage 
if(process.env.NODE_ENV === 'production'){
  // Release stage 
  productPlugins.push("transform-remove-console")
}

module.exports = {
  "presets": [
    "@vue/app"
  ],
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ],
    ...productPlugins,
//---------------------------------------- Code start 
    // Configure the routing lazy load plug-in 
    "@babel/plugin-syntax-dynamic-import"
//-------------------------------------- Code end 
  ]
}

modify router.js file

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'

Project online

1. project npm run build pack

2. newly build express The server

npm i express

3. newly build vue_shop_server Folder

4. newly build app.js This file

const express = require('express')

const app = express()

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

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

5. newly build dist Folder

6. Copy the packaged files to this folder

7. Start the server   , Enter file directory , perform  node .\app.js

8. Browser input   http://127.0.0.1:8998

  Turn on gzip Compress

open vue_shop_server Folder terminal , Enter the command :npm i compression -D
open app.js, Write code :

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")
})

  To configure https service

To configure https Services are generally processed in the background , Front end developers can understand .
First , Application required SSL certificate , Get into https://freessl.cn Official website
Import the certificate in the background , Open today's information / material , Copy two files in the material to vue_shop_server in
open app.js file , Write code to import certificates , And open https service

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

const app = express()
// Create configuration objects and set public and private keys 
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")
// })

// start-up https service 
https.createServer(options,app).listen(443)

Use pm2 Management applications

open vue_shop_server Folder terminal , Enter the command :npm i pm2 -g
Use pm2 Start project , Enter command in terminal :pm2 start app.js --name Custom name
View item list command :pm2 ls
Restart project :pm2 restart Custom name or ID
Stop the project :pm2 stop Custom name or ID

Delete the project :pm2 delete Custom name or ID

// start-up 
pm2 start app.js --name shop

// see 
pm2 ls

// Restart 
pm2 restart  shop

// close 
pm2 stop shop

// Delete the project :
pm2 delete shop

copyright notice
author[Zhi jiangpeng],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290502035860.html

Random recommended