Home > Web Front-end > JS Tutorial > Detailed example of vue-cli optimized webpack configuration

Detailed example of vue-cli optimized webpack configuration

小云云
Release: 2017-12-28 09:04:31
Original
1857 people have browsed it

The recent project has passed the busy infrastructure construction period, and it has gradually relaxed. I am going to record my recent webpack optimization measures, hoping to have the effect of reviewing the past and learning the new. This article mainly introduces the detailed explanation of webpack configuration based on vue-cli optimization. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

The project uses vue family bucket, and the build configuration is improved based on vue-cli. Regarding the original webpack configuration, you can read this article vue-cli#2.0 webpack configuration analysis. The article basically explains each line of code in the file in detail, which will help you better understand webpack.

After carefully summarizing, my optimization is basically based on the points circulated on the Internet

  1. Extract common libraries through externals configuration and quote cdn

  2. Configure CommonsChunkPlugin properly

  3. Make good use of alias

  4. dllplugin enables pre-compilation

  5. happypack multi-core build project

externals

Document address https://doc.webpack-china.org /configuration/externals/

Prevent certain imported packages from being packaged into bundles, and instead obtain these external dependencies from the outside during runtime.

CommonsChunkPlugin

Document address https://doc.webpack-china.org/plugins/commons-chunk-plugin/

The CommonsChunkPlugin plug-in is an optional function for creating an independent file (also called a chunk). This file includes common modules of multiple entry chunks. By separating the common modules, the final synthesized file can be loaded once at the beginning and then stored in the cache for subsequent use. This brings speed improvements because the browser will quickly pull the common code out of the cache instead of loading a larger file every time a new page is accessed.

resolve.alias

Document address https://doc.webpack-china.org/configuration/resolve/#resolve-alias

Create import or require aliases to ensure that module introduction becomes easier. For example, some common modules located in the src/ folder:

However, through my own practice, the last three points are the most optimized for my own project. The article also mainly explains the following points in detail

The original time required to package a project is basically about 40 seconds, then how long will it take to go through the next three steps of optimization

1. Use dllplugin to precompile and reference

Why should we reference Dll in the first place? After browsing some articles on the Internet, I found that in addition to speeding up the build, using webpack's dll has another benefit.

Dll exists independently after being packaged. As long as the libraries it contains are not increased, decreased, or upgraded, the hash will not change, so the online dll code does not need to be updated frequently with version releases. Because Dll packages are basically independent library files, one characteristic of such files is that they do not change much. When we normally package these library files into an app.js, changes in other business files affect the cache's optimization of the build, resulting in the need to search for relevant files in the npm package again every time. After using DLL, as long as the included libraries are not upgraded, added or deleted, there is no need to repackage. This also improves build speed.

So how to use Dll to optimize the project?

First, you must create a dll configuration file and introduce the third-party libraries required by the project. The characteristic of this type of library is that it does not need to be updated frequently with version releases and is stable in the long term.


const webpack = require('webpack');
const path = require('path');

module.exports = {
 entry: {
  //你需要引入的第三方库文件
  vendor: ['vue','vuex','vue-router','element-ui','axios','echarts/lib/echarts','echarts/lib/chart/bar','echarts/lib/chart/line','echarts/lib/chart/pie',
   'echarts/lib/component/tooltip','echarts/lib/component/title','echarts/lib/component/legend','echarts/lib/component/dataZoom','echarts/lib/component/toolbox'],
 },

 output: {
  path: path.join(__dirname, 'dist-[hash]'),
  filename: '[name].js',
  library: '[name]',
 },

 plugins: [
  new webpack.DllPlugin({
   path: path.join(__dirname, 'dll', '[name]-manifest.json'),
   filename: '[name].js',
   name: '[name]',
  }),
 ]
};
Copy after login

The basic configuration parameters are basically the same as webpack. I believe everyone who has seen optimization will understand what it means, so I won’t explain it. Then execute the code to compile the file. (My configuration file is placed in the build, and the path below needs to be changed according to the project path)


webpack -p --progress --config build/webpack.dll.config.js
Copy after login

