Previous words
Prior to the advent of Webpack, the existing module management and packaging Tools on the market were not suitable for large projects, especially single-page Web applications. The most urgent reason is how to maintain the separation and storage of various module resources in a large-scale code base, maintain their dependencies, and seamlessly integrate them together to generate static resources suitable for browser-side request loading. Webpack is now the most popular modular management and packaging tool for front-end resources. It can package many loose modules according to dependencies and rules into front-end resources that meet the deployment of the production environment. You can also code-separate modules that load on demand, and then load them asynchronously when you actually need them.
Webpack's content is rich and messy, and is not friendly to novices. This paper introduces the important concepts of webpack in the form of an example, and emphatically explains how to use Webpack
Overview
Webpack is a module wrapper.
Characteristics
Webpack has the following characteristics
Code splitting
Webpack has two types of organizational modules that are dependent on the way, synchronous and asynchronous. Asynchronously relies as a split point to form a new block. After the dependency tree has been optimized, each asynchronous chunk is packaged as a file.
Loader
The Webpack itself can only handle native JavaScript modules, but the loader converter can convert various types of resources into JavaScript modules. In this way, any resource can be a module that Webpack can handle.
Intelligent parsing
Webpack has an intelligent parser that can handle almost any third-party library, regardless of whether they are in the form of CommonJS, AMD or ordinary JS files. Even when loading dependencies, the dynamic expression require ("./templates/" + name + ". Jade") is allowed.
Plug-in System
Webpack also has a feature-rich plug-in system. Most of the content features are based on this plug-in system, and you can develop and use open source Webpack plug-ins to meet a wide range of requirements.
Fast Running
Webpack uses asynchronous I/O and multi-level caching to improve operational efficiency, which enables Webpack to compile quickly and incrementally at incredible speed
Installation
Installing Webpack with NPM
$ NPM Install Webpack
A common problem is that you cannot use the Webpack command after you install Webpack
This is because only the local installation is done, there is no global installation, and the following code is required for global installation to run
$ NPM Install Webpack-g
Use
First create a static page index.html and a JS entry file Entry.js
<!--index.html-->
// entry.jsdocument.write (' It works. ')
Then compile the entry.js and package to Bundle.js:
$ webpack entry.js bundle.js
The packaging process displays logs:
2.6.1time:47ms Asset Size Chunks Chunk namesbundle.js 2.66 kB 0 [ Emitted] main [0]./entry.js bytes {0} [built]
Open with a browser and index.html you'll see It works.
Next you add a module module.js and modify the portal entry.js :
// module.jsmodule.exports = ' It works from Module.js. '
// entry.jsdocument.write (' It works. ') ) document.write (Require (// Add Module
webpack entry.js bundle.jsRefresh page to see changes after repackagingIt works.It works from module.js.
2.6.1time:61ms Asset Size Chunks Chunk namesbundle.js 2.83 kB 0 [emitted] main [0]./module.js bytes {0} [built] [1]./entry.js bytes {0} [built]
Webpack parses the entry file and parses the individual files that contain the dependencies. These files (modules) are packaged in Bundle.js. Webpack assigns each module a unique ID and indexes and accesses the module through this ID. When the page starts, the code in the Entry.js is executed first, and the other modules are executed at run require time.
LoaderWebpack itself can only handle JavaScript modules, and if you want to work with other types of files, you need to convert using loader.
Loader can be understood as a converter for modules and resources, which itself is a function that accepts the source file as a parameter and returns the result of the transformation. Detailed information at this point
In the example above, we will introduce a CSS file style.css to the page, using require ("!style-loader!css-loader!. /style.css ") code, code reading order from right to left, indicating that the home page will style.css also as a module, first load Style.css, and then use css-loader to read it, and then style-loader insert it into the page
/**body {background:yellow;}
Modify Entry.js:
Require ("style-loader!css-loader!. /style.css ") document.write (' It works. ') ) document.write (Require ('./module.js '))
Install loader:
NPM Install Css-loader Style-loader
Recompile the package, refresh the page, you can see the yellow page background
If every time require the CSS file to write loader prefix, is a very tedious thing. We can automatically bind the required loader based on the module type (extension).
Modify the Entry.js require("!style-loader!css-loader!./style.css") to require("./style.css") , and then execute the
$ webpack entry.js bundle.js--module-bind ' Css=style-loader!css-loader '
Obviously, these two ways of using loader, the effect is the same
ConfigurationWebpack can also be executed with the specified configuration file, in addition to passing parameters at the command line. By default, the file for the current directory webpack.config.js is searched, which is a node. JS module that returns a JSON-formatted configuration information object, or a --config configuration file with the option to specify it.
To continue our case, create a dependency in the root directory package.json to add Webpack:
{ "name": "Project", "version": "1.0.0", "devdependencies":{ "Css-loader": "^0.28.4", "Style-loader": "^0.18.2", "Webpack": "^2.6.1" } }
Don't forget to run it npm install . You then create a configuration file webpack.config.js that defines the rules property for a separate module object in the following configuration, which contains two mandatory attributes: test and use. The equivalent of telling Webpack compiler that "the path to '. CSS ' is resolved in the Require ()/import statement", use Css-loader to convert before adding and packaging them.
var webpack = require (' webpack '= { // ingress file output: { Path: __dirname,// exit path filename: ' bundle.js '/ / export name }, module: { rules: [ /\.css$/,use: [' Style-loader ', ' Css-loader ' } ]} }
At the same time simplified entry.js style.css loading mode:
Require ('./style.css ');
Last run webpack , you can see that the results of Webpack through the configuration file are the same as the results from the previous section through the command line webpack entry.js bundle.js --module-bind ‘css=style!css‘
If the configuration file is not called the default webpack.config.js, but the other name, such as Test.js, you need to set the following command to package
Webpack--config Test.js
Plug - insPlug-ins can do more of the functionality that loader cannot do. The use of plug-ins is typically specified in the Webpack configuration information plugins option. The Webpack itself has some common plugins built in, and third-party plugins can be installed via NPM. Detailed information at this point
To use a plug-in, you just need to require () it and add it to the plugins array. Built-in plug-in does not need require, directly use can
Next, we use a simple built-in plug-in BannerPlugin to practice the configuration and operation of the plug-in, the role of this plug-in to the output of the file header to add comment information.
Modify webpack.config.js , add plugins :
var webpack = require (' webpack '= { // ingress file output: { Path: __dirname,// exit path filename: ' bundle.js '/ / export name }, module: { rules: [ /\.css$/,use: [' Style-loader ', ' Css-loader ' } ] }, plugins: [ new webpack. Bannerplugin (' This file was created by Xiaohuochai ') }
Then run webpack , open bundle.js , and you can see that the file header appears with our specified comment information:
/* * * * * * * * * (function// Webpackbootstrap/* * * * * *//The Module Cache/ *** * * * * var installedmodules = {}; // The following code is omitted
Development environmentWhen the project becomes larger, the compilation time of the webpack becomes longer, and the output of the compilation can be made with the progress and color by the parameters
$ webpack--progress--colors
If you do not want to recompile each time you modify the module, you can start the listening mode. When the listening mode is turned on, the unchanged module will be cached in memory after compilation, and will not be recompiled every time, so the overall speed of the listening mode is very fast.
$ webpack--progress--colors--watch
For example, after executing the above command, change the background color of the body of ' style.css ' to red, without recompiling, and the page changes after the page is refreshed.
Of course, using webpack-dev-server development services is a better choice. It will launch an express static resource Web server in localhost:8080, and will automatically run Webpack in listening mode, open http://localhost:8080/or http://localhost:8080/in the browser webpack-dev-server/can browse the pages in the project and compile the output of the resources, and through a Socket.io service to listen to their changes in real time and automatically refresh the page
# Installing NPM install Webpack-dev-server-g# run $ webpack-dev-server--progress--colors
For example, after executing the above command, change the background color of the body of ' style.css ' to blue, without recompiling, and without refreshing the page.
Webpack Getting Started