The core principles of WebPack

  1. Everything is module

Just as a JS file can be a ‘module’, other files (such as CSS, image, HTML) can also be considered modules. So, you can require(‘ myjsfile.js ‘) or require(‘.css’). This means that we can break things (businesses) into smaller, manageable pieces for reuse purposes.

  1. According to the need to load

Traditional module bundlers eventually compile all modules into a huge bundle.js file. But in a real app, the ‘bundle.js’ file might be 10M-15m in size and asynchronously load part of the code to load on demand.

Development mode and production mode

The first thing you need to know is that Webapck has many features, some in ‘development mode’, some in ‘production mode’, and some in both modes.

To generate bundles, you might add the following script items to the package.json file

'script': {"build":"webpack --config webapck.config.prod.js"
   "dev":"webapck-dev-server"
}
Copy the code

Webpack CLI and webapck – dev – server

It is worth noting that WebPack, as a module packaging tool, provides two user interaction interfaces

  1. Webapck CLI Tool — This is the default interface (which comes with webpack in the.bin directory)

  2. Webapck-dev-server tool — a Node.js server (you need to install it separately)

Webapck CLI (great for production build)

The command-line tool receives configuration options through the CLI, or through the config file (default webapck.config.js configuration file), which will be used in the webpack packaging process.

Although you may have started learning webapck through the CLI, the command-line tools are actually more used to create bundles for use in production environments

Usage:

OPTION 1:
// Global installation
npm install webpack --g
At the command line, use webpack to generate the package
webpack

OPTION2:
// Partial installation
npm install webpack --save
// Add it to script of package.json"Scripts" : {" build ":" webpack --config webpack.config.prod.js -p ",... }// How to use it
"npm run build"
Copy the code
Webapck-dev-server (great for creating development builds and serving static assets)

Webpack-dev-server is an express NodeJS server running on port 8080. This server will call webpack itself to implement the build. The advantage of this server is that it can provide utilities such as “Live Reloading” or “Hot Module Replacement(HMR)”

npm install webpack-dev-server --save
OPTION1:
// use the command line
webpack-dev-server --inline --hot

OPTION2:
// The script added to package.js"Scripts" : {" start ", "webpack dev - server - the inline - hot",... }/ / useNPM run start open browser at:http://localhost:8080
Copy the code
webpack vs webpack-dev-server options

Note that options like inline and hot are specific to webapck-dev-server, while others like hind-modules are specific to CLI modules

Wepack-dev-server CLI options and configuration items Note that you can pass parameters to webpack-dev-server in two ways:

  1. ‘devServer’ object via the webpack.config.js file
  2. CLI Options
// Send parameters through the CLI
webpack-dev-server --hot --inline
// Pass the parameter through webpack.config.js
devServer: {
inline: true.hot:true
}
Copy the code

Sometimes devServer configuration items (hot: true and inline: true) do not take effect, so I prefer to pass parameters to the CLI as follows

// package.json
{
    "scripts": "webpack-dev-server --hot --inline"
}
Copy the code

Note: Make sure you do not pass both hot: true and -hot

“Hot” and “inline” options for webpack-dev-server

The ‘inline’ option adds’ hot loading ‘to the entry page, and’ hot ‘enables’ hot replacement’, which attempts to reload the changed portion of the component (rather than reload the entire page). If both arguments are passed in, erbpack-dev-server will try hot replacement first when the resource changes and reload the entire entry page if it fails.

// When a resource changes, new bundles are generated in the following three cases, but there are differences
// The browser will not be refreshed
webpack-dev-server
// Refresh the browser
webpack-dev-server --inline
// Reload the changed section, and HRM fails to refresh the page
Copy the code

“Entry” : The case where the values are strings, arrays, and objects

The Entry configuration tells WebPack where the root module or starting point of the application is, and different types have different purposes.

Like most apps, if your app has a single entry, you can use any type of enter and the output will be the same

entry-array

However, if you want to append multiple files that are not dependent on each other, you can use the array format

For example, if you need to add ‘googleAnalytics. Js’ to your HTML, you can tell Webpack to append analytics. Js to bundle.js

entry-object

Now, suppose your application is a multi-page application rather than a SPA, with multiple HTML files (index.html and profile.html). You then tell WebPack to generate a bundle for each HTML file via an object

The following configuration will generate two JS bundle files, indexEntry. Js and profileEntry. Js for index. HTML and profileEntry

Use method:

//profile.html< script SRC = "dist/profileEntry js" > < / script >//index.html
<script src="Dist/indexEntry js"></script>
Copy the code
Entry-combination (Combination type)

You can also use array entries in object entry. For example, the following config will generate three files vendor.js and index.js, profile.js:

Output: ‘path’ and ‘publicPath’

The Output TAB tells WebPack how and where to store the output. Two configuration items for output, ‘path’ and ‘publicPath’, can be confusing.

‘Path’ simply tells Webapck where the results are stored, whereas’ publicPath ‘is used by many WebPack plug-ins in production mode to update url values embedded in CSS, HTML filesFor example, in your CSS, you might load’./test.png’ with another URL from your localhost. However, in production, the test.png file may exist in the CDN, which means you may need to manually update these urls to get the correct URL in production

To solve the problem of manually modifying urls, you can use the publicPath parameter of Webpack, which is understood and used by almost all plugins, and automatically updates these urls when creating production builds

