Vue project packaging and optimization implementation steps

Vue project packaging and optimization implementation steps

Packaging, launching and optimizing the Vue project

After the project is completed, we will launch the project online. In order to improve performance, we often perform some optimization processing

Packaging of Vue project

There is a default packaging command in the scaffolding project. We can enter npm run bulid to package the project.

Open the terminal and switch to the project root directory

Enter the command: npm run build

A dist folder will be generated in the root directory of the current project, which contains the packaged files

insert image description here

Project hosting

We can create a simple node server to host the packaged project, so that we can simulate accessing the server project

1. Create a new directory as the server root directory, execute node init -y in the small black window to perform initialization, then execute npm i express to download the express package, and then create the app.js file and copy the following code into it (use the express package to open a server)

2. Copy the dist directory just packaged to the node server directory

3. The resources are in the dist directory, so you can use static resource hosting to provide resources and use the dist directory as the resource hosting directory

express create server

var express = require('express')
const path = require('path')

// 2. Create the server var app = express();

// Hosting static resources // You can also place all static resources in a specified directory, such as public, and then add the following configuration app.use(express.static('dist'))
app.use('/', express.static(path.join(__dirname, 'dist')))

// 3. Start the server and listen to the port app.listen(3001, () => {
  console.log('http://127.0.0.1:3001')
})

Start the server

Open the terminal in the server directory and enter node app.js

Enter the server address in your browser

[External link image transfer failed. The source site may have an anti-hotlink mechanism. It is recommended to save the image and upload it directly (img-woOTHmF2-1627475455630) (img\02-access server resources.jpg)]

Common optimization of projects

After the project is packaged, the previously used deployment dependency packages and external resources used in the project will be packaged

If many packages are introduced before, or unnecessary packages are introduced, the size of the project will increase, causing users to request more data to access normally, which is not conducive to user experience, so the packaging process needs to be optimized.

Generally speaking, we can optimize the project from the aspect of optimizing the code, or we can use a CDN-like method to optimize the project.

The scaffolding provides a command that allows us to see the distribution (occupancy) of project resources: npm run build – --report

Generate project report files

npm run build – --report 

insert image description here

Open the report page

insert image description here

1. In the report page, the larger the block, the larger the volume occupied by the template.
2. If the module occupies a larger volume, we should consider not packaging it into the product

CDN acceleration optimization

cdn: The essence of CDN is to cache media resources, dynamic and static images (Flash), HTML, CSS, JS and other content to an IDC closer to you, so that users can share resources and achieve the needs of reducing the response time between sites, etc. The essence of the online game accelerator is to accelerate for users by establishing a high-bandwidth computer room and setting up multi-node servers.

We can use some large-volume modules and let CDN help us provide the corresponding resources, which can relieve the pressure on our own servers and provide faster and better resource response.

vue.config.js

In the scaffolding project, if you want to add your own project configuration, you can add a vue.config.js file in the root directory and implement custom configuration in this file

When packaging, this configuration will be combined with the scaffolding configuration

Add package exclusions

module.exports = {
    configureWebpack: {
        externals:{
            'vue': 'Vue',
            'element-ui': 'ELEMENT',
            'quill': 'Quill'
        }
    },
}

insert image description here

As you can see, the size of the packaged project is significantly reduced, but the problem is not solved. Without these packages, the packaged project cannot be run.

insert image description here

This is because there is no Vue package in the packaged project, so an error occurs. We now need to use CDN to provide these resources.

Add user customization of CDN

Add the following code to vue.config.js

let cdn = {
  css: [
    //element-ui css
    'https://unpkg.com/element-ui/lib/theme-chalk/index.css', // Style sheet // Rich text box plug-in style 'https://cdn.bootcdn.net/ajax/libs/quill/2.0.0-dev.4/quill.bubble.css'
  ],
  js: [
    // vue must be at first!
    'https://unpkg.com/vue/dist/vue.js', // vuejs
    // element-ui js
    'https://unpkg.com/element-ui/lib/index.js', // elementUI
    // Rich text box plug-in 'https://cdn.bootcdn.net/ajax/libs/quill/2.0.0-dev.4/quill.js'
  ]
}

Automatically add resources to the page through plugins

Mount resources to plugins

