Webpack Tutorial

Webpack Tutorial from Coding compiler. Webpack is a static module bundler for modern JavaScript applications.

Webpack Tutorial

When webpack processes an application, it internally creates a dependency graph that maps to each module the project needs and then generates all of those dependencies into one or more bundles .

From here you will learn more about JavaScript module and webpack module.

Starting with webpack 4.0.0, you don’t have to package a project by introducing a configuration file . However, webpack it is still highly configurable , and can well meet the demand.

Core Concepts of Webpack

Before you start, you need to understand its core concepts :

  • Entry
  • Output
  • Loader
  • Plugins

This webpack tutorial is intended to give a high-level overview of these concepts , as well as detailed and relevant use cases for specific concepts.

To better understand the ideas behind the module packaging tool and how the underlying principles work, check out these materials:

Webpack Entry Point

The entry point indicates which module webpack should use as the start of building its internal dependency graph , and webpack will find out which modules and libraries are dependent on the entry point (direct and indirect).

The default value is ./src/index.js, however, you can specify a different entry start point by configuring the entry attribute in the webpack configuration (or you can specify multiple entry start points as well).

Webpack.config.js
module.exports = {
 entry: './path/to/my/entry/file.js'

Webpack Export

The output attribute tells webpack where to output the bundles it creates , and how to name these files. The main output file defaults to ./dist/main.js the default output directory for other generated files ./dist.

You can specify a configuration in the outputfield, to configure these processes:

Webpack.config.js

const path = require('path');

module.exports = {
 entry: './path/to/my/entry/file.js',
 output: {
   path: path.resolve(__dirname, 'dist'),
   filename: 'my-first-webpack.bundle.js'

In the above example, we are through output.filename and output.path property, to tell the name of webpack bundle, and we want to bundle generate (emit) where. Maybe you want to know what the path module is imported at the top of the code. It is a Node.js core module for manipulating file paths.

Output Properties also more configurable features , in the output section to learn more about its concept.

Webpack Loader

As a self-contained feature out of the box, webpack itself only supports JavaScript. The loader enables the processing of those non webpack JavaScript files, and converts them to a valid first module , and then added to the dependency graph, which can be provided to the applications.

Note, loader can import import any type of module (such as .cssa file), which is webpack specific features, other possible packaged program or task execution is not supported. We think this language extension is necessary because it allows developers to create more accurate dependency graphs.

At a higher level, the loader has two characteristics in the webpack configuration :

  • test An attribute that identifies one or some files that should be converted by the corresponding loader.
  • use Attribute, which indicates which loader should be used when converting.
Webpack.config.jsconst path = require('path');
module.exports = {
 output: {
   filename: 'my-first-webpack.bundle.js'
 },
 module: {
   rules: [
     { test: /\.txt$/, use: 'raw-loader'
Webpack.config.jsconst path = require('path');
module.exports = {
 output: {
   filename: 'my-first-webpack.bundle.js'
 },
 module: {
   rules: [
     { test: /\.txt$/, use: 'raw-loader' }

In the above configuration, a single module to define the object rules attribute, which contains two attributes must be: test and use. This tells the webpack compiler (compiler) the following information:

“Hey, the webpack compiler, when you get the path to ‘.txt’ in the require()/ import statement, use the raw-loader conversion before you package it. ”

It is important to remember when, defined in the configuration loader in webpack, to be defined in module.rules instead rules. In order for you to benefit from this, webpack will give a warning if it is not done in the right way.

You can go deeper into the loader chapter to learn more about customizing the imported loader.

Webpack Plugins

The loader is used to convert certain types of modules, while the plug-ins can be used to perform a wider range of tasks, including: package optimization, resource management, and injection environment variables.

By looking at plug-in interface documentation to learn how to use it extend webpack function.

Wants to use a plug-in, you only need require()it, then add it to the plugins array. Most plugins can be customized with options. You can also use multiple times because of the different purposes with a plug in a configuration file, then need to use new to create an instance of operator.

Webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 通过 npm 安装
const webpack = require('webpack'); // 用于访问内置插件

module.exports = {
 module: {
   rules: [
     { test: /\.txt$/, use: 'raw-loader' }
   ]
 },
 plugins: [
   new HtmlWebpackPlugin({template: './src/index.html'})

In the above example, html-webpack-plugin an html file is generated for your application and then all generated bundles are automatically injected.

Webpack offers many plugins available out of the box! Check out our list of plugins for more information.

The use of plug-in webpack configuration is straightforward, but there are a lot we can further explore the use cases! .

Webpack mode

By mode parameter setting development, production or none, in a corresponding WebPACK built environment can enable optimization. The default is production.

module.exports = {
 mode: 'production'

From the mode configuration can learn what to do in each mode are optimized.

Webpack Browser Compatibility

Webpack supports all ES5 compatible browsers (IE8 and below are not supported). webpack of import() and require.ensure()need to have an environment Promise. Before if you want to support older browsers, you should use the expression of these webpack provided to load a polyfill.

Webpack Entry Points

As we mentioned at the starting, there are many ways defined in webpack configuration entry attributes. Explain why it can be very useful addition, we’ll also show you how to configure entry properties.

Single Entry Syntax

usage:entry: string|Array<string>
Webpack.config.js
module.exports = {
 entry: './path/to/my/entry/file.js'
};

entry The single entry syntax for an attribute is the following shorthand:

module.exports = {
 entry: {
   main: './path/to/my/entry/file.js'
 }
};

When you ask entry when passed an array of what would happen? To entry pass “file path (file path) array” attribute will create “more the main entrance (Multi-main entry)” . The way you pass in an array is useful when you want multiple dependency files to be injected together and graph their dependencies into a “chunk”.

This is a great choice when you are looking for a quick setup of the webpack configuration for an application or tool that has only one entry point (ie library). However, using this syntax is inflexible when extending the configuration.

Object Syntax

usage:entry: {[entryChunkName: string]: string|Array<string>}
Webpack.config.jsmodule.exports = {
 entry: {
   app: './src/app.js',
   vendors: './src/vendors.js'
 }
};

Object syntax can be cumbersome. However, this is the most scalable way to define entries in your application.

“Extensible webpack configuration” means reusable and can be combined with other configurations. This is a popular technique for separating concerns from the environment, build targets, and runtimes. Then merge them using specialized tools like webpack-merge .

Common use cases:

Here are some of the entry configurations and their actual use cases:

Separate application (app) and third party (vendor) portals

Webpack.config.js

module.exports = {
 entry: {
   app: './src/app.js',
   vendors: './src/vendors.js'
 }
};

what is this? On the surface, this tells us webpack from app.js and vendors.js start creating dependency graph (dependency graph). These dependency graphs are completely separate and independent of each other (one webpack bootstrap in each bundle). This approach is more common in a single page application with only one entry start (excluding the vendor).

why? This setting allows you CommonsChunkPlugin to extract vendor references (vendor reference) to the vendor bundle, and the partial replacement of references from the vendor for the “application bundle” the __webpack_require__() calls. If there is no vendor code in the application bundle, then you can implement a generic pattern called long- lived caching in webpack .

To support DllPlugin that provides better vendor separation, consider removing the scenario.

Multi-page application

Webpack.config.jsmodule.exports = {
 
entry: {
   pageOne: './src/pageOne/index.js',
   pageTwo: './src/pageTwo/index.js',
   pageThree: './src/pageThree/index.js'

what is this? We tell webpack that we need 3 separate dependency graphs (as in the example above).

why? In a multi-page application, the server will get a new HTML document for you. The page reloads the new document and the resource is re-downloaded. However, this gives us a special opportunity to do a lot of things:

Use CommonsChunkPlugin the application to share code between each page to create a bundle. Due to the increased number of entry points, multi-page applications can reuse a large number of code/modules between the entry points, which can greatly benefit from these technologies.

Based on experience: each HTML document uses only one entry start point.

Webpack Output

Configuration output options control webpack how to compile files written to the hard disk. Note that Entrance only one Output configuration can be specified , even though there can be multiple starting points .

Usage

Webpack arranged in the output minimum property requirement is to set its value to an object, comprising the following two points:

  • filename The name of the file to use for the output file.
  • Target output directory path absolute path.
webpack.config.js

module.exports = {
 output: {
   filename: 'bundle.js',
   path: '/home/proj/public/assets'
This configuration of a single bundle.js output file to the /home/proj/public/assets directory.

Multiple Entry Points

If the configuration creates multiple separate “chunks” (for example, using multiple entry starters or using plugins like CommonsChunkPlugin), you should use substitutions to ensure that each file has a unique name.

module.exports = {
 entry: {
   app: './src/app.js',
   search: './src/search.js'
 },
 output: {
   filename: '[name].js',
   path: __dirname + '/dist'
 }
};

// Write to hard disk:./dist/app.js, ./dist/search.js

Advanced Output

The following is a complex example of using CDN and resource hashes:

config.jsmodule.exports = {
 //...
 output: {
   path: '/home/proj/cdn/assets/[hash]',
   publicPath: 'https://cdn.example.com/assets/[hash]/'

Final output file does not know at compile time publicPath the path of the case, publicPath can be left blank, is provided at the inlet and the dynamic run file start point. If you don’t know at compile time publicPath, you can ignore it first and set it at the beginning of the entry __webpack_public_path__.

__webpack_public_path__ = myRuntimePublicPath;
// Remaining application portal

Webpack Mode

Provide mode configuration options, use the built-in optimization inform webpack corresponding mode.

string

Mode The default value is production.

Usage

Only in the configuration mode options

module.exports = {
 mode: 'production'
};

Or pass from the CLI parameters:

webpack --mode=production

The following string values ​​are supported:

Development:

It will process.env.NODE_ENVset the value development. Enabling NamedChunksPlugin and NamedModulesPlugin.

Production:It will process.env.NODE_ENVset the value production. Enable FlagDependencyUsagePlugin, FlagIncludedChunksPlugin,

ModuleConcatenationPlugin, NoEmitOnErrorsPlugin, OccurrenceOrderPlugin, SideEffectsFlagPluginand UglifyJsPlugin.

None: Do not use any default optimization options

If not set, webpack will be production used as mode default values to set. Among them, mode supports the following values:

Remember, just set NODE_ENVthe time, it does not automatically set mode.

mode: development

// webpack.development.config.js

module.exports = {
+ mode: 'development'
- plugins: [
-   new webpack.NamedModulesPlugin(),
-   new webpack.NamedChunksPlugin(),
-   new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("development") }),
- ]
}

mode: production

// webpack.production.config.js

module.exports = {
+  mode: 'production',
-  plugins: [
-    new UglifyJsPlugin(/* ... */),
-    new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("production") }),
-    new webpack.optimize.ModuleConcatenationPlugin(),
-    new webpack.NoEmitOnErrorsPlugin()
-  ]
}

mode: none

// webpack.custom.config.js

module.exports = {
+  mode: 'none',
-  plugins: [
-  ]
}

If you want to influence the compilation behavior based on the mode variable in webpack.config.js , you must export the object instead of exporting a function:

var config = {
 entry: './app.js'
 //...
};

module.exports = (env, argv) => {

 if (argv.mode === 'development') {
   config.devtool = 'source-map';
 }

 if (argv.mode === 'production') {
   //...
 }

 return config;
};

Webpack Loader

The loader is used to convert the source code of the module. loader can make you import or “load” file preprocessing module. Therefore, the loader is similar to the “task” in other build tools and provides a powerful way to handle front-end build steps. The loader can convert files from different languages ​​(such as TypeScript) to JavaScript, or convert inline images to data URLs. The loader even allows you to directly load import CSS files in a JavaScript module !

Webpack Loader Example

For example, you can use the loader to tell webpack to load CSS files, or to convert TypeScript to JavaScript. To do this, first install the corresponding loader:

npm install --save-dev css-loader
npm install --save-dev ts-loader

Then webpack instructions for each .css use css-loader, as well as for all .ts use of the file ts-loader:

Webpack.config.js

module.exports = {
 module: {
   rules: [
     { test: /\.css$/, use: 'css-loader' },
     { test: /\.ts$/, use: 'ts-loader' }
   ]
 }
};

Using Loader

There are three ways to use the loader in your application:

  • Configuration (recommended): Specify the loader in the webpack.config.js file.
  • Inline : each import explicitly specify loader statement.
  • CLI : Specify them in a shell command.

Configuration

Module.rules Allows you to specify multiple loaders in the webpack configuration. This is a concise way to show the loader and help to make the code simple. It also gives you a global overview of each loader:

module.exports = {
 module: {
   rules: [
     {
       test: /\.css$/,
       use: [
         { loader: 'style-loader' },
         {
           loader: 'css-loader',
           options: {
             modules: true
           }
         }
       ]
     }
   ]
 }
};

Inline

Can import statement or any equivalent to “import” a way to specify the loader. Use !separate resource loader. Each part that is separated is parsed relative to the current directory.

import Styles from 'style-loader!css-loader?modules!./styles.css';

By prepending all rules and usage !, the source file can be reloaded into any loader in the configuration.

Options can pass query parameters, for example ?key=value & foo=bar, or a JSON object, for example ?{“key”:”value”,”foo”:”bar”}.

Use module.rules it whenever possible , as this reduces the amount of code in the source code and allows you to debug and locate problems in the loader faster when errors occur.

CLI

You can also use the loader via the CLI:

webpack --module-bind jade-loader --module-bind 'css=style-loader!css-loader'

It will .jade document the use jade-loader of .css files style-loader and css-loader.

Loader Feature

  • The loader supports chained delivery. Each loader in the loader chain converts the resources processed by the previous loader. The loader chain will execute in the reverse order. The first loader passes the result of the application (using the converted resource) to the next loader, which is executed in turn. Finally, the last loader in the chain returns the JavaScript expected by webpack.
  • The loader can be synchronous or asynchronous.
  • The loader runs in Node.js and is able to perform any possible operations.
  • The loader receives the query parameters. Used to pass the configuration to the loader.
  • It can also be used loader options object configuration.
  • In addition to the use of package.json common main property can also be exported as plain npm module loader, practice is package.json defined in a loaderfield.
  • Plugins can bring more features to the loader.
  • The loader can generate additional arbitrary files.

The loader provides more power to the JavaScript ecosystem through the (loader) preprocessor. Users now have more flexibility in introducing fine-grained logic such as compression, packaging, language translation, and more .

Parsing loader

The loader follows standard module parsing . In most cases, loader from the module path (usually the module path considered npm install, node_modules) resolution.

The loader module needs to be exported as a function and written in Node.js compatible JavaScript. It is usually managed using npm, but you can also use a custom loader as a file in your application. By convention, the loader is usually named xxx-loader (for example json-loader).

Webpack Plugins

Plugins are the backbone of webpack . The webpack itself is built on top of the same plugin system you used in the webpack configuration !

The plugin is designed to solve other things that the loader can’t .

Anatomy

webpack plug-in is having a apply JavaScript object method. Apply The properties are called by the webpack compiler, and the compiler object is accessible throughout the compilation lifecycle.

ConsoleLogOnBuildWebpackPlugin.js
const pluginName = 'ConsoleLogOnBuildWebpackPlugin';

class ConsoleLogOnBuildWebpackPlugin {
 apply(compiler) {
   compiler.hooks.run.tap(pluginName, compilation => {
     console.log('webpack The build process begins!');
   });
 }
}

The first argument to the tap method of the compiler hook should be the name of the camel named plugin. It is recommended to use a constant for this so that it can be reused in all hooks.

Usage

Since the plug can carry parameters / options, you must webpack configuration, the pluginsincoming attribute newinstance.

There are several ways to use plugins depending on your webpack usage.

Configuration

webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin'); //Install via npm
const webpack = require('webpack'); //Access the built-in plugin
const path = require('path');

module.exports = {
 entry: './path/to/my/entry/file.js',
 output: {
   filename: 'my-first-webpack.bundle.js',
   path: path.resolve(__dirname, 'dist')
 },
 module: {
   rules: [
     {
       test: /\.(js|jsx)$/,
       use: 'babel-loader'
     }
   
]
 },
 plugins: [
   new HtmlWebpackPlugin({template: './src/index.html'})
 ]
};

API Node

Even with Node API, the user should be passed in the configuration plugins properties. Compiler.apply Not the recommended way to use it.

some-node-script.js
const webpack = require('webpack'); //Access webpack runtime
const configuration = require('./webpack.config.js');

let compiler = webpack(configuration);
compiler.apply(new webpack.ProgressPlugin());

compiler.run(function(err, stats) {
 // ...
});

Did you know that the example seen above is very similar to webpack’s own runtime (runtime) . There are a lot of usage examples hidden in the wepback source , which you can use in your own configuration and scripts.

Webpack Configuration

You may have noticed that very few webpack configurations look exactly the same. This is because the webpack configuration file is a JavaScript file that exports an object. This object is parsed by webpack based on the properties defined by the object.

Because the webpack configuration is a standard Node.js CommonJS module, you can do the following :

  • By require(…)import other files
  • By require(…)using npm utility functions
  • JavaScript expression using flow control, for example, ?:the operator
  • Use constants or variables for commonly used values
  • Write and execute functions to generate partial configurations

Please use these features at the right time.

Although technically feasible, the following practices should be avoided :

  • Access command line interface (CLI) parameters when using the webpack command line interface (CLI) (should write your own command line interface (CLI), or use–env )
  • Export undefined values ​​(calling webpack twice should produce the same output file)
  • Write a very long configuration (you should split the configuration into multiple files)

The biggest thing you need to get from this document is your webpack configuration, which can be in a variety of formats and styles. But for you and your team to be easy to understand and maintain, you should always adopt the same usage, format and style.

The following example shows how the webpack configuration object is both expressive and configurable because the configuration object is the code :

Basic Configuration

Webpack.config.js
var path = require('path');

module.exports = {
 mode: 'development',
 entry: './foo.js',
 output: {
   path: path.resolve(__dirname, 'dist'),
   filename: 'foo.bundle.js'
 }
};

Multiple Targets

View: Export multiple configurations

Use a different configuration language

Webpack accepts configuration files written in a variety of programming and data languages.

Webpack Modules

In modular programming , developers break down the program into discrete chunks of functionality and call it _module_.

Each module has a smaller contact surface than the full program, making verification, debugging, and testing a breeze. The well-written _module_ provides reliable abstraction and encapsulation boundaries, giving each module in the application a well-organized design and clear purpose.

Node.js supports modular programming from the very beginning. However, on the web, modular support is coming slowly. There are several tools on the web that support JavaScript modularity, each with its own advantages and limitations. The webpack is based on lessons learned from these systems and applies the concept of _module_ to any file in the project.

What is the webpack module?

Comparing the Node.js module , webpack_module_ can express their dependencies in various ways, a few examples are as follows:

Webpack 1 requires a specific loader to convert ES 2015 import, but webpack 2 can be used out of the box.

Supported module types

Webpack supports various languages ​​and preprocessor writing modules through the loader . loader described webpack how to deal with non-JavaScript (non-JavaScript) _ _ module, and a bundle introduction of these dependencies _ _. The webpack community has built loaders for a variety of popular language and language processors , including:

In general, webpack provides a customizable, powerful, and rich API that allows any technology stack to use webpack, keeping it non- opinionated in your development, testing, and build processes

Webpack Module Resolution

The resolver is a library that helps to find the absolute path of the module. A module can be used as a dependency module for another module and then referenced by the latter, as follows:

import foo from 'path/to/module';
// or
require('path/to/module');

The module that depends on can be a library from application code or a third party. The resolver helps webpack find the module code that needs to be introduced in the bundle, which is included in each require/ import statement. Webpack Use enhanced-resolve to parse file paths when packaging modules

Parsing rules in webpack

Using enhanced-resolve webpack, it can parse the three file paths:

Absolute path

import '/home/me/file';
import 'C:\\Users\\me\\file';

Since we have obtained the absolute path of the file, no further analysis is required.

Relative path

import ‘../src/file1’;
import ‘./file2’;

In this case, use import or require directory resource file (resource file) where the context is considered directory (context directory). In import/require a relative given path, the path will add this context (context path), to generate an absolute path to the module (absolute path).

Module path

import 'module';
import 'module/lib/file';

Module will resolve.modules search all directories specified. You can replace the original module path, through the use of this alternative path resolve.alias to create an alias configuration options.

Once the path is resolved according to the above rules, the resolver will check if the path points to a file or directory. If the path points to a file:

  • If the path has a file extension, the file is packaged directly.
  • Otherwise, the [ resolve.extensions] option is used as a file extension to resolve, which tells the parser which extensions (for example .js, .jsx) can be accepted in parsing .

If the path points to a folder, take the following steps to find the correct file with the correct extension:

  • If the folder contains package.json files, in order to find resolve.mainFields the configuration options specified in the field. And package.json the first such field determines the file path.
  • If the package.json file does not exist or package.json main field file does not return a valid path, in order to find resolve.mainFiles the configuration options specified in the file name, to see if there is a match to the file name in the import / require directory.
  • File extensions resolve.extensions parsing using a similar method options.

The webpack provides a reasonable default configuration for these options based on the build target .

Parsing Loader (Resolving Loaders)

Loader parsing follows the same rules as those specified by the file parser. But the resolveLoader configuration options can be used to provide independent parsing rules for the Loader.

Cache

Each file system access is cached to trigger multiple parallel or serial requests to the same file faster. In observation mode , only modified files are extracted from the cache. If you turn off watch mode, clean up the cache before each compilation.

Webpack Dependency Graph

At any time, one file depends on another, and webpack treats this as a dependency between files . This allows webpack to receive non-code assets (such as images or web fonts) and can provide them as _dependencies to your application.

Webpack starts with a list of modules defined in the command line or configuration file and processes your application. From the beginning of these entries , webpack recursively builds a dependency graph that contains each module required by the application and then packages all of these modules into a small number of bundles– usually only one – that can be loaded by the browser.

For HTTP/1.1 clients, packaging your application by webpack is especially powerful because it reduces the amount of time an application must wait when a new request is made by the browser. For HTTP/2 , you can also use Code Splitting and webpack packaging for optimal optimization

Webpack Manif

There are three main types of code in a typical application or site built using webpack:

  1. Source code written by you or your team.
  2. Your third source’s library or “vendor” code will depend on your source code.
  3. The webpack’s runtime and manifest manage the interaction of all modules.

This article will focus on the last of these three parts, runtime and manifest.

Runtime

As mentioned above, we will only briefly introduce it here. The runtime, along with the accompanying manifest data, mainly refers to all the code that webpack uses to connect to the modular application while the browser is running. The runtime contains: the loading and parsing logic required to connect the modules as they interact. Includes connections to loaded modules in the browser, and execution logic for lazy loading modules.

Manifest

Then, once your application, shaped like a index.html file, some of the bundle and resources loaded into the browser, what happens? You orchestrated /src the file directory structure does not exist now, so webpack how to manage the interaction between all the modules it? This is the origin of the use of manifest data…

When the compiler starts executing, parsing, and mapping the application, it retains the detailed points of all the modules. This collection of data is called “Manifest” and is parsed and loaded by Manifest at runtime when it is packaged and sent to the browser. Whichever you choose modules grammar , those import or require statements have now been converted to a __webpack_require__method, which points to the module identifier (module identifier). By using the data in the manifest, the runtime will be able to query the module identifier and retrieve the corresponding module behind it.

Problem

So now you should have a little understanding of webpack working behind the scenes. “But what does this have to do with me?”, you might ask. The answer is not in most cases. The runtime does what it does, uses the manifest to perform its operations, and once your application is loaded into the browser, everything will show magical operation. However, if you decide to improve the performance of your project by using browser caching, understanding this process will suddenly become even more important.

By using the bundle to calculate the content hash as the file name, when the content or file is modified, the browser will point to the new file through the new content hash, thus invalidating the cache. Once you start doing this, you will immediately notice some interesting behavior. Even if some of the content on the surface is not modified, the calculated hash will change. This is because the injection of runtime and manifest changes every time you build.

Webpack Build Targets

Because both the server and browser code can be written in JavaScript, webpack provides a variety of build targets that you can set in your webpack configuration .

webpack the target property and not to output.libraryTarget attribute

Usage

To set the targetproperty, only you need to set the value of the target in your webpack configuration.

Webpack.config.js
module.exports = {
 target: 'node'
};

In the above example, the use of node webpack will be compiled into a “class Node.js” environment (using the Node.js require, rather than using any of the built-in modules (such as fsor path) to load the chunk).

Each target has a variety of deployment/environment-specific add-ons to support its needs. Look at the available values for target .

Further expansion for other popular target values

Multiple Targets

Although webpack not to support the target incoming multiple strings, you can create a homogenous library by packing two separate configurations:

Webpack.config.js
const path = require('path');
const serverConfig = {
 target: 'node',
 output: {
   path: path.resolve(__dirname, 'dist'),
   filename: 'lib.node.js'
 }
 //…
};

const clientConfig = {
 target: 'web', // <=== The default is 'web', which can be omitted
 output: {
   path: path.resolve(__dirname, 'dist'),
   filename: 'lib.js'
 }
 //…
};

module.exports = [ serverConfig, clientConfig ];

The above example will you dist create folder lib.js and lib.node.js file.

Resource

As you can see from the above options, there are several different deployments_targets to choose from. Below is a list of examples and resources you can refer to.

Webpack Hot Module Replacement

The HMR – Hot Module Replacement feature replaces, adds, or removes modules while the application is running , without having to reload the entire page. Mainly through the following ways to significantly speed up the development:

  • Retains the state of the application that was lost when the page was completely reloaded.
  • Only update changes to save valuable development time.
  • Adjusting the style is faster – almost equivalent to changing the style in the browser debugger.

How does all this work?

Let’s look at it from a few different perspectives to understand how HMR works…

In the application

The following steps can be used to swap in and out modules in an application:

  1. The application code requires the HMR runtime to check for updates.
  2. The HMR runtime (asynchronous) downloads the update and then notifies the application code.
  3. The application code requires the HMR runtime to apply the update.
  4. HMR runtime (asynchronous) application update.

You can set HMR so that this process automatically triggers an update, or you can choose to require updates when the user interacts.

In the Compiler

In addition to common resources, the compiler needs to issue an “update” to allow the previous version to be updated to the new version. “update” consists of two parts:

  1. Updated manifest (JSON)
  2. One or more updated chunks (JavaScript)

The manifest includes the new compiled hash and all the chunk directories to be updated. Each update chunk contains code for all update modules (or a flag to indicate that the module is to be removed) corresponding to this chunk.

The compiler ensures that the module ID and chunk ID are consistent between these builds. These IDs are usually stored in memory (for example, when using webpack-dev-server ), but they may also be stored in a JSON file.

In the Module

HMR is an optional feature that only affects modules that contain HMR code. For example, by style-loader as style style additional patches. In order to run the append patch, style-loader the HMR interface is implemented; when it receives the update via HMR, it replaces the old style with the new style.

Similarly, when the HMR interface is implemented in a module, you can describe what happens when the module is updated. However, in most cases, there is no need to force the HMR code to be written in each module. If a module does not have an HMR handler, the update will bubble. This means that a simple handler can update the entire module tree. If a separate module is updated in this module tree, the entire set of dependent modules will be reloaded.

About module.hot interface details, see the HMR API page .

In HMR Runtime

These things are more technical… If you are not interested in it internally, you can skip to the HMR API page or the HMR guide at any time .

For runtime module system, additional codes are sent to parents and children tracking module. On the management side, runtime supports two methods check and apply.

Check Send an HTTP request to update the manifest. If the request fails, there is no update available. If the request is successful, the chunk to be updated will be compared to the currently loaded chunk. For each loaded chunk, the corresponding chunk to be updated is downloaded. When the download is complete all pending updates chunk, you will be ready to switch to the readystate.

Apply The method marks all updated modules as invalid. For each invalid module, you need to have an update handler in the module, or an update handler in its parent module. Otherwise, the invalid tag is bubbling and also invalidating the parent. Each bubbling continues until the application entry start point is reached, or to the module with the update handler (whichever comes first). This process fails if it bubbling from the beginning of the entry.

After that, all invalid modules are processed and unloaded (via the dispose handler). Then update the current hash and call all “accept” handlers. The runtime switches back to 闲置state and everything continues as usual.

Getting Started with HMR

HMR can be used as a replacement for LiveReload during development. webpack-dev-server support hotmode, before attempting to reload the entire page, the heating mode will try to use the HMR to update. See the module hot update guide for more details .Like many other features, the power of webpack is its customizable. There are many ways to configure HMR depending on your specific project needs . However, for most implementations, webpack-dev-server it works well and allows you to get started quickly with HMR.

Related JavaScript Tutorials For Beginners

JavaScript Introduction Tutorials
Introduction to JavaScript
Javascript Reference and Specifications
Javascript Code editors
Javascript Developer Console
Javascript Basics
JavaScript Hello World.!
External JavaScript Files
JavaScript Code Structure
Use Strict in JavaScript

Leave a Comment