Implementation steps: A. Generate A packaged report and optimize the project based on the report b. Enable the CDN for the third-party library c. load the lement-UI component on demand D. Lazy route loading E. Customize the content on the home page

Clear the console.log information during the release phase

Online products should not have console.log print on the console

Install a plugin (Babel-plugin-transform-remove-console) to remove all console.log information from the build phase of the project

  • Open babel.config.js in the project and edit the code as follows:

  • Process.env.node_env can get the corresponding mode

    • Production release phase

    • Development is the development stage

Declare the plug-in in babel.config.js.

// The Babel plugin is required for the project release phase
const productPlugins = []
​
// Determine whether production is the 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"}].// Extend the plugins in the array. productPlugins ] }Copy the code

Generate a packaged report

When packaging, reports can be generated at packaging time to visually detect problems in your project. There are two ways to generate a report:

  1. Reports are generated as command-line arguments

    // The vue-cli command option generates a package report // the --report option generates report. HTML to help analyze the package contentsCopy the code
  2. View reports directly through a visual UI panel

    In the visual UI panel, you can easily see the problems existing in the project through the console and analysis panel. Click "Task" => "build" => "Run". After running, click "Analysis" on the right and view the report in the "Console" panelCopy the code

Modify webPack configuration

Create the vue.config.js file in the project root directory