module.exports = {
  // Add packaging exclusions to indicate that the packages in the following configuration will not be packaged into the project in the future configureWebpack: {
    externals:{
            'vue': 'Vue',
            'element-ui': 'ELEMENT',
            'quill': 'Quill'
        }
  },
  //Mount the CDN resources to the plugin chainWebpack (config) {
    config.plugin('html').tap(args => {
      args[0].cdn = cdn
      return args
    })
  }
}

Use the plug-in to add the specified CDN resource in the page, and add the following code to the public index in the project (the index file before the project is packaged)

Add css import (in head structure)

<% for(var css of htmlWebpackPlugin.options.cdn.css) { %>
  <link rel="stylesheet" href="<%=css%>" />
<% } %>

Add js import (in body structure)

<% for(var js of htmlWebpackPlugin.options.cdn.js) { %>
  <script src="<%=js%>"></script>
<% } %>

Repack, OK

Set to use CDN only in production stage

When developing a project, there is actually no need to use CDN, which will reduce the efficiency of our page loading and is not suitable for local development (network connection is required)

We can perform corresponding processing according to the environment variables, and only when the product is in use, let the plug-in automatically inject the corresponding resource files into the HTML page.

const isProd = process.env.NODE_ENV === 'production' // Is it a production environment? let externals = {
  'vue': 'Vue',
  'element-ui': 'ELEMENT',
  'quill': 'Quill'
}


let cdn = {
  css: [
    //element-ui css
    'https://unpkg.com/element-ui/lib/theme-chalk/index.css', // Style sheet // Rich text box plug-in style 'https://cdn.bootcdn.net/ajax/libs/quill/2.0.0-dev.4/quill.bubble.css'
  ],
  js: [
    // vue must be at first!
    'https://unpkg.com/vue/dist/vue.js', // vuejs
    // element-ui js
    'https://unpkg.com/element-ui/lib/index.js', // elementUI
    // Rich text box plug-in 'https://cdn.bootcdn.net/ajax/libs/quill/2.0.0-dev.4/quill.js'
  ]
}

cdn = isProd ? cdn : { css: [], js: [] }
externals = isProd ? externals : {}


module.exports = {
  // Add packaging exclusions to indicate that the packages in the following configuration will not be packaged into the project in the future configureWebpack: {
    externals
  },
  // 
  chainWebpack (config) {
    config.plugin('html').tap(args => {
      args[0].cdn = cdn
      return args
    })
  }
}

This concludes this article on the implementation steps of vue project packaging and optimization. For more relevant vue project packaging and optimization content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Essential bonus items for optimizing and packaging the front end of Vue projects
  • Vue project packaging, merging and compression to optimize web page response speed
  • Vue project packaging and compilation optimization solution
  • Detailed explanation of how to optimize the packaging of multi-page projects implemented by Vue
  • Vue project summary of webpack conventional packaging optimization solution
  • Detailed explanation of Vue project optimization and packaging

<<:  Tutorial on installing and using virtualenv in Deepin

>>:  Solving problems encountered when importing and exporting Mysql

Recommend

How to use Vue to develop public account web pages

Table of contents Project Background start Create...

In-depth understanding of Vue's method of generating QR codes using vue-qr

Table of contents npm download step (1) Import (2...

HTML hyperlink style (four different states) setting example

Copy code The code is as follows: <style type=...

Layim in javascript to find friends and groups

Currently, layui officials have not provided the ...

Example of configuring multiple SSL certificates for a single Nginx IP address

By default, Nginx supports only one SSL certifica...

Mysql transaction isolation level principle example analysis

introduction You must have encountered this in an...

How to use .htaccess to prohibit a certain IP from accessing the website

Preface For cost considerations, most webmasters ...

How to implement variable expression selector in Vue

Table of contents Defining the HTML structure Inp...

MySQL conditional query and or usage and priority example analysis

This article uses examples to illustrate the usag...

Summary of coalesce() usage tips in MySQL

Preface Recently, I accidentally discovered MySQL...

Solutions to VMware workstation virtual machine compatibility issues

How to solve VMware workstation virtual machine c...

How to install Oracle_11g using Docker

Install Oracle_11g with Docker 1. Pull the oracle...

Design Theory: Hierarchy in Design

<br />Original text: http://andymao.com/andy...

MySql 8.0.16-win64 Installation Tutorial

1. Unzip the downloaded file as shown below . 2. ...