Packaging optimization

Project development completed

Packaging:

  • Do with webpack packaging (the vue, js,. Less — — — — — – >. Js, the CSS, the HTML)
  • Commands are provided in the project:npm run build

Package optimization:

  • Keep our files as small as possible while maintaining functionality
  • Let’s make our page display faster while keeping the functionality available

After packaging, you get dist directory. If you want to double-click to open index.html, you need to configure it in vue.config.js in advance: vue.config.js

{
  	publicPath: '/'
}
Copy the code

Package optimization – Route lazy loading

The problem

{
    path: '/login'.component: () = > import('@/views/login/index'),
    hidden: true
  },
Copy the code

Component: () => import(‘@/views/login/index’)

How does it differ from the following?

const Login = import('@/views/login/index')
{
    path: '/login'.component: Login,
    hidden: true
  },
Copy the code

What is lazy routing

A route to a component represents a page. Lazy loading means that the component’s resources are loaded only when the route enters the page.

Route lazy load magic comment

You can name this file manually by specifying webpackChunkName in the comment. Here is an example.

components = () = > import(/* webpackChunkName:"login"*/ ".. /component/Login.vue");
Copy the code

Package optimization – Package size analysis

The target

Perform package size analysis on developed applications

Packet size analysis

We integrate functionality, write a lot of components, and end up packing them into a bunch of files (there will be a lot of.js files in the js directory). How big is each package?

We can use vue-CLI’s own performance analysis tool to package and analyze all the features we developed, which is very simple to use

npm run preview -- --report
Copy the code

This command will do dependency analysis from our entry **main.js** to figure out the size of each package for easy observation and optimization

After executing this command, we should see output from the console similar to the following

Access:http://localhost:9526/report.html

As shown in the figure, the larger the square is, the larger the file occupies, and the larger the file, the higher the requirement for network bandwidth and access speed, which is the direction of our optimization.

Webpack configuration excludes packaging – holistic analysis

review

The packaging process: Starts from main.js and is packaged by WebPack

Analysis of the

Do we need to package all third party libraries into our own projects? Don’t need

The XLSX package is quite large (715K) and this type of plugin doesn’t need to be updated for a long time, so there’s no need to pack it!

Train of thought

When you pack, don’t punch these bags in,

Webpack configuration excludes packing – packing thin

The target

You can configure vue-CLI to exclude some packages that are not normally needed from the package file.

For example: Let WebPack not pack vue XLSX and Element

use

Find vue.config.js and add externals as follows:

configureWebpack: {
  // Set the page title of the single-page application
  name: name,
  externals: {
     /** * externals object attribute parsing. * Basic format: * 'package name' : 'name introduced in the project' * */
    'vue': 'Vue'.'element-ui': 'ElementUI'.'xlsx': 'XLSX'
  },
  resolve: {
    alias: {
      The '@': resolve('src')}}}Copy the code

Running the package again, we see that the package size has been significantly reduced: the three packages are no longer in the target file for the package.

Package to remove console.log

In vue.config.js, configure:

chainWebpack(config) {
    config.optimization.minimizer('terser').tap((args) = > {
      args[0].terserOptions.compress.drop_console = true
      return args
    })
}
Copy the code

The Webpack configuration excludes packaging – referencing network resources

The target

Perform related configurations: Import excluded packets through public network resources

Configuration – Takes effect in the production environment

Note that file resources can still be pulled from the local node_modules at development time, and external resources need to be used only when the project is online. At this point we can use environment variables to differentiate. Details are as follows:

In the **vue.config.js** file:

let externals = {}
let cdn = { css: [].js: []}const isProduction = process.env.NODE_ENV === 'production' // Check whether it is a production environment
if (isProduction) {
  externals = {
      /** * externals object attribute parsing: * 'package name' : 'name introduced in the project' */
      'vue': 'Vue'.'element-ui': 'ELEMENT'.'xlsx': 'XLSX'
  }
  cdn = {
    css: [
      'https://unpkg.com/element-ui/lib/theme-chalk/index.css' // Element-ui CSS style sheet].js: [
      // vue must at first!
      'https://unpkg.com/[email protected]/dist/vue.js'.// vuejs
      'https://unpkg.com/element-ui/lib/index.js'.// element-ui js
      'https://cdn.jsdelivr.net/npm/[email protected]/dist/xlsx.full.min.js'.// xlsx]}}Copy the code

Webpack Configure the externals configuration item

configureWebpack: {
  // Set the page title of the single-page application
  name: name,
+ externals: externals,
  resolve: {
    alias: {
      The '@': resolve('src')}}}Copy the code

Inject the CDN configuration into the HTML template

This is then injected into index.html via the html-webpack-plugin:

In vue.config.js, set

chainWebpack(config) {
  config.plugin('preload').tap(() = >[{rel: 'preload'.fileBlacklist: [/\.map$/./hot-update\.js$/./runtime\.. *\.js$/].include: 'initial'}])// Inject CDN variables (done when packaged)
  config.plugin('html').tap(args= > {
    args[0].cdn = cdn // Configure the CDN for the plug-in
    return args
  })
  // omit other...
}
Copy the code

Go to public/index.html and configure CDN Config to inject CSS and JS in sequence.

Modify head as follows:

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= webpackConfig.name %></title>

      <! -- Introducing styles -->
      <% for(var css of htmlWebpackPlugin.options.cdn.css) { %>
        <link rel="stylesheet" href="<%=css%>">The < %} % ><! JS -->
    <% for(var js of htmlWebpackPlugin.options.cdn.js) { %>
      <script src="<%=js%>"></script>The < %} % ></head>
Copy the code

Pack and check

npm run build:prod
Copy the code

Check for CSS and JS imports in the generated index.html

Change the publicPath

publicPath: './',
Copy the code
<! - the introduction of JS - > < % for (var JS of htmlWebpackPlugin. Options. The CDN. JS) {% > < script SRC = "< % = JS % >" > < / script > < %} % >Copy the code

Pack and check

npm run build:prod
Copy the code

Check for CSS and JS imports in the generated index.html

Change the publicPath

publicPath: './',
Copy the code

Open it again and double-click dist/index.html to see the effect