WebPack4.0 Getting Started Practice Tutorial

WebPack can be seen as a module baler: what he does is to analyze your project structure, find JavaScript module and other browsers cannot run directly ( SCSS , typescript , etc.), which is packaged into a suitable format for browsers

Construction is to publish to convert source code into executable line the JavaScript , CSS, HTML code, including the following:

    Code conversion
  • : TypeScript compiled into JavaScript , SCSS compiled into CSS, etc. file optimization : Compression JavaScript , CSS, HTML code, compression merged picture, etc.
  • code division
  • : Extract the public code of multiple pages, extract the code that does not require the execution section makes it asynchronous to load
  • module merge
  • : There are many modules and files with modular items. Requires the building function to classify the module into a file
  • Automatic refresh
  • : monitor local source code change, automatic build, refresh browser
  • code check
  • : You need to detect whether the code meets the specifications before the code is submitted to the warehouse, and the unit test is automatically released by
  • : After updating the code, the code is automatically built out the code and Transfer to the publishing system.
  • Construction is actually an embodiment of engineering and automation in front-end development. Use a series of processes to implement, so that the code automatically performs this series of complex processes.

Basic Concept of Webpack

entry (entry point): WebPACK indicates which module should be used, which is constructed as an internal start dependency graph, which will identify WebPACK module library and is the starting point of entry (direct and indirect) dependent.

The default value is

./ src / index.js

, however, may be specified by a starting point for different inlet disposed in the entry webpack configuration attributes (or may specify a plurality of inlets starting point).

export output: attribute tells webpack where output bundles it created, and how to name the files, the main output file defaults to ./ dist / main.js

, the other generated files The default output directory is

./ dist loader: let webpack able to deal with those non-JavaScript files (webpack itself only understand JavaScript). loader can convert all types of files is valid module webpack can handle, then you can use packaged ability webpack, and to process them.

Note that, Loader import can be introduced into any type of module (e.g. .css file), which is webpack specific features, other tasks may be packaged programs or actuator does not support. We believe that this language extension is necessary because it allows developers to create more accurate dependency graph.

widget plugins: perform a wider range of tasks loader is used to convert certain types of blocks, which plug can be used. Range of plug-ins include, from packaging optimization and compression, all the way to redefine the environment variable. Extremely powerful plugin interface, can be used to handle a variety of tasks.

mode mode: by selecting



a Production among,To set the mode parameter, you can enable the WebPack built-in optimization

  • Module configured from entry start recursive ENTRY All Module dependent.
  • Each time you find a Module, you will find the corresponding conversion rules according to the configured Loader.
  • After converting MODULE, the Module that is currently dependent on the current Module.
  • These modules are grouped in entry, and an entry and all of its dependent module are divided into a group.

Final WebPack converts all Chunk into file output. WebPack will perform the logic defined in the Plugin in the appropriate timing throughout the process.

  • We generally have two sets of build environments in the daily front-end development work: set in a set of development, one Set of uses on a set of rows.
  • Development
  • : Configuration file used to development, used to define WebPack dev server and other things Production : Used to produce the configuration file for definition
  • uglifyjsplugin

SourceMaps , etc. may need to print DEBUG information when developing, Contains


file, and the production environment is used in the line, the code is compressed, and the DEBUG information is not printed at runtime. for exampleAxios, ANTD, etc. In our production environment, then we should install this dependence in the production environment, and WebPack-dev-server is required to be installed in the development environment

usually In the file installed in

    , we have -s -d, -d indicates that our dependence is installed in the development environment, while -s is installation dependencies in the production environment.
  • This article takes you to build basic front-end development environment, what do the front-end development environment do?
  • Constructing resources for HTML, CSS, JS, Picture, etc., using CSS pre-regulators, use Less
  • to configure Babel transcoder => Treatment and compression image
  • is disposed using ES6 +


can meet the basic configuration required in front-end development. Here is the rendering of this paper:
webpack4.0 入门实践教程

Building a basic development environment


MKDIR WebPack-Dev && Cd WebPack-Devnpm Init -ynpm I Webpack Webpack-Cli -d
Add Scripts

Generates a package.json file, add