When the execution is completed, two new files will be generated in the same directory. level, one is verdor.js generated in the dist folder, which contains the compressed code of the entry dependencies; the other is verdor-manifest.json in the dll folder, which indexes each library by number and uses It's id instead of name.

Next, you just need to add a line of code to the plugin in your webpack configuration file and it will be ok.


const manifest = require('./dll/vendor-manifest.json');
...
...,
plugin:[
  new webpack.DllReferencePlugin({
    context: __dirname,
    manifest,
  }),
]
Copy after login

At this time, if you execute the webpack command again, you can find that the time has dropped sharply from 40 seconds to about 20s. Is it twice as fast? (I don’t know if it’s because This happens because I have too many dependent libraries, so I cover my face manually).

2.happypack multi-threaded compilation

Generally node.js performs compilation in a single thread, while happypack starts multi-threading of node for construction, which greatly improves the construction speed. speed. The method of use is also relatively simple. Taking my project as an example, create a new happypack process in the plug-in, and then replace the place where the loader is used with the corresponding id


var HappyPack = require('happypack');
...
...
modules:{
  rules : [
    ...
    {
      test: /\.js$/,
      loader:[ 'happypack/loader?id=happybabel'],
      include: [resolve('src')]
    },
    ...
  ]
},
...
...
plugin:[
  //happypack对对 url-loader,vue-loader 和 file-loader 支持度有限,会有报错,有坑。。。
  new HappyPack({
     id: 'happybabel',
     loaders: ['babel-loader'],
     threads: 4,//HappyPack 使用多少子进程来进行编译
  }),
  new HappyPack({
     id: 'scss',
     threads: 4,
     loaders: [
        'style-loader',
        'css-loader',
        'sass-loader',
     ],
  })
]
Copy after login

这时候再去执行编译webpack的代码,打印出来的console则变成了另外一种提示。而编译时间大概从20s优化到了15s左右(感觉好像没有网上说的那么大,不知道是不是因为本身js比重占据太大的缘故)。

3.善用alias

3.配合resolve,善用alias

本来是没有第三点的,只不过在搜索网上webpack优化相关文章的时候,看到用人提到把引入文件改成库提供的文件(原理我理解其实就是1.先通过resolve指定文件寻找位置,减小搜索范围;2.直接根据alias找到库提供的文件位置)。

vue-cli配置文件中提示也有提到这一点,就是下面这段代码


resolve: {
  //自动扩展文件后缀名,意味着我们require模块可以省略不写后缀名
  extensions: ['.js', '.vue', '.json'],
  //模块别名定义,方便后续直接引用别名,无须多写长长的地址
  alias: {
   'vue$': 'vue/dist/vue.esm.js',//就是这行代码,提供你直接引用文件
   '@': resolve('src'),
  }
 },
Copy after login

然后我将其他所有地方关于vue的引用都替换成了vue$之后,比如


// import 'vue';
import 'vue/dist/vue.esm.js';
Copy after login

时间竟然到了12s,也是把我吓了一跳。。。

然后我就把jquery,axios,vuex等等全部给替换掉了。。。大概优化到了9s左右,美滋滋,O(∩_∩)O~~

4.webpack3升级

本来是没第四点,刚刚看到公众号推出来一篇文章讲到升级到webpack3的一些新优点,比如Scope Hoisting(webpack2升级到webpack3基本上没有太大问题)。通过添加一个新的插件


// 2017-08-13配合最新升级的webpack3提供的新功能,可以使压缩的代码更小,运行更快
...
plugin : [
  new webpack.optimize.ModuleConcatenationPlugin(),
]
Copy after login

不过在添加这行代码之后,构建时间并没有太大变化,不过运行效率没试过,不知道新的效果怎么样

好了基本上感觉就是以上这些效果对项目的优化最大,虽然没有到网上说的那种只要3~4秒时间那么变态,不过感觉基本8,9秒的时间也可以了。

相关推荐:

图文解析如何使用vue-cli脚手架

实例详解vue-cli vscode 配置 eslint

如何使用 vue-cli 开发多页应用方法

The above is the detailed content of Detailed example of vue-cli optimized webpack configuration. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template