vue project optimization and steps

Posted by dgwade on Mon, 10 Jan 2022 17:46:11 +0100

Generate the packaging report, optimize the project according to the report, then add the progress bar and install the nprogress plug-in in main JS edit code

//Import progress bar plug-in
import NProgress from 'nprogress'
//Import progress bar styles
import 'nprogress/nprogress.css'

//Before the request reaches the server, the callback function in use will be called to add the request header information
axios.interceptors.request.use(config => {
  //When entering the request interceptor, it indicates that the request has been sent, and we open the progress bar
  NProgress.start()
  //For the request header object, add the Authorization field of token authentication
  config.headers.Authorization = window.sessionStorage.getItem("token")
  //config must be returned
  return config
})
//In the response interceptor, hide the progress bar
axios.interceptors.response.use(config =>{
  //When entering the response interceptor, it indicates that the request has ended, and we end the progress bar
  NProgress.done()
  return config
})

Yes In the pretierrc file, set "printWidth":200, and change the number of words per line of code to 200

Install a plug-in (Babel plugin transform remove console), remove all console information in the project build phase, open the project console, click dependency - > development dependency, enter Babel plugin transform remove console, and the installation opens

babel.config.js, the editing code is as follows:

/Required in the project release phase babel plug-in unit
const productPlugins = []

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

module.exports = {
  "presets": [
    "@vue/app"
  ],
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ],
    ...productPlugins
  ]
}

By default, the project generated by Vue cli 3.0 hides the webpack configuration item. If we need to configure the webpack, we need to go through Vue config. JS. Create Vue. Exe in the project root directory config. JS file,

module.exports = {
    chainWebpack:config=>{
        //Publishing mode
        config.when(process.env.NODE_ENV === 'production',config=>{
            //Entry finds the default packaging entry, and calling clear deletes the default packaging entry
            //add adds 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')
        })
    }
}

Supplement: chainWebpack can modify the webpack configuration in the form of chain programming. configureWebpack can modify the webpack configuration in the form of operation object

B. Enable CDN for third-party libraries

By default, all third-party packages of dependencies are packaged in js / chunk vendors. * * If the js file is too large, we can exclude these packages through externals so that they are not packaged into js / chunk vendors. * * js file

module.exports = {
    chainWebpack:config=>{
        //Publishing mode
        config.when(process.env.NODE_ENV === 'production',config=>{
            //Entry finds the default packaging entry, and calling clear deletes the default packaging entry
            //add adds a new packaging entry
            config.entry('app').clear().add('./src/main-prod.js')

            //Setting exclusions using externals
            config.set('externals',{
                vue:'Vue',
                'vue-router':'VueRouter',
                axios:'axios',
                lodash:'_',
                echarts:'echarts',
                nprogress:'NProgress',
                'vue-quill-editor':'VueQuillEditor'
            })
        })
        //Development mode
        config.when(process.env.NODE_ENV === 'development',config=>{
            config.entry('app').clear().add('./src/main-dev.js')
        })
    }
}

After the exclusion is set, in order to enable us to use vue, axios and other contents, we need to load the external CDN to solve the introduction of dependencies. Open the development entry file main-prod.js (the original file is main.js, copy one JS for development, one JS for release online, and the other is dev.js), and delete the default import code

Then open public / index HTML add external cdn introduction code (i.e. those links with http, such as < link href=“ https://unpkg.com/element-ui/lib/theme-chalk/index.css ">)


C. Element UI components are loaded on demand

According to custom, you can load as needed for daily use. Do not select import all

D. Route lazy loading

When the route is accessed, the corresponding route file is loaded, which is route lazy loading. Implementation steps of route lazy loading: 1 Install @ Babel / plugin syntax dynamic import, open the vue console, click dependency - > install dependency - > develop dependency - > Search @ Babel / plugin syntax dynamic import, and click Install.

2. In Babel config. JS, and open Babel config. js

//babel plug-ins required in the project release phase
const productPlugins = []

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

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

Change the route to load on demand and open the router JS, change the imported component code as follows,

The name is in the front, and then the generated file is placed under that file. Repeat the operation where the component is located

const Login = () => import(/* webpackChunkName:"login_home_welcome" */ './components/Login.vue')
// import Login from './components/Login.vue'

E. Homepage content customization

The home page of the development environment and the home page of the publishing environment show different forms of content. For example, the development environment uses import to load third-party packages, while the publishing environment uses CDN, so the home page also needs to be implemented differently according to different environments. We can customize the home page content through plug-ins and open Vue config. JS, the code is as follows:

module.exports = {
    chainWebpack:config=>{
        config.when(process.env.NODE_ENV === 'production',config=>{
            ......
            
            //Using plug-ins
            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')

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

Then in public / index Use plug-ins in HTML to determine whether it is a publishing environment and customize the content of the home page

<% output% >

  <title><%= htmlWebpackPlugin.options.isProd ? '' : 'dev - ' %>E-commerce background management system</title>

F project launch

Create a new folder and initialize the warehouse npm init -y

Install express npm i exoress -S locally

Copy the dist file generated by the completed project package to the new folder, and then create an app in the folder JS file and write code

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

Run node on the terminal \app. JS (enter app and press tab to complete the code)

Turn on gzip compression

Enter the command: npm i compression -D to 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")
})

Configure https service (if some passwords and bank cards are not secure, https will be used)

Configuring https services is generally handled in the background, which can be understood by front-end developers. First, you need to apply for an SSL certificate to enter FreeSSL home page - FreeSSL Cn is a website that provides free HTTPS certificate application Import the certificate in the background on the official website, open today's materials / materials, and copy two files in the materials to Vue_ shop_ Open app. In server JS file, write code, import the certificate, and start the 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 https service
https.createServer(options,app).listen(443)

Use pm2 to manage applications (in addition to managing items with user-defined names, you can also manage items with IDS)

Install pm2 # npm i pm2 -g

Start project:: PM2 start app JS -- name custom name

View item list command: pm2 ls

Restart project: pm2 restart custom name

Stop item: pm2 stop custom name

Delete item: pm2 delete user defined name

Topics: Front-end Vue.js elementUI