// Development: Both Server and the image are on localhost. Image {background - image: url (". / test. PNG '); }// Production: Server is on Heroku but the image is on a CDNImage {background - image: url (" HTTPS:/ / someCDN/test. PNG ');
 }
Copy the code
Loaders and chaning Loaders module loading and chain module loading

Loaders are extra node modules designed to help ‘load’ or ‘import’ various types of files into js and CSS file formats that browsers can recognize. Further, loader also allows you to import these files into JS via require or import

For example, you can use able-loader to convert JS code written in ES6 to ES5 code that the browser can recognize

module: {
 loaders: [{
  test: /\.js$/, please Testfor ".js" file, if it passes, use the loader
  exclude: /node_modules/, please Exclude node_modules folderloader: Babel ←use Babel (shortfor'Babel - loader')}]Copy the code

Multiple loaders can be used on the same file and are called chaining. Chain calls are executed from right to left with “! “between loaders. To segment

For example, if we have a “macss. CSS” file and we need to dump its contents into the HTML CSS content, we can do this with the following two loaders: CSs-loader and style-loader

module: {
 loaders: [{
  test: /\.css$/Loader: 'style! CSS '< -- (shortforstyle-loader! css-loader) }]Copy the code

Can the following diagram explain how this process works

  1. Mycssfile.css will be treated as a dependency. Mycssfile.css will be treated as a dependency. Webpack first gives the CSS file to the ‘CSS-loader’ for processing

  2. Cs-loader loads all CSS content and its depency(e.g. @import otherCSS), saves it as json. webpack and passes the result to style-loader for further processing.

  3. Style-loader takes the JSON, adds CSS contents and inserts the string into the index.html file

Loaders can also be configured

Loaders can work in different ways by passing in different patameters

In the following example, we configure url-loader to use DataURLs directly if the image is smaller than 1024 bytes. We can specify this size by passing in the limit argument

. Babelrc file

How to parse react JSX to js files using the babel-loader presets option

module: {
  loaders: [{test: /\.jsx? $/,
      exclude: /(node_modules|bower_components)/,
      loader: 'babel'.query: {
        presets: ['react'.'es2015'}}]}Copy the code

However, many projects may have many Babel configuration items, in which case you can put balble’s configuration items into the.babelrc file. Babel-loader will automatically load the.babelrc file if it exists.

So in many cases, you might see:

//webpack.config.js 
module: {
  loaders: [{test: /\.jsx? $/,
      exclude: /(node_modules|bower_components)/,
      loader: 'babel'}}]//.bablerc{" react ": [" es2015"]}Copy the code

The plug-in

Plug-ins are typically Node modules that export bundles

For example, uglifyJSPlugin takes bundle.js and compresses and obfuscates the content to reduce the file size.

Similar extract-text-webpack-plugin internally uses csS-loader and style-loader to collect all CSS in one place and eventually extract the result into a separate “styles.css” file. And reference style.css in HTML.

//webpack.config.js
// Get all the.css files, merge their contents and extract the CSS contents into a separate "styles.css"
var ETP = require("extract-text-webpack-plugin");

module: {
 loaders: [{test: /\.css$/, loader:ETP.extract("style-loader"."css-loader")}}],plugins: [
    new ExtractTextPlugin("styles.css") //Extract to styles.css file]}Copy the code

Note: If you just want to inline your CSS with style tags, you don’t have to use the extract-text-webpack-plugin, just use the CSS loader and style loader:

module: {
 loaders: [{
  test: /\.css$/,
  loader: 'style! css' // (short for style-loader! css-loader)
 }]
Copy the code

Loaders and plug-ins

As you may already be aware, loaders handle separate file levels and are usually used before or during package generation.

Plug-ins work at the bundle or chunk level and are usually the last stage of bundle generation. Some plug-ins such as commonschunkPlugin modify the way bundles are generated even more directly.

The extension of the processing file

Many Webpack configuration files have a resolve property and then an empty string value as shown in the code below. Empty strings are used to resolve expressions that import files without file extensions, such as require(‘./myJSFile’) or import myJSFile from ‘./myJSFile’. The default is to find the path as a js file.

{
 resolve: {
   extensions: [' '.'.js'.'.jsx']}}Copy the code

CDN related content

Content Delivery Network (CDN)

It is a distributed network composed of edge node server farms distributed in different regions, which is built and overlaid on bearer network

Assume that the domain name accelerated through the CDN is www.a.com. After the CDN network is connected and the accelerated service is started, the process is as follows when the terminal user (Beijing) initiates an HTTP request:

  1. When a terminal user (Beijing) sends a request to a specified resource under www.a.com, the terminal user first sends a domain name resolution request to LDNS (local DNS).
  2. LDNS checks whether the IP address of www.a.com is recorded in the cache. If yes, it is returned directly to the end user. If no, consult the authorized DNS.
  3. When the authorized DNS resolves www.a.com, the IP address of domain name CNAME www.a.tbcdn.com is returned. The domain name resolution request is sent to aliyun DNS scheduling system and the optimal node IP address is assigned to the request.

4.LDNS obtains the resolved IP address returned by the DNS. The user obtained the resolved IP address. The user initiates an access request to the obtained IP address. Working principle:

  1. CDN acceleration resources are tied to domain names
  2. To access resources by domain name, DNS searches the IP address of the CDN node (edge server) nearest to the user
  3. To access the actual resources through IP, if there is no cached resource on the CDN, it will request the resource from the source site and cache it on the CDN node. In this way, the CDN node will have the cache of corresponding resources when the user accesses the CDN node next time.