Webpack2 Learning Log

Source: Internet
Author: User

Webpack said easy also easy, said difficult also difficult, mainly is to see individual, want to learn what kind of degree, many companies may request just will use on the line, but also some companies require relatively high, to understand some underlying principle, so still want to spend some time, see individual demand. This article is just a summary, all from the official website, easy to review.

First, understand the concept of Webpack:

Official website:Webpack is a Modular Packager (module bundler)for a modern JavaScript application. When Webpack processes an application, it constructs a dependency graph recursively (dependency graph), which contains each module that the application requires, and then packages all of them into a small bundle -usually with only one , which is loaded by the browser.

Here to add, the difference between Webpack and gulp:

Gulp is a front-end automation build tool, Task runner, whose core functions are:

Definition and organization of 1,task

2, file-based stream build

3, plug-in system

Webpack is the module bundler, Modular Packager, the core functions are:

1, build the target file according to the dependency of the module

The 2,loader system supports different modules

3, plug-in system provides additional features

Original author Link: https://www.zhihu.com/question/45536395?sort=created, this piece is well written, summed up a lot of

For the use of Gulp, please see the Gulp study log;

Second, the core concept (Entry,output,loader,plugins)

1,entry and context

The function of the context is that Webpack will retrieve the entry file from the context-configured path first;

Such as:

Const CONFIG = {

Context:path.resolve ('./src '),//path.resolve ([from...],to), resolves the to parameter to an absolute path, path is the node module

Entry: ' Index.js '

}

Index.js files are placed in the SRC directory;

Webpack creates a graph of all the dependencies of the application (dependency graph), the starting point of which is entry points, the entry file, where to start, can be a single entry, or multiple portals, syntax can be a string, can be an object, can also be an array, the object is highly extensible

Single entry:

Const CONFIG = {

Entry: "./index.js '//String syntax

};

module.exports = config;

Equivalent to

Const CONFIG = {

Entry: {

Main: "./index.js"//Object syntax

}

};

module.exports = config;

You can also write multiple pages

 < span class= "token keyword" >const config = {entry: {pageone  "/src/pageone/index.js '  : :      }};
每一个key会是chunk的名称

2,output
入口起点可以多个,但是输出配置只有一个
两个必须的属性:
filename:输出文件名
path:输出目录,必须是绝对路径,否则会报错。
入口起点单个,最简单的例子:
Const CONFIG={Output:{filename:' Bundle.js ', Path:'/home/proj/public/assets '}};
If multiple entry beginnings
Const CONFIG = {
Output: {
FileName: ' [name].js ',
Path: __dirname + '/dist '//__dirname represents the current directory
}
}
The Publicpath property, which represents the directory referenced by the specified resource file, does not mean that the path defined in Publicpath can be omitted in front of path, such as
Output: {
Publicpath: '/dist ',
Path:path.resolve ('./dist/js '),
FileName: ' Bundle.js '
},
What does Output.chunkfilename do? (abhorrence, interview asked this question, a face, heard but do not know what to do-.) -)
This option determines the name of the non-portal chunk file, and the value is in the filename
(About Output.filename:
1, for a single entry starting point, filename is a static string,
FileName: "Bundle.js"
2, if not a single entry, in order to distinguish between different bundles, you need to use one of the following methods to give each bundle a unique name
FileName: ' [name].bundle.js '
Using the internal chunk ID
FileName: ' [id].bundle.js '
With each build process, the unique hash generation
FileName: ' [name]. [Hash].bundle.js '
Use a hash based on each chunk content
FileName: ' [chunkhash].bundle.js ')

Output.hotupdatechunkfilename: Custom Hot update chunk file name, optional values see filename above, no need to modify this value, the default is the line
Output has some other properties, not described here, see the official website



3,loader,
The source code of the module to convert, can be import or load (before packaging) preprocessing files, a bit similar to the task, in the webpack2.0 version, the following wording:
Module: {
Rules: [
{
Test:/\.txt$/,//test used to identify files that should be converted by the corresponding loader, using regular notation
Use: ' Raw-loader '//use is used to convert the file, and it can be added to dependency graph, and eventually added to the bundle, note that webpack2 inside loader must write the whole, Webpack1 in loader can only write '-' in front of, but 2 inside will error
}
]
}
We can also configure multiple loader for use:
Module: {
Rules: [
{
Test:/\.css$/,
Use: [
{loader: ' Style-loader '},
{
Loader: ' Css-loader ',
Options: {
Modules:true
}
}
]
}
]
}
Similarly we can use the CLI using loader to directly knock the command:
Webpack--module-bind jade-loader--module-bind ' Css=style-loader!css-loader '
This will use Jade-loader for. Jade files, using Style-loader and Css-loader for. css files

Each rule is divided into three parts: conditions, results, and nested rules:
1, Condition: There are two input values, resource: The absolute path of the request file, the related property is Test,include,exclude,resource
Issuer: The absolute path of the module file for the requested resource, and the related property is issuer
These two input values explain, from app.js inside import "./style.css", then resource is/path/to/style.css, and Issure is/path/to/app.js
2, results: There are two input values, the applied loader: The loader array applied on the resource,
Parser option: The option object used to create the parser for the module.
Properties that affect loader: loader,options,use,query,loaders
3, Nesting rules: attribute rules,oneof making nested rules
Other attributes of rule, see official documentation

4,plugin
The purpose of the plugin is to resolve things that loader cannot achieve.
Usage, passing the new instance to the Plugins property, I'll list some common plugin

Const Htmlwebpackplugin = require (' Html-webpack-plugin ');
Const Cleanwebpackplugin = require (' Clean-webpack-plugin ');
Const WEBPACK = require (' Webpack ')
plugins: [ new HtmlWebpackPlugin ({
    title: ‘Hot Module Replacement‘           //关于HtmlWebpackPlugin的参数配置,参考这个作者链接http://www.cnblogs.com/haogj/p/5160821.html
  }),
  new webpack.HotModuleReplacementPlugin(),        //模块热替换,
  new cleanWebpackPlugin([‘dist‘])             //清除dist文件夹
]

5, other configurations:

Devtool: Recommended "Cheap-module-eval-source-map" in the development environment, "SOURCE-MAP" in production environment, other options See official documents

Webpack-dev-server: This is not much to say, is a local service and then listen to file changes

Webpack-p equivalent to Webpack--optimize--define process.env.node_env= "' Production '" will perform the following steps:
Use Uglifyjsplugin for JS file compression, run Loaderoptionsplugin (mainly used to migrate webpack1 to Webpack2), set NODEJS environment variables, trigger some package packages, Compiling in a different way

Devserver: Configuration items See official documents, more than a few common:
Devserver: {
ContentBase:path.resolve (__dirname, ' dist '),
Compress:true,//All services enable gzip compression
port:9000,
Color:true,
Hot:true,
Hotonly:true,
Open:true
}

6,manifest
Concept: When the compiler starts to execute, parse, and map the application, it retains the detailed points of all the modules that are manifest
Runtime: The loading and parsing logic required for the connection module when interacting with the module, including the connection of modules already loaded in the browser, and the execution logic of the lazy load module.
When the package is finished and sent to the browser, the module is parsed and loaded at run time through manifest, when import or require has been converted to the __webpack_require__ method, which points to the module identifier by using the data in the manifest. Runtime will be able to query the module identifier and retrieve the corresponding module behind it.

7,target
Webpack provides a variety of build target targets that indicate which JavaScript is used in which environment
Node: Compiled for Class node. JS Environment Available
Web: Compile as available in a class browser environment (default)
。。。。。。



  < span class= "token keyword" >     




Webpack2 Learning Log

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.