The following package optimization schemes are all very practical in actual projects. Optimization using the following schemes can usually reduce the project volume by about 30%.

The basic idea of optimization: the file as small as possible; Multiple small files instead of one large file.

Source Map

The Source Map was created to address the fact that production code is often compressed and obfuscated, making it difficult to locate exceptions thrown at runtime.

The Source Map is essentially an information file that stores information about the location of the code before and after the conversion, so that exceptions can be accurately located.

Generating the Source Map can greatly reduce the packaging speed.

Production environments can consider canceling Source Map generation. If you do, configure the server to not allow ordinary users to access the Source Map file!

// vue.config.js
module.exports = {
   productionSourceMap: false // Disable source map generation in production environment
}
Copy the code

Component lazy loading

By default, component code is packaged into app.js and app.css files, respectively. The more components, the larger the file.

App. js and app. CSS files are loaded on the first screen. Large files slow down the loading speed, resulting in a long blank screen. Lazy loading allows the component’s code to be pulled away, generating separate files that are loaded only when the component is used.

The most used route in actual projects is lazy loading.

Lazy loading requires extracting code and generating files, thus reducing packaging speed.

WebpackChunkName Specifies the name of the generated file.

const routes = [
    / /... route
    {
        path: '/about'.name: 'About'.component: () = > import(/* webpackChunkName: 'about' */'./views/about.vue'); }];Copy the code

According to the need to load

Real projects often rely on many third-party packages, and the global import approach packages all of the package’s code into the project. In fact, most of the code is not needed, and loading on demand removes unwanted code during the build process.

Loading on demand can greatly reduce file size and can be used as a major optimization tool.

Load ElementUI on demand

First, install the babel-plugin-Component:

npm install babel-plugin-component -D
Copy the code

Then, change babel.config.js to:

module.exports = {
  presets: ["@vue/cli-plugin-babel/preset"].plugins: [
     / /... plugins
    [
      "component",
      {
        libraryName: "element-ui".styleLibraryName: "theme-chalk",},],],};Copy the code

Next, create an element-ui-plugin.js file and register the components you need to use:

import { Button, Message } from 'element-ui';

export default {
    install: (Vue) = >{ Vue.use(Button); Vue.prototype.$message = Message; }}Copy the code

Finally, introduce element-ui-plugin.js in main.js:

import Vue from 'vue';
import ElementUiPlugin from './element-ui-plugin';

Vue.use(ElementUiPlugin);
Copy the code

The CDN to accelerate

Third-party packages in a project are packaged into chunk-vendors. Js by default, so the file size tends to be quite large.

Chunk-vendors. Js loads on the first screen, and oversized files slow down the loading speed, resulting in a long white screen. By configuring externals (external extensions), the third package of code can be removed from chunk-vendor.js, and these extension dependencies can then be picked up by the runtime from the user environment.

An external extension is usually specified as a CDN link, and the HTML-webpack-plugin can easily inject A CDN link into an HTML file.

When using CDN, a stable and reliable CDN service is very, very important.

// vue.config.js

// Define external extensions
const externals = {
    vue: "Vue"};// Define the CDN address
const cdn = {
    css: [
        'https://unpkg.com/element-ui/lib/theme-chalk/index.css'].js: [
        'https://unpkg.com/[email protected]/dist/vue.runtime.min.js']}module.exports = {
    chainWebpack: (config) = > {
        if (process.env.NODE_ENV === 'production') {
            config.externals(externals);
            // Use html-webpack-plugin to enter the CDN connection
            config
                .plugin('html').tap((args) = > {
                    args[0].cdn = cdn;
                    returnargs; }}}};Copy the code

To configure the index.html file:

<! DOCTYPEhtml>
<html>
  <head>
    <meta charset="utf-8">
    <! -- Add CSS -->
    <% for(let css of htmlWebpackPlugin.options.cdn.css) { %>
      <link rel="stylesheet" href="<%=css%>">The < %} % ><! Insert JS -->
    <% for(let js of htmlWebpackPlugin.options.cdn.js) { %>
      <script src="<%=js%>"></script>The < %} % ><title><%= htmlWebpackPlugin.options.title %></title>
  </head>

  <body>
    <div id="app"></div>
  </body>
</html>

Copy the code

Split third-party modules

If you cannot find a stable and reliable CDN service, or if you do not want to use a CDN and want to separate third-party packages from chunk-vendor.js, you can split them using splitChunks and rely on generating separate files.

Note: Consider splitting only when the file size is too large, and actual optimization requires a trade-off between the size and number of requests.

// vue.config.js
module.exports = {
    / /... options

    chainWebpack: (config) = > {
        // Production environment configuration
        if (process.env.NODE_ENV === 'production') {
            config.optimization
                .runtimeChunk("single")
                .splitChunks({
                    chunks: "all".// Analyze both synchronous and asynchronous modules
                    maxInitialRequests: Infinity.// Specify the maximum number of parallel requests for the entry, as many generated files as possible
                    minSize: 20000.// Specify the minimum size of the generated file
                    cacheGroups: {
                        vendor: {
                            test: /[\\/]node_modules[\\/]/,
                            name: (module) = > {
                                const packageName = module.context.match(
                                    /[\\/]node_modules[\\/](.*?) (/ / \ \ | $) /) [1];
                                // Specify the third-party package output file name
                                return `${packageName.replace("@"."")}`; }}}}); }}};Copy the code

Gzip compression

Gzip compression, which can greatly reduce the size of files and speed up the transmission efficiency, can be used as the main optimization means. To use Gzip compression, the server must be configured. If Gzip is not supported, ordinary files must be transferred to the client.

Package production Gzip files

First, install the compression-webpack-plugin:

Note: If using the latest version of VUE-CLI, it is recommended to install compression- webpack-Plugin 5.0.0, otherwise there will be an exception during the packaging process.

npm install compression-webpack-plugin@5.0. 0 --save-dev
Copy the code

Next, modify vue.config.js:

// vue.config.js
const CompressionWebpackPlugin = require("compression-webpack-plugin");

module.exports = {
    / /... options
    chainWebpack: (config) = > {
        if (process.env.NODE_ENV === 'production') {
            / / register the Plugin
            config
                .plugin('Compression')
                .use(CompressionWebpackPlugin, [
                  {
                    include: 'src'.// Specify the SRC directory
                    test: /\.js$|\.html$|\.css$/.// Matches all js, HTML, and CSS files in the SRC directory
                    minRatio: 1.// Only files whose compression ratio is greater than 1 are compressed. Compression ratio = compressed size/original size
                    threshold: 10240.// Compress files larger than 1KB},])}}};Copy the code