I believe that every front-end student must have used Webpack, as an epoch-making construction tool, but many students’ understanding of it is still stuck in the cognition of how to change the host. Modern scaffolding greatly improves the efficiency of project construction, but the convenience of tools, automation and perfect configuration also make many students have no deep understanding of Wepback. Here I have compiled a few classic scenarios of webpack application, hope to help you

Several core parameters of Webpack

As a warm-up, let’s first introduce the following core basic configuration parameters of WebPack

1 entry

Accepts an object or array. With this configuration, we can set one or more entries

2 output

Accepts an object that sets the output path and file name of the packaged output file. In the case of multiple entries, you can use [name] and [hash] as dynamic parameters to set naming rules for multiple output files

3 plugins

An array that can load multiple plug-ins as files for processing. Common plug-ins are:

Uglify webpack – plugin: compressed javascript

Clean-webpack-plugin: Delete the files in the dist directory

Copy-webpack-plugin copies files

ExtractTextPlugin: Separate the CSS from the package

HtmlWebpackPlugin: Webpack automatically generates HTML pages

HappyPack: Multi-core packaging speeds up packaging

CommonsChunkPlugin/SplitChunksPlugin: extracting utility module

Webpack. DllPlugin + webpack. DllReferencePlugin with multiple entry Can mutual dependence of entrance separately packaged

4.module

Loader is configured by setting the module.rule array. Loaders generally use regular expressions to process specified file types

Babel-loader @babel/ core@babel /preset-env: JS turns into ES5 family barrel, needs to be used

Css-loader: parses imported. CSS files

Style-loader: Inserts processed CSS as tags into HTML

Html-loader: parses. HTML files and analyzes imported JS, CSS, images and other data

5.resolve

This parameter sets the configuration of path resolution. Common attributes are

Extensions :[‘.js’, ‘.vue’, ‘.json’], meaning that the import path can be found without the suffix and will automatically search for the default suffix in the extensions group

Alias: {‘@’: resolve(‘ SRC ‘)} : path alias, using this setting to indicate the SRC directory in the code

6.devtool

This parameter has 10+ enumerated values and sets how the sourcesouMap of the code is packaged. Some package sourcesoumaps into code, some save them as a separate. Map file, and sourcesoumaps vary in detail

The above are the core parameters that I think are more important. I can probably understand the use of them. In the actual use process, you can refer to the document for more detailed understanding of their configuration

Second, webpack scenario application

Ok, I believe that most of the above introductory configuration items are understood by most students, but in the practical application process, because the scaffolding has helped us to complete the configuration in most cases, there is basically no need to make any changes. However, in some projects where scaffolding is not possible, we have to write the configuration ourselves. Here are a few classic scenarios to see how Webpack works

Scenario 1: Package common code into a third-party library

There are currently two entry JS, a.js and B.js, both of which are very simple and require the introduction of a third-party library, such as Jquery. So the code for A and B files is very simple:

import $ from jquery

console.log($)

Copy the code

If we don’t do anything special, we set the entry A and B in the entry entry, and then set the name and path of the output file in the output, then we have two output files, and both files are inserted into the HTML and work correctlyThat’s it. So let’s use Webpack to help us implement this function. In this case, the version of WebPack is 4.3, and webPack4 already integrates this feature for the extraction of the third library, so we only need to use the optimization.splitchunks attribute, without the need to install additional plug-ins.

Optimization: {splitChunks: {// cacheGroups: {// cache group cache common code Commons: {// common module name: "Commons ", chunks: "Initial ", // start extracting code minSize: 0, // start extracting code minChunks: 2, // repeat code twice or more}}}}Copy the code

With this setup, the final output file will be removed from the common library as commons.js we set up

Scenario 2: Specify unpackaged libraries

Now I have written a good picture playback plug-in, the specific implementation of you can imagine, but I also use jquery code, code in a large number of places to use $() DOM operations. This plugin will eventually be uploaded to the NPM community as an NPM package for everyone to use. Also, without any optimization, the JS that I eventually package for everyone to use will contain jquery code, so each code that uses my plug-in will have hundreds of extra K of volume, which is not what I want.

In this case, I can make a disclaima in the instructions that the plugin will be based on jquery, so I need to make sure that jquery is available in my environment when referencing the plugin, so I don’t need to pack jquery into my files, my plugin package will probably only need a few kilobytes. At the core of this requirement is the use of the externals configuration, which can declare that the specified library will not be packaged into the code, leaving only a reference where it is used, so that as long as the library is present in the plug-in environment, it will work, and the plug-in itself will not package the library code

externals:{
  jquery:'commonjs2 jquery'
}

Copy the code

As an extra note, this setup has a commonjs2 string configuration. This is where we declare which specification the library is loaded into our code. A specification is just a native JS form or a specification from AMD, CMD or commonJS referenced in it. I don’t want to expand too much here, but the most commonly used ones are actually two: native and commonJS. Native is what we’ve introduced in HTML via CDN to run directly on the page. The commonJS specification is what we use for Node, and we almost always import third-party packages using the import or require syntax. If you set externals to ‘commonjs2 jquery’, you need to specify ‘commonjs2 jquery’.

3. Advanced cases of Webpack applications

This time we are going to do a more complete NPM package. To help you understand, now we need to make a simplified version of the Element component library. Speaking of this UI library, I believe that everyone has used it. There are dozens of components in Element that we can use. We can introduce it with the following global code:

Import ElementUI form 'Element' vue.use (ElementUI)Copy the code

This allows you to insert component tags directly into the template where needed throughout the project. But if we only need one or more of these components, we can use only a few of them by introducing them locally:

Import {button,select}form 'Element'Copy the code

In this way, our own code will only contain the above 2 introduced component code, and the other dozens of components will not be packaged into our code. Let’s implement such a requirement:

  1. The project structure

First, it is a library of VUE components that we can create through vuecil scaffolding and build the following directory

dist  ... 
src  index.js
packages
    button / button.vue
    select / select.vue
    checkbox /checkbox.vue

Copy the code

This is a project structure that you have an intuitive sense of

2. Code references

The entry for this project is SRC /index.js, and the file needs to implement the install method, because the install method is called when global is imported via vue. use(our component library), and we need to implement it here. The functionality implemented is to register the three VUE components in Packages into the VUE by iterating through objects or arrays

Import button from 'packages/button' Import select from 'packages/select' Import checkbox from 'packages/ checkbox' Const components = [button ,select,checkbox] const install = function(Vue, opts = {}) { components.forEach(component => { Vue.component(component.name, component); })}; export default { button , select, checkbox, install }Copy the code

While our three components are a normal VUE component, there should be no need to write pseudo-code for you.

3. The webpack configuration

Now that the basic structure is complete, the WebPack configuration is ready. The first entry must be our SRC /index.js and I’m sure there will be no objection here. Then the emphasis is on configuring output:

Output: {path: path.resolve(process.cwd(), './lib'), // Package output: {path: path.resolve(process.cwd(), './lib'), 'COMP', // this item needs to be used with libraryTarget, 'commonjs2' does not take effect libraryTarget: 'commonjs2' // declare output file supported specification},Copy the code

Since the use of our component library is introduced through the import statement, the libraryTarget needs to be set to ‘commonJs2’, as in case 2. LibraryTarget has multiple values. Only with some options does library need to be set. Otherwise, library does not need to be written and does not take effect. If it were printed now, the code for all three components would be packaged into comp.common.js, and there would be no local import. So again, the externals external extension configuration is needed.

Externals{'./packages/button.vue ':' commonjs2 button ', './packages/select.vue ':' commonjs2 select ', '. / packages/checkbox. Vue ':' commonjs2 checkbox} 'Copy the code

The resulting comp.common.js will only leave references, and the code for the three components themselves will not be packaged. But is that it? No, because these three external extension libraries are not public CDN libraries, but exist in our local project, so we need to package the three components separately to create an available component. Js, so that it can be used normally. This configuration entry should be three, corresponding to three components, and the output specification should also be CommonJs2, since our SRC /index.js imports three components using import

Package a single component.js

entry:{ "button": "./packages/button.vue", "select": "./packages/select.vue", "checkbox": "./packages/checkbox.vue" }, output: { path: path.resolve(process.cwd(), './lib'), filename: '[name].js', // button.js select.js libraryTarget: 'commonjs2'}Copy the code

Finally, our package command actually requires running two Webpack configurations, resulting in four files: comp.common.js and three component names.js. So with webpack’s tree shaking ability, when we use the locally introduced writing, the resulting package file will only package the locally used component code.

To the end of this text, I hope to bring you practical experience to help. Next time we will talk about the operation principle of Webpack, together with a simple manual manual Webpack!

This article uses the article synchronization assistant to synchronize