“scripts”: {“builds”: {“build”: Mode production “}
  -  MODE 
mode (must, otherwise there will be Warning
), is

WebPack4 new parameter option, the default is Production – Mode Production

UglifyJS-WebPack-PLUGIN Code Compression

No need to define
    New WebPack. DefinePlugin ({“process.env.node_env”: json.stringify (“production”)})
  • Default
  • Production
  • Default Open NoemitonerRorsplugin -> Optimization.NoemitonerrorS Skip output when compiling to ensure that output resources do not include errors
  • Default Open ModuleConcateNationPlugin -> Optimization.ConcatenateModules ,
  • WebPack3
  • Added scope enhancement ( Scope hoisting ) - Mode Development Development environment Constructing Module using EVAL Increased constructing speed
  • No need to define
new webpack.definePlugin ({“process.env.node_env”: json.stringify (“development”)})


    NamedModulesPlugin -> Optimization.namedModules
  • The relative path of the module is displayed when using the module hot replacement (HMR)
  • After adding Scripts, new src / index.js , then execute npm run build
  • , you will find a new
  • dist directory, store It is WebPack to build a good main.js
  • file.

PS NPM Scripts User Guide New WebPack.config.js file To add more configuration information to WebPack, we need Create a WebPack configuration file. After creating webpack.config.js , then the webpack

command will be executed, and WebPack has the following basic configuration

configuration. Information:

Module.Exports = {Entry: ”, // Packing Port: Which module should be used as a WebPack to build its internal dependent graph Output: ”, // Exit Resolve: {}, // Configuration Analysis: Configure alias, extensions Automatic parsing determined extension, etc. DevServer: {}, // development server: Run dev / start configuration, such as port, proxy, etc. Module : {}, // Module configuration: Configure Loader (Processing non-JavaScript files, such as LesS, SASS, JSX, Picture, etc.), etc., etc., etc.: Package optimization, resource management and implant environment variable}

configuration First we go to

Const path = request (‘PATH’) Module.Exports = {// Specify Package Entry Entry: ‘./src/index.js’, // Package Output: {Path: path.resolve (__ DIRNAME, ‘DIST’), // Analysis The path is ./dist filename: ‘bundle.js’}}

above we define the packaging entry

./ src / index.js , package Export is . / Dist

, the packaged folder name is
bundle.js , after executing
 npm run build  command, the index.js file will be packaged as  Bundle.js 
file. At this point, an HTML file is created. This bundle.js
can see you in

index.js . Path.Resolve ([… paths]) method will parse a sequence of a path or path fragment into an absolute path. Use HTML-WebPack-Plugin to create an HTML file We don’t want to pack once, create a new HTML file to leadWith the packaged file, this is not intelligent or when you pack the file name to modify, the reference path will be wrong. This time we can use the HTML-WebPack-Plugin plugin to associate the HTML reference path and our build results. NPM Install HTML-WebPack-Plugin -D

Create a file

public / index.html Modification WebPack.config.js

const htmlwebpackplugin = Require (‘html-webpack-plugin’) module.exports = {//// … plugins: [New HTMLWebPackPlugin ({filename: ‘index.html’, // Configuring Output File Name and Path Template: ‘./public/index.html’ // Configure HTML file})]}
   NPM Run Build 
, the dist catalog will be multiple index.html
and introduced

bundle.js Compressed HTML file

Modified WebPack.Config.js
const htmlwebpackplugin = Require (‘html-webpack-plugin “) Module.exports = {// … plugins: [New HTMLWebPackPlugin ({filename: ‘index.html’, // Configuring Output file name and path template: ‘./public/index.html’, // Configure HTML to be compiled Document Hash: True, // Compressed => Production mode Using minify: {transovettributequotes: true, // Delete Double quotes collapsewhitespace: true // Fold HTML is a row}}]}

We want to use WebPack to build a CSS file, for this, need to introduce Loader in the configuration to resolve and process CSS files:

NPM Install Style-Loader CSS-Loader -D

SRC / askS / STYLE / color.css , modify
 WebPack.config.js  file:  

module.exports = {// … module: {/ ** * test : Match specific conditions. A regular expression or regular expression of a regular expression is typically provided * include: Match specific conditions. It is generally provided a string or string array * Exclude: excludes specific conditions * and: Must match all the conditions in the array * or: Match an array, * NOR: must exclude * / ruLes: [{test: /\.css $/, include: [path.resolve (__ DIRNAME, ‘SRC’)], Use: [‘Style-Loader’, ‘CSS-Loader’]}]} // ..

After the processing of the two Loader, the CSS code will be converted to JS, and if you need to separate the CSS file separately, we need to use Mini-CSS-Extract -plugin plug-in

Extract CSS to independent file, automatically add prefix
NPM I mini-css-extract-plugin postcss Loader Autoprefixer -D

We can't avoid browser compatibility when writing CSS, such as Transform

attribute, you need to add browser prefixes to be With other browsers. Therefore, use
postcss-loader , the following is the relevant configuration

const minicssextractplugin = Require (‘mini-css-extract-plugin “) module.exports = {// … module: {rules: [{test: /\.css $/, include: [Path.Resolve (__Dirname, ‘src’)], Use: [MinicssextractPlugin.Loader, ‘CSS-loader ‘, {loader:’ Postcss-loader ‘, options: {plugins: [Require (‘ autoprefixer ‘)]}}]}]}, plugins: [// … new minicssextractplugin ({filename:’ Name] .css’, chunkfilename: ‘[ID] .CSS’}]}

Packaging Less file
 development It usually uses a pretreatment language, here as an example of  Less , by 
Less-Loader can be packaged as CSS file

NPM Install Less Less-loader -d

New SRC / askS / style / index.less , and in

Import ‘./assets/style/index.less’
 Configuration  WebPack.config.js 

const minicssextractplugin = Require (‘mini-css-extract-plugin “) module.exports = {module: {rules: [// … {test: / / \ $ $ Uses: [MinicssextractPlugin.LoadeR, ‘CSS-Loader’, {Loader: ‘Postcss-loader’, options: {plugins: [Require (‘autoprefixer’)] // Add a browser prefix in CSS}}, ‘less-loader’]}] } //… }

After the package, you can find the style of Index.less

color.css is packaged in
 main.css .  
WebPack @ V4 upgrade stepped pit: About using Mini-CSS-Extract-Plugin
‘s attention.

NPM Install File-Loader Url-Loader -D

FILE-Loader: Can be used to handle a lot of types of files, and its main role is to output files directly and return the built file path. URL-LOADER: If the picture is more, there will be a lot of HTTP requests, which will reduce the page performance.

will encode the introduced picture to generate DataURL. It is equivalent to translating the picture data into a string of characters. Then pack this string to the file, and eventually you only need to introduce this file to access the picture. Of course, if the picture is large, the encoding will consume performance. So URL-Loader
 provides a LIMIT parameter, which is smaller than the Limit byte will be converted to DataURL, which is greater than the LIMIT to use  File-Loader  to perform COPY. 
URL-LoAder can be seen as a enhanced version of File-Loader.
URL-Loader encodes the picture into the base64 format to write into the page, thereby reducing server requests.

Module.Exports = {Module: {Rules: [// ... {test: /\. (PNG|JPG|GIF) $, Use: [{loader: 'url-loader', options: {OutputPath: 'Images /', // Output to images folder Limit: 500 // is the format of a file that is less than 500b into base64, write js} }]}]} //... }

url-loader and file-loader what is the relationship?


Url-Loader encapsulated File-loader

URL-LOADER does not depend on
 file-loader , only when  URL-Loader 
is required, only url-loader
is required, No need to install


, because

URL-Loader has built-in file-loader . Through the above description, we can see, url-loader work two possibilities:

    the file size is less than the limit parameters, url-loader will be put into the file DataURL
  • The size of the piece is greater than the limit, url-loader calls the file-loader to process, and the parameters will pass directly to the file-loader. So we only need to install URL-LOADER.
and File-Loader
 analysis: image introduction of Webpack - Enhanced File-Loader: Url-loader   


is a JS compilation that allows us to use ES new features Tools, we can configure Babel in WebPack to use the ES6, ES7 standard to write JS code. Related Dependent Packages of Babel 7 Need to add @babel Scope. A major change is that Presets set by the original ENV to @ Babel / Preset-Env , you can configure Targets , Usebuiltins , etc. Options are used to compile the code that is compatible with the target environment. Where USEBUILTIS If set to "Usage" , Babel will introduce the corresponding Polyfill as needed according to the ES6 / ES7 code used in the actual code, and Targets you specify. without the need to introduce

import ‘@ Babel / polyfill’

in the code, avoiding the output package, while can safely use a variety of new grammar characteristics.

  • NPM I Babel-Loader @babEL / CORE @ Babel / Preset-Env -d
  • The author is equipped with the version number

{" Babel-loader ":" ^ 8.0.4 "," @ Babel / Core ":" ^ 7.1.2 "," @ Babel / PRESET-ENV ":" ^ 7.1.0 "}

Babel-Loader: Use Babel to convert ES6 code to use


@ Babel-Preset-ENV: By default, ES2015 + ES2016 + ES2017, that is, it transforms these three versions of ES syntax.

@ Babel / Core: Babel Core Bank

New .babelrc


{” PRESETS “:[[[@ Babel / PRESET-ENV”, {“Modules”: false, “Targets”: {“Browsers”: [“> 1%”, “Last 2 Versions”, “Not IE Presets is a bunch of Plugins’s presets, which makes it easy. Plugins is encoding transformation tools, Babel will be based on the plugin you configure Perform corresponding conversion. Modified WebPack.Config.js

module.exports ={Module: {Rules: [// … {test: /\.m?js $/, Exclude: / (node_modules | Bower_Components) /, Use: {loader: ‘Babel-loader’}}]}}
  Babel / Polyfill and Transform-Runtime  
Babel only converts new JavaScript syntax (Syntax) without converting new API, such as Iterator, Generator, SEMBOL, PROXY, REFLECT, SYMBOL, PROMISE, etc., and some ways to define on global objects (such as Object.assign) will not rotate.
Babel-polyfill: As mentioned above, for new APIs, you may need to introduce Babel-polyfill to compatibility

key points
 Babel-polyfill It is to simulate a complete ES2015 + environment designed for applications instead of library / tools.  Babel-Polyfill will contaminate the global role  

Extract the auxiliary function . When ES6 transcathes, Babel will need some auxiliary functions, such as _extend. Babel defaults to each of these auxiliary functions to each JS file, Babel provides Transform-Runtime to make these auxiliary functions "move" into a separate module Babel-Runtime, which can reduce the size of the project file.

Provide Polyfill

: Will not contaminate global scope, but do not support examples such as Array.includes

Babel-Runtime is more like a dispersed polyfill module, Need to be introduced separately in the respective modules, with

plug-ins, it is to process all this, that is, you don’t want to be related to the file IMPORT Polyfill
, you only need to use,  Transform-Runtime <= 8"]
 "useBuiltIns": "usage"
} will help you introduce. 
For development applications, it is more convenient to use the above-described on-demand
    , but if it is a development tool, this solution is not necessarily suitable (
  • Babel -Polyfill
  • is achieved by adding methods to global objects and built-in objects to add methods to the method, resulting in global variable contamination). Babel provides another program
  • Transform-Runtime
  • , which will only introduce a code that needs

during the compilation process into a corresponding module in Core-JS . Link (Alias). Regarding the specific differences and selection of these two programs, you can search the relevant tutorial yourself, this is no longer expanded, and a reference configuration scheme of

is provided below.
 First installation of Runtime Related Dependency   
NPM I @ Babel / Plugin-Transform-Runtime -Dnpm I @ Babel / Runtime -s



  • {// … “plugins”: [ “@ babel / plugin-transform-runtime”]}

Package before cleaning the source directory file clean-webpack-plugin
  • each package, static resources will build the project, with the additions and deletions of certain documents, under our dist directory may produce some no longer in use static resources, webpack does not automatically determine what resources are needed, in order to keep these old files can also be deployed to take up space on the production environment, so before packing webpack best to clean up the dist directory.
  • npm install clean-webpack-plugin -D

Review webpack.config.js file

const CleanWebpackPlugin = require ( ‘clean-webpack-plugin’) module.exports = {plugins: [new CleanWebpackPlugin ([ ‘dist’])]}

extraction common code If you a.js and b.js import all the c.js file, this code would jumbled up. Why should extract common code, simply put, is to reduce the code redundancy, load faster.

module.exports = {// … optimization: {splitChunks: {cacheGroups: {commons: {// detached write their own common code chunks: ‘initial’, name: ‘common’, // file name of the package, arbitrarily named minChunks: 2, // minimum reference 2 minSize: 0 // 0 bytes long beyond a new packet is generated}, styles: {name: ‘styles’, // public detached style test: /\.css$/, chunks: ‘all’, minChunks: 2 , enforce: true}, vendor: {// detached third party plug-test: / node_modules /, // specified third party package chunks in node_modules: ‘initial’, name: ‘vendor’, // the files packaged name, any name // set priorities, and to prevent self-defined common code extracted is covered, not packaged priority: 10}}}}}

hash is doing with? Every time we packed out the results may have been the same file, that when I was on the line is not asked to replace js on the line, how do I know which is the latest of it, we will generally clear about the cache. The hash in order to solve this problem exists

In this case we have to change the number of webpack.config.js disposed in the
module.exports = {/ / … output: {path: path.resolve (__ dirname, ‘dist’), filename: ‘[name] [hash: 8]. .js’}, // … pLugins: [{filename: ‘[Name]. [hash: 8] .css’, chunkfilename: ‘[id]. [hash: 8] .css’}]}

Reduce resolve analysis, configures alias

If we can streamline resolve
 configuration, let  WebPack  in Query Module When the path is rapidly positioned to the required module, do not do additional query work, then 
WebPack will be fast

Module .exports = {Resolve: {/ ** * alias: Alias ​​Configuration * * EXTENSIONS: Automatic parsing determines the extension, *, such as import ‘xxx / theme.css’ can add ‘.css’ in Extensions, introduction method Import ‘xxx / theme’ * @Default [‘.wasm’, ‘.mjs’, ‘.js’, ‘.json’] * * Modules Tells the WebPack to resolve the module * If you want to add a directory Go to the module search directory, this directory is preferred in Node_Modules / Search * This configuration can simplify the display of the module to some extent, upgrade build speed @Default node_modules priority * / alias: {‘@’: path.Resolve (__ Dirname, ‘src) ‘), Tool $: path.resolve (__ DIRNAME,’ SRC / UTILS / TOOL.JS ‘) // Add $ at the end of a given object, to indicatePrecision match}, extensions: [‘.wasm’, ‘.mjs’, ‘.js’, ‘.json’, ‘.jsx’], modules: [path.resolve (__ DIRNAME, ‘SRC’), ‘Node_Modules’ ]}}
Top how to pack files, but we need one in development Local service, then we can use WebPack-Dev-Server
to open a simple static service locally for development.

WebPack-Dev-Server is a tool provided by WebPack that quickly launches a static service based on the current WebPack build configuration. When


is development , the function of Hot reload is provided, that is, when the source code file changes, the current page is updated so that you can see the latest Effect. … NPM Install WebPack-Dev-Server -d

 Add  Scripts in Package.json 
“START”: “WebPack-Dev-Server –Mode Development”

The default opens a local service Window http: // localhost: 8080 / Easy to develop

Configuring development server

We can be
WebPack-DEV-Server Do targeted configuration
module.exports = {// Configuration Development Server DevServer: {Port: 1234, Open: true, // Automatic Open the browser compress: true // server compression // … proxy, hot}}

ContentBase: The root directory of the server accesses (available for access static) Resources

Open: Automatically open browser Hot module replacement

Module Heat Replacement (
HMR – Hot Module Replacement ) feature replaced, add, or delete modules during the application run without reloading the entire page. Mainly in the following ways to significantly speed up the development speed:
   The application status that is lost when the page is fully reloaded. 
Update the change content to save valuable development time.

Adjustment style is more fast – almost equivalent to changing the style in the browser debugger. Here we

npm start

modified a file, the page will be refreshed once. This is a big problem. For example, we use REDUX ,


and other plug-ins, the page is stored in REDUX , Vuex The things will be lost, which is very disadvantageous for our development. HMR with WebPack-Dev-Server, firstFirst we configure WebPack.Config.js

Module.exports = {DevServer: {// … Hot: true} , Plugins: [New WebPack.hotmoduleReplacementPlugin () // …]}
  It is not possible after configuration, because WebPack still doesn't know where you want to update, modify  SRC / INDEX.JS 
file, add

{module.hot.accept ()}
After the service, NPM START
, the modification introduced


file, the page will not refresh, this is the HMR

But there is a problem that you modify the CSS / LESS and other patterns have not changed, what?

HMR modified style sheet needs to be used with

style-loader , and we It used to use minicssextractplugin.loader

, this is also good, modify one of Rules, we can try to change
   Module.Exports = {Module: {Rules: [{Test: /\.LESS$/, use: [// minicssextractplugin.Loader, 'Style-loadEr ',' CSS-Loader ', {Loader:' Postcss-loader ', options: {plugins: [Require (' autoprefixer ')] // Add CSS browser prefix}},' less-loader ']} ]}} 
So we will find that the HMR has been implemented.
  • In fact, we can find that the loader configured under DEV is
  • style-loader
  • , while the production environment is needed
  • minicssextractplugin.Loader
This involves the configuration between different environments. Can be obtained by

process.env.node_env is currently the development environment or a production environment, then configuring different loaders, this is not expanded here. The next article is intended to be a configuration of the development environment with the configuration environment of the development environment to different files in the configuration of React-CLI


Vue-CLI .

  • The knowledge mentioned above is some of WebPack’s foundation, more information can be queried with WebPack Chinese official website, the official website is more detailed, I Here is the most common configuration, and it is also an article of entry series. There are still many places involved in the text, such as optimizing the construction speed of WebPack, reduce the volume of the package.
  • WEBPACK 4.0
  • There is also a need to practice, more, the author is also the configuration of Webpack, and if you ask you.
Next article intends to configure a scaffolding from zero to deepen your understanding of WebPack.

The code generated herein: WebPack-dev The above is the full content of this article, I hope to help everyone, I hope everyone will support Tumi Cloud.

© Copyright Notice
Just support it if you like
comment Grab the couch

Please log in to comment