By default, vue-CLI 3.0 generates a project that hides the WebPack configuration items. If we need to configure WebPack, we need to configure it through vue.config.js. (For details, see cli.vuejs.org/zh/config/#…)

// vue.config.js
 // From this file, you should export an object containing custom configuration options
 module.exports = {
 / / options...
 }
Copy the code

Configure a different package entry for development mode and release mode

Why do you need to configure two packing entries? == in order to separate the development process from the release process of the project

By default, the Vue project’s development mode and distribution mode share the same packaged entry file (i.e. SRC /main.js). To separate the development process from the release process of a project, we can specify an entry file for each of the two modes, namely:

(1) The entry file for development mode is SRC /main-dev.js

② The entry file of the publishing mode is SRC /main-prod.js

Difference between configureWebpack and chainWebpack

The configureWebpack and chainWebpack functions the same in the vue.config.js configuration objects. The only difference is that they modify the WebPack configuration differently:

① chainWebpack changes the default WebPack configuration by chaining

② configureWebpack Changes the default WebPack configuration by manipulating objects

The use of two specific differences, may refer to the following url: cli.vuejs.org/zh/guide/we…

Customize the packaging entry via chainWebpack

module.exports = {
    chainWebpack:config= >{
        // Publish mode
        config.when(process.env.NODE_ENV === 'production'.config= >{
            //entry Find the default package entry, call clear to remove the default package entry
            //add adds a new package 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')}}}Copy the code

Use externals to load external CDN resources

By default, third-party dependency packages imported through the import syntax are eventually packaged into the same file. As a result, the size of a single file becomes too large after the package is completed. To solve these problems,

  • External CDN resources can be configured and loaded using the Externals node of WebPack. Any third-party dependencies declared in externals are not packaged. The configuration code is as follows

    config.set('externals', {
             vue: 'Vue'.'vue-router': 'VueRouter'.axios: 'axios'.lodash: '_'.echarts: 'echarts'.nprogress: 'NProgress'.'vue-quill-editor': 'VueQuillEditor'
    })
    Copy the code
  1. Add the above code to vue.config.js

    module.exports = {
        chainWebpack:config= >{
            // Publish mode
            config.when(process.env.NODE_ENV === 'production'.config= >{
                //entry Find the default package entry, call clear to remove the default package entry
                //add adds a new package entry
                config.entry('app').clear().add('./src/main-prod.js')
    ​
                // Use externals to set exclusions
                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')}}}Copy the code
  2. In the entry file main-prod.js, remove the default import code (before making two copies of the main.js entry file, main-prod.js belongs to the release phase and main-dev.js belongs to the development phase)

    For example, delete imported JS and CSS

    // import './plugins/element.js'
    // Import the font icon
    import './assets/fonts/iconfont.css'
    // Import global styles
    import './assets/css/global.css'
    // Import the third-party component vue-table-with-tree-grid
    import TreeTable from 'vue-table-with-tree-grid'
    // Import the progress bar plug-in
    import NProgress from 'nprogress'
    // Import the 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 the vue-Quill-editor style
    // import 'quill/dist/quill.core.css'
    // import 'quill/dist/quill.snow.css'
    // import 'quill/dist/quill.bubble.css'
    Copy the code
  3. Then open public/index.html to add the corresponding CDN import code

      <! -- 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 js file -->
        <script src="https://cdn.staticfile.org/element-ui/2.8.2/index.js"></script>Copy the code

    Show different content depending on the development and release environment

If import is used to load third-party packages in the development environment, and CDN is used in the publishing environment, then the home page also needs to be implemented differently according to different environments

  1. We can customize the homepage content by means of plug-in, open vue.config.js, and write the code as follows:

    module.exports = {
        chainWebpack:config= >{
            // Publish mode
            config.when(process.env.NODE_ENV === 'production'.config= >{...// Use a plug-in
                config.plugin('html').tap(args= >{
                    // Add parameter isProd
                    args[0].isProd = true
                    return args
                })
            })
           // Development mode
            config.when(process.env.NODE_ENV === 'development'.config= >{
                config.entry('app').clear().add('./src/main-dev.js')
    ​
                // Use a plug-in
                config.plugin('html').tap(args= >{
                    // Add parameter isProd
                    args[0].isProd = false
                    return args
                })
            })
        }
    }
    Copy the code
  2. With the < % {= htmlWebpackPlugin. Options. IsProd} % > can get isProd parameters in cooperating with three expression is false or true

  3. The CDN mode or import mode can be determined by the if judgment

    If judging grammar < % if (htmlWebpackPlugin. Options. IsProd) {% > here put the introduction of CDN way} < % % >

    ​
    <% 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 js file -->
        <script src="https://cdn.staticfile.org/element-ui/2.8.2/index.js"></script>The < %} % >Copy the code

The route was loaded lazily. Procedure

When you package a build project, the JavaScript package can become so large that it affects page loading. It would be more efficient if we could split the components of each route into separate code blocks and then load the components when the route is accessed

It takes three steps:

① Install the @babel/ plugin-syntactic -dynamic-import package.

Declare the plug-in in the babel.config.js configuration file.

Change route to load on demand form, the example code is as follows:

Const routing the corresponding component () = = > import (/ * routing group: "name" * / ' ' 'routing path)

The route of the same group will package the corresponding components into the same JS file. When requesting the component Foo, it will also request the component Bar. Similarly, when requesting the component Bar, it will also request the component Foo

const Foo = () = > import(/* webpackChunkName: "group-foo" */ './Foo.vue')
const Bar = () = > import(/* webpackChunkName: "group-foo" */ './Bar.vue')
const Baz = () = > import(/* webpackChunkName: "group-boo" */ './Baz.vue')
​
Copy the code

Detailed documentation about routing lazy loading, may refer to the following links: router.vuejs.org/zh/guide/ad…

  1. Declare the plug-in in babel.config.js and open babel.config.js

    // The Babel plugin is required for the project release phase
    const productPlugins = []
    ​
    // Decide whether it is development or release
    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"}].// Extend the plugins in the array. productPlugins,// Configure the route to load the plug-in lazily
        "@babel/plugin-syntax-dynamic-import"]}Copy the code
  2. Change the route to load on demand, open router.js, and change the imported component code as follows:

    The component group name is Login_Home_Welcome

import Vue from 'vue'
import Router from 'vue-router'// import Login from './components/Login.vue'
const Login = () = > import(/* webpackChunkName:"login_home_welcome" */ './components/Login.vue')
​
// import Home from './components/Home.vue'
const Home = () = > import(/* webpackChunkName:"login_home_welcome" */ './components/Home.vue')
​
// import Welcome from './components/Welcome.vue'
const Welcome = () = > import(/* webpackChunkName:"login_home_welcome" */ './components/Welcome.vue')
Copy the code

The gZIP compression function is enabled

Open gZIP compression === “dump the pot to the back end… Ha ha

Using Gzip can reduce the file size and make the transfer faster.

  1. Enter the command NPM I compression -d to install the corresponding package

  2. Gzip compression can be done on the server side using Express. The configuration is as follows:

    • NPM install compression -s
    • // import package const compression = require(‘compression’)
    • // Enable middleware app.use(compression())
const express = require('express')
//1. Import the GZIP plug-in
const compression = require('compression')
​
// Create the Web server
const app = express()
// 2. Enable the middleware
app.use(compression())
​
// Hosting static resources
app.use(express.static('./dist'))
​
// Start the Web service
app.listen(8998.() = >{
    console.log("server running at http://127.0.0.1:8998")})Copy the code


\