This article is based on the results of the report. The original address: www.smashingmagazine.com/2017/02/a-d…
JavaSript modular packaging has been around for a long time. In 2009, RequireJS submitted its first version, Browserify followed, and other packaging tools began to take off. In the end, Webpack came out on top. If you don’t know much about it, HOPEFULLY my article will give you a taste of this powerful packing tool.
What is a modular packaging tool?
In most languages (the latest version of JS, ECMAScript 2015+, is also supported, but not in all browsers), you can split your code into multiple files and use the methods they contain by referencing these files in your business code. Unfortunately, browsers don’t have this capability. Hence the modular packaging tool, which provides this capability to browsers in two forms: 1. Load modules asynchronously and run them after loading. 2. Assemble the required files into a single JS file, and finally load the JS file in HTML with
Without modular loading and packaging tools, you would have to manually piece together files or load countless
- You need to care about the order in which files are loaded, including which files depend on other files; You also need to verify that unnecessary files have been imported.
- multiple
<script>
Tagging means loading code with multiple network requests, and it also means worse performance. - Obviously, there is a lot of manual work that could have been left to a computer.
Most modular packaging tools integrate directly with NPM or Bower, which makes it easier to add dependencies to your business code. All you have to do is install it, write a line of code to introduce it, then run the modular packaging tool, and you’ve integrated third-party code into your business code. Or, if configured correctly, you can consolidate all the three-party code to be used into a separate file so that when you update the business code and users need to update the cache, they don’t have to re-download the vendor code.
Why Webpack?
Now that you have a basic understanding of Webpack’s vision, why choose Webpack over all the other heroes? In my opinion, there are several reasons:
- It has been helped by the fact that it can bypass or avoid the problems of its predecessors.
- Easy to get started. You don’t even need a configuration file if you just want to package some JS files and have no other requirements.
- Its plug-in architecture makes it powerful enough to do so much more, so it may be the only build tool you need.
I know of few other module packaging and building tools that do the same. But Webpack still has a leg up: there’s a huge community of support when you step on a pit. Browserify’s community may just be large, but if it isn’t, it will lack some of the potentially essential features of Webpack. With all the benefits of Webpack, you’re probably just waiting for the code? So let’s start.
Install Webpack
Before we can use Webpack, we need to install it first. To do this, we need Node.js and NPM, and I’m going to assume that you have them installed, but if you don’t, start on the Node.js website.
There are two ways to install WebPack (or other CLI packages) : globally or locally. For global installations, you can use it in any directory, but it is not included in the dependencies list of your project. Also, you can’t switch between two different versions of Webpack (some projects may require more work to update to the latest version, so they need to maintain the old version). So I prefer to install the CLI package locally and run it using a relative path or NPM script. If you’re not used to installing CLI packages locally, check out my previous post on getting rid of the global installation of NPM packages.
However, in our sample project, we will use the NPM script. Next, install the sample project locally. First: Create a directory to experiment with and learn about Webpack. I have a repository on GitHub that you can clone locally and switch between branches to learn below, or create a new project from scratch that can then be compared with my repository code.
After command line selection, once in the project directory, you will initialize the project with the NPM init command. The information you fill in next doesn’t matter at all, unless you want to post your project to NPM.
The package.json file is now ready (it was created using the NPM init command), where you can save dependency package information. NPM install webpack -d (-d is short for the –save-dev command, which installs the NPM package as a dependency on the development environment. Json file) installs Webpack as a dependency package.
We need a simple application to start the journey of using Webpack. NPM install Lodash -s (-s == –save) to install LoDash, so that our simple application has a dependency package to load. Next we create a SRC directory and create a file named main.js in that directory with the following contents:
var map = require('lodash/map');
function square(n) {
return n*n;
}
console.log(map([1.2.3.4.5.6], square));Copy the code
Easy, right? We simply create a small array of integers 1 through 6, and then use the map function in the Loadash library to create a new array where the numbers in the new array are the squares of the numbers in the original array. Finally, we print the new array in the console. Run the node SRC /main.js command to see the result: [1, 4, 9, 16, 25, 36]. You see, even Node.js can run this file.
But if we want to package this little script that also includes Lodash code that we can run in the browser, where do we start with Webpack? How?
Webpack command line
If you don’t want to waste time on configuration files, using the Webpack command line is the easiest way to get started. If configuration files are not enabled, the simplest command contains the input file path and the output file path. Webpack reads the input file, tracks its dependency tree, packs all the dependency files into a single file, and finally prints the file in the output path you specify. In this case, the input path is SRC /main.js, and we’ll export the packaged file to dist/bundle.js. To do this, let’s add the NPM script (we don’t have Webpack installed globally, so we can’t run it directly from the command line). Edit the “scripts” part of the package.json file as follows:
"scripts": {
"build": "webpack src/main.js dist/bundle.js",
}Copy the code
Now, run the NPM run build command and the Webpack will run. Soon, the dist/bundle.js file will be generated upon completion. You can then run the file with Node.js (via the Node dist/bundle.js command). You can also run it in a browser with simple HTML and see the same results later in the console.
Before continuing to explore the Webpack, let’s tweak the build scripts a bit more professionally: remove the DIST directory and its contents before rebuilding, and add some scripts for directly executing the bundle files. First, install the del-CLI tool so that you don’t have to worry about operating system differences when deleting directories (sorry, I use Windows). Run NPM install del-cli -d. Then update the NPM script as follows:
"scripts": {
"prebuild": "del-cli dist -f",
"build": "webpack src/main.js dist/bundle.js",
"execute": "node dist/bundle.js",
"start": "npm run build -s && npm run execute -s"
}Copy the code
We kept the “build” configuration as before, but added the “prebuild” configuration to clear the directory, which will run before each “build” command. Also added is the “execute” configuration: use Node.js to execute a packed script. In addition, with the “start” configuration, you can execute all of the above commands with a single command (-s simply keeps the NPM script from printing something useless on the console). By executing the NPM start command, you can see the Webpack output in the console, followed by printing the array squared.
A: congratulations! You just did everything in the example1 branch. This branch is in the warehouse I mentioned earlier.
Webpack configuration file
As interesting as it is to get started with the Webpack command line, once you start using more of Webpack’s features, you’ll want to abandon passing Webpack configuration parameters through the command line in favor of configuration files. Using a configuration file takes up more space, but at the same time increases readability because it is written in JS.
Let’s create a configuration file. Create a new file, webpack.config.js, in the root directory. Webpack looks for this file by default, but if you want to give the configuration file a different name or put it in a different directory, you can do so by passing the –config [filename] parameter.
In this tutorial, we use the default file name. Now let’s try to make the configuration file work to achieve the same effect as using the command line alone. To do this, we need to add the following code to the configuration file:
module.exports = {
entry: './src/main.js'.output: {
path: './dist'.filename: 'bundle.js'}};Copy the code
As before, we specify the input and output files. This is not a JSON file but a JS file, so we need to export the configuration object, so we use module.exports. It’s hard to see how writing these configurations is any better than using commands, but you’ll love it by the end of this article.
Next, remove the configuration passed to Webpack from the package.json file like this:
"scripts": {
"prebuild": "del-cli dist -f",
"build": "webpack",
"execute": "node dist/bundle.js",
"start": "npm run build -s && npm run execute -s"
}Copy the code
Run the NPM start command as before. Does the result look familiar? That’s what you need to do in branch Example2.
Webpack loader (Loaders)
We enhance Webpack in two main ways: loaders and plugins. We’ll talk about loaders first, and plugins later. Loaders are used to convert or manipulate specific types of files. You can string multiple loaders together to process one type of file. For example, files with the.js suffix should be checked by ESLint before Babel converts ES2015 syntax to ES5 syntax. Alerts from ESLint will be printed on the console, and syntactic errors will prevent Webpack from continuing to pack.
We won’t set syntax checking here, but we’ll set Babel to convert the code to ES5. Of course we need some ES2015 code first, right? Change the code for the main.js file to look like this:
import { map } from 'lodash';
console.log(map([1.2.3.4.5.6], n => n*n));Copy the code
In fact, this code does the same thing as before, except for two things: first, it uses the arrow function instead of the square function defined earlier. Second, we used the IMPORT syntax in ES2015 to load the map function in the LoDash library, but this would pack the entire Lodash library code into our output file, instead of introducing the ‘Lodash /map’ library that only contains the map function code. You can also change the first line to import map from ‘lodash/map’ if you like; But I have my reasons for writing it this way:
- In larger applications, you may need to use many parts of the Lodash library, so you’d better load it all in.
- If you’re using backbone. js, you’ll find it difficult to package only the functions you need because there’s no documentation that tells you what functions functions depend on.
- In the next big version of Webpack, developers are going to add something called tree-shaking, which will rule out parts of the import module that are not used. So that’s one way to do it.
- I’m writing this to give you an example so you can understand the point I made earlier.
(Note: Lodash works with both loading methods, because its developers specify that it does, and not all libraries work this way.)
Anyway, with the ES2015 code now in hand, we’re going to convert it to ES5 code so that it runs in older browsers (in fact, ES2015 is fairly well supported in newer browsers). Therefore, we need Babel and the infrastructure to run Babel in Webpack. At least babel-core (Babel-core), babel-Loader (Babel-core Webpack loader interface), babel-PRESET – ES2015 (preset rules for ES2015 to ES5), That’s what Babel needs to know). We also introduced babel-plugin-Transform-Runtime and babel-Polyfill, although they are implemented in slightly different ways. Both are used to change the way Babel adds polyfills and helper functions. As a result, they are adapted to different kinds of projects. You probably don’t want to introduce both of them, you can choose one of them, but I’m going to introduce both of them here, so that whichever you choose, you know how to introduce them. To learn more, visit the official documentation for Polyfill and Runtime Transform.
Anyway, install them first: NPM I -d babel-core babel-loader babel-preset- ES2015 babel-plugin-transform-Runtime babel-polyfill. Then configure Webpack for them. First, add a section to add the loader. Update webpack.config.js as follows:
module.exports = {
entry: './src/main.js'.output: {
path: './dist'.filename: 'bundle.js'
},
module: {
rules: [
…
]
}
};Copy the code
We added a Module property that contains the rules property. Rules is an array that contains the configuration of each loader. We will add the babel-loader configuration here. For each loader, we need to configure at least two parameters: test and loader. Test is usually a regular expression that verifies the absolute path of each file. We generally only validate file suffixes, e.g. /\.js$/ validates all files ending in.js. In this case, we set this parameter to /\.jsx? $/ This matches.js and.jsx files for use with React. Next configure the loader parameter, which describes which loader should be used to process the file under the corresponding test parameter.
It works by passing a string of the loader’s name, separated by an exclamation point, such as ‘babel-loader! Eslint – loader ‘. Eslint-loader will run before babel-loader because Webpack reads from right to left. If a loader has a special parameter configuration, you can use the Query String syntax. For example, to configure a fakeoption to true for Babel, we would have to change the previous example to ‘babel-loader? fakeoption=true! Eslint – loader ‘. If you find it easier to read and maintain, you can also use use instead of the Loader configuration, passing in an array instead of the previous string. Change the previous example to: use: [‘babel-loader? Fakeoption =true’, ‘eslint-loader’], or even more, you can write them in multiple lines to improve readability.
Currently we are only using the Babel Loader, so our configuration file looks like this:
... rules: [ {test: /\.jsx? $/.loader: 'babel-loader'}]...Copy the code
If we use only one loader, we can also configure the object as a key-value map instead of a Query String. So, for the fakeOption example, our configuration file could be written like this:
... rules: [ {test: /\.jsx? $/.loader: 'babel-loader'.options: {
fakeoption: true}}]...Copy the code
Configure our Babel loader as follows:
... rules: [ {test: /\.jsx? $/, loader:'babel-loader',
options: {
plugins: ['transform-runtime'],
presets: ['es2015'}}]...Copy the code
Presets are used to convert ES2015 features to ES5. We also set Babel with the transform-Runtime plug-in that is already installed. As mentioned above, the plug-in is not necessary; it is here for demonstration purposes. We could also create a separate.babelrc file to configure these parameters independently, but that wouldn’t be good for demonstrating Webpack. In general I recommend using the.babelrc file, but we’ll leave it that way.
Everything is ready except the east wind. We need to tell Babel to skip processing files in node_modules to speed up our build. Exclude tells the loader to ignore files in the target directory. Its value is a regular expression, so we write it like this: /node_modules/.
... rules: [ {test: /\.jsx? $/, loader:'babel-loader',
exclude: /node_modules/,
options: {
plugins: ['transform-runtime'],
presets: ['es2015'}}]...Copy the code
Also, we should have used the include attribute to say that we only read the SRC directory, but I think we should leave it as it is. You should then be able to execute the NPM start command again and get the ES5 code for the browser. If you want to use Polyfill instead of the Transform-Runtime plug-in, you need to make one or two changes. First remove plugins: [‘ transform-Runtime], this line (if you don’t want to use it anymore, you can uninstall it directly using NPM). Next, edit the entry section of the Webpack configuration file as follows:
entry: [
'babel-polyfill'.'./src/main.js'].Copy the code
We have replaced a string describing a single entry with an array describing multiple entries. The new entry is polyfill. We put them in the first place so that the syntactic fillers will appear first in the packaged file because we need to make sure they already exist before we use them in our code.
Instead of using the Webpack configuration file, we could have done this by adding import ‘babel-polyfill; To achieve the same goal. We used the configuration file, not only for the service example, but also as an example of how to package multiple entries into a single file. Well, that’s the example3 branch in the repository. Once again, you can run the NPM start command to confirm that the project is running properly.
Another example: the Handlebars loader
Let’s add another loader for the project: Handlebars. The Handlebars loader is used to compile Handlebars templates into functions. When you import a Handlebars file in JS, the compiled functions are imported into the JS file. This is what I like about Webpack loaders: even if a non-JS file is introduced, it will be converted to something available in JS at packaging time. The following example will use another loader that allows you to import image files and convert them into base64 encoded URL strings that can be used to add inline images to pages in JS. This also means that if you have multiple loaders in series, one of them can even optimize the file size of the image.
Again, we install the loader first by executing the NPM install -d handlebars-loader command. Handlebars itself is indispensable when you use them: run NPM install -d Handlebars. This way you can control Handlebars versions without updating the loader version, and they can be iterated separately.
Now that both are installed, let’s get a Handlebars template to use. Create a numberList. HBS file in the SRC directory with the following contents:
<ul>
{{#each numbers as |number i|}}
<li>{{number}}</li>
{{/each}}
</ul>Copy the code
This template represents an array (the variable name is numbers, or any other variable name) and creates an unordered list.
Next, we adjust the previous JS file to print a list using the template, rather than just printing the array itself. Main.js will look like this:
import { map } from 'lodash';
import template from './numberlist.hbs';
let numbers = map([1.2.3.4.5.6], n => n*n);
console.log(template({numbers}));Copy the code
Unfortunately, Webpack doesn’t know how to introduce NumberList. HBS so far, because it’s not a JS file. We can add something to the import path to tell Webpack to use the Handlebars loader:
import { map } from 'lodash';
import template from 'handlebars-loader! ./numberlist.hbs';
let numbers = map([1.2.3.4.5.6], n => n*n);
console.log(template({numbers}));Copy the code
We tell Webpack that the file should use that loader by adding the loader name to the path and prefixing it with an exclamation point separating the name and path. This way, we don’t have to add anything to the configuration file. However, on a fairly large project, you will most likely be loading more than one template, so it makes more sense to tell Webpack in the configuration file that we are using Handlebars to avoid prefixes to paths when importing templates. Let’s update the configuration file:
... rules: [ {/ * Babel loader config... * /},
{ test: /\.hbs$/.loader: 'handlebars-loader'}]...Copy the code
This part is pretty easy. All we need to do is specify handlebars-loader to handle.hbs ending files, and that’s it. We handled Handlebars and the example4 branch. Now, once you run NPM start, you should see the Webpack output as follows:
<ul>
<li>1</li>
<li>4</li>
<li>9</li>
<li>16</li>
<li>25</li>
<li>36</li>
</ul>Copy the code
Webpack plug-in
Plug-ins are another way to customize Webpack functionality. You can add them to Webpack workflows more freely, because there are few restrictions on them other than loading special file types. They can be implanted anywhere, which makes them more powerful. It’s hard for me to define how much the Webpack plug-in can do, so I’ll just give you a list of search results from NPM Packages that have “webpack-plugin” that should be a good answer.
We’ll only touch on two plug-ins in this tutorial (one of which will be revealed soon). This is where I am and you know my style, so we don’t need any more examples. Let’s start with the HTML Webpack Plugin, which does just that: generate HTML files – finally ready for the browser!
Before using the plug-in, let’s first update the NPM script to run a simple server that can test the sample application. Install a server: Run the NPM I -d http-server command. Next, change the previous execute script to the server script as follows.
..."scripts": {
"prebuild": "del-cli dist -f"."build": "webpack"."server": "http-server ./dist"."start": "npm run build -s && npm run server -s"},...Copy the code
Once the Webpack is built, NPM start will also start a Web server and redirect the browser to localhost:8080 to get to your page. Naturally, we still need the plugin to create the page, so next, we need to install the plugin: NPM i-d html-webpack-plugin.
Once installed, we go to webpack.config.js and make the following changes:
var HtmlwebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: [
'babel-polyfill'.'./src/main.js'].output: {
path: './dist'.filename: 'bundle.js'
},
module: {
rules: [{test: /\.jsx? $/.loader: 'babel-loader'.exclude: /node_modules/.options: { plugins: ['transform-runtime'].presets: ['es2015']}}, {test: /\.hbs$/.loader: 'handlebars-loader'}},plugins: [
new HtmlwebpackPlugin()
]
};Copy the code
We made two changes: we introduced the newly installed plug-in at the top of the file, and we added a plugins section to the end of the configuration object where we passed in the instance object of the plug-in.
Currently we don’t pass in a configuration object for the plug-in instance and default to its base template, which doesn’t contain much beyond our packaged script files. When you visit the URL in your browser after running NPM start, you will see a blank page, but if you open the console in developer tools, you should see HTML printed out inside.
We might need to get the template and spit out the HTML on the page instead of the console so that a “normal person” can actually get information from the page. We’ll start by creating an index.html file in the SRC directory so we can define our own template. By default, the plug-in uses EJS template syntax, but you can also configure the plug-in to use other supported template languages. Here we’ll use EJS because there’s no real difference in the syntax. Index. HTML will look like this:
<! DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<title><% = htmlWebpackPlugin.options.title% ></title>
</head>
<body>
<h2>This is my Index.html Template</h2>
<div id="app-container"></div>
</body>
</html>Copy the code
Please note a few points:
- We’ll pass in a configuration object for the plug-in to define the title (just because we can).
- We didn’t specify where to insert our script file, because the plug-in defaults to
body
Add the script before the end of the element. - The DIV id here is not specific, we just picked one up here.
Now that we have the template we want, we won’t end up with a blank page. Next update main.js to add the HTML structure to that div instead of printing it in the console. To do this, we simply update the last line of main.js: document.getelementById (“app-container”).innerhtml = template({numbers});
Also, we need to update the Webpack configuration file to pass in two parameters for the plug-in. The configuration file should now look like this:
var HtmlwebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: [
'babel-polyfill'.'./src/main.js'].output: {
path: './dist'.filename: 'bundle.js'
},
module: {
rules: [{test: /\.jsx? $/.loader: 'babel-loader'.exclude: /node_modules/.options: { plugins: ['transform-runtime'].presets: ['es2015']}}, {test: /\.hbs$/.loader: 'handlebars-loader'}},plugins: [
new HtmlwebpackPlugin({
title: 'Intro to webpack'.template: 'src/index.html'}})];Copy the code
The template configuration specifies the location of the template file, and the title configuration is passed into the template. Now, run NPM start and you should see the following in your browser:
If you keep doing this, the example5 branch ends here. The parameters or configuration items passed in by different plug-ins vary greatly because of the wide variety and scope of plug-ins, but they all end up being added to the plugins array in webpack.config.js. Also, there are other ways to handle HTML page generation and filename padding, and once you start adding cache-busting hashes suffixes to packaged files, these things become very simple.
Looking at the sample repository, you’ll see that there is an example6 branch where I implemented JS code compression by adding plug-ins, but this is not required unless you want to change the UglifyJS configuration. If you don’t like the default configuration of UglifyJS, check out the repository in this branch (just look at webpack.config.js) to find out how to use the plugin and configure it. But if the default configuration works for you, all you need to do is pass in the -p argument when you run Webpack from the command line. This parameter is short for production and has the same effect as using –optimize-minimize to compress JS code and –optimize-occurence-order to optimize the order of modules that have been introduced, Look at slightly smaller file sizes and slightly faster execution times. I didn’t know about the -p parameter until some time after the sample repository was complete, so I decided to save the sample plug-in as a reminder that there is an easier way (besides adding plug-ins). Another shortcut command argument you can use is -d, which displays more Webpack print and generates a source map without any other arguments. There are many other command-line shortcuts available.
Lazy loading of data blocks
Lazy-loading modules are modules that I’m comfortable with in RequireJS but have trouble working in Browserify. A sizeable JS file will benefit from reducing network requests, but it will almost certainly download code that the user doesn’t need during a session.
Webpack can break a package into chunks that can be lazily loaded without any configuration. You just write the code in one of two ways, and Webpack does the rest. One is based on CommonJS and the other is based on AMD. To use lazy loading with the former, write:
require.ensure(["module-a"."module-b"].function(require) {
var a = require("module-a");
var b = require("module-b");
/ /...
});Copy the code
Require. Ensure needs to ensure that the module is available (but not running), and then pass in an array of module names, followed by a callback. To really use modules in callback functions, you need to explicitly require the corresponding modules passed in the array.
Private think this way phase trouble, so, we see AMD writing.
require(["module-a"."module-b"].function(a, b) {
/ /...
});Copy the code
In AMD mode, the require function is passed in an array of dependent module names, followed by a callback function. The arguments to this callback function are references to dependent modules, arranged in the same order as the dependent modules are arranged in the array.
Webpack 2 also supports system.import, which relies on promises rather than callback functions. While it wasn’t difficult to wrap the callback content under a promise, I still found the promotion very useful. Note, however, that system.import is now obsolete, and newer specifications recommend using import(). A word of caution, however, is that Babel (and TypeScript) throws syntax exceptions when you use System.import. You can use the babel-plugin-dynamic import-webpack plugin, but that plugin will convert it to require.ensure, rather than allowing Babel to legally process the new import or let Webpack handle it. I don’t think AMD or Require. ensure will be obsolete for a long time, and Webpack won’t support System.import until the third release, which is a long way off, so just use the one you like.
Expand our code, let it stall for two seconds, then lazily load the Handlebars template in and print it to the screen. To do this, we remove the top import template statement, and then wrap the last line around setTimeout and amD-mode require to introduce the template.
Run NPM start and you will see that another asset file named 1.bundle.js is generated. Open the page in your browser, then listen for network traffic in developer tools, and after 2 seconds you’ll see that the new resource file is finally loaded and running. All of this is easy to do, but there is more to the user experience.
Note that these sub-bundles, or chunks, contain all of their dependencies internally, but not the dependencies already introduced by their parent chunks. (You can have multiple entry files, each loading a block lazily, so that the block loads different dependency modules in its master block.)
Create Vendor Chunks
One more optimization point: common library data blocks. You can define a separate bundle for packaging that houses the “common” library or third-party code that doesn’t change often. This strategy allows users to cache your public library files separately from business code so that users don’t have to re-download the library files as you iterate through your application.
To do this, we use the official Webpack plugin: CommonsChunkPlugin. It comes with Webpack, so we don’t need to install it. Just make a few changes to webpack.config.js:
var HtmlwebpackPlugin = require('html-webpack-plugin');
var UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
var CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
module.exports = {
entry: {
vendor: ['babel-polyfill'.'lodash'].main: './src/main.js'
},
output: {
path: './dist'.filename: 'bundle.js'
},
module: {
rules: [{test: /\.jsx? $/.loader: 'babel-loader'.exclude: /node_modules/.options: { plugins: ['transform-runtime'].presets: ['es2015']}}, {test: /\.hbs$/.loader: 'handlebars-loader'}},plugins: [
new HtmlwebpackPlugin({
title: 'Intro to webpack'.template: 'src/index.html'
}),
new UglifyJsPlugin({
beautify: false.mangle: { screw_ie8 : true },
compress: { screw_ie8: true.warnings: false },
comments: false
}),
new CommonsChunkPlugin({
name: "vendor".filename: "vendor.bundle.js"}})];Copy the code
We introduce the plug-in in line 3. Later, you modify the configuration in the Entry section to replace it with an object literal to specify multiple entries. The Vendor entry records the libraries that will be introduced in the common library data block, which contains Polyfill and Lodash, and places our main entry in the main entry. Next, we simply add the CommonsChunkPlugin to the plugins section, specify the “Vendor” data block as the index for the plugin-generated data block, and specify the vendor.bundle.js file to hold the common library code. Here, name in the plug-in configuration: “vendor” corresponds to the vendor entry in the entry array, and the dependency module specified in the entry array is the dependency module finally stored in vendor.bundle.js file).
By specifying a “Vendor” block, the plug-in pulls all of the block’s dependencies and stores them in the common library block, which are specified in a separate entry file. If the block name is not specified in the entry object literal, the plug-in will generate separate files based on common dependency modules between multiple entry files.
Run Webpack and you will see three JS files: bundle. JS, 1.bundle. JS and vendor.bundle. JS. You can also run the NPM start command to view the results in a browser if you wish. It seems that Webpack even puts its main code that loads different modules into a common library data block, which is extremely useful.
Now that we’re done with the Example8 branch tour, we’re nearing the end of the tutorial. I’ve talked a lot, but I’ve only scratched the surface of what Webpack can do. Webpack makes CSS modules easier, caching easier, image optimization easier, and more – so much so that even if I wrote a book, I wouldn’t be able to tell you all about it, and most of what I’ve written will be updated and replaced by the time I’ve written it. So, try Webpack and tell me if it improves workflow. Wish my Lord bless, happy programming!
IKcamp’s original new book “Mobile Web Front-end Efficient Development Combat” has been sold on Amazon, JD.com and Dangdang.