After The release of WebPack 3, the WebPack team promised the community a long and stable development cycle for subsequent iterations of the main version of WebPack. In August 2017, the WebPack team Released the Next branch from the Master branch for WebPack 4 development. After a five-month development cycle, WebPack 4.0-Beta was Released in January 2018. Not only does it deliver on its promise, but it also brings a lot of new features and improvements to the user experience.

The installation

If you want to use WebPack 4, you need to install it from the Next branch:

// yarn
yarn add webpack@next webpack-cli --dev

// npm 
npm install webpack@next webpack-cli --save-devCopy the code

Incomplete migration refers north

The environment

Node.js 4 is no longer supported.

Based on package.json configuration, the minimum supported version of Node.js is 6.11.5

Module type

Before WebPack 4, JS was the only module type in Webpack and therefore could not effectively package other types of files. Webpack 4 offers five module types:

  • javascript/auto: (default type in WebPack 3) Supports all JS module systems: CommonJS, AMD, ESM
  • javascript/esm: EcmaScript module, not available in other module systems (default).mjsFile)
  • javascript/dynamic: Supports only CommonJS & AMD, EcmaScript modules are not available
  • json: byrequireimportThe imported DATA is in JSON format (default.jsonThe file)
  • webassembly/experimental: WebAssembly module (experimental, defaults to.wasmThe file)

Additionally, webPack 4 will parse.wasm,.mjs,.js, and.json files by default.

In the loader configuration of the corresponding file, the type field should be added to specify the module type:

 module: {
    rules: [{
        test: /\.special\.json$/,
        type: "javascript/auto",
        use: "special-loader"
    }]
 }Copy the code

Javascript/Auto/javascript/ ESM can handle ESM, but the latter is more stringent:

  • The import name must exist in the imported module
  • Dynamic modules (non-ESM, such as CommonJS) can only pass by defaultimportImport, other methods (including namespace) import will report an error

For the WebAssembly module:

  • Other modules can be imported (JS and WASM)
  • Attempting to import a nonexistent module into a WASM module will result in a warning or error
  • ESM can import module names exported from WASM modules
  • Only available in Async Chunks (throughimport()Used in imported modules), invalid in Initial chunks (not conducive to improving web application performance)

import()Dynamic import

In WebPack 4, import() returns an object with a namespace, which doesn’t affect ES Modules, but adds a layer for modules that follow the CommonJS specification:

// webpack 2/3
import("./commonjs").then(exports => {
    ...
})

// webpack 4
import("./commonjs").then({default: exports}=> {
    ...
})Copy the code

modeMode configuration

Mode is a new parameter added to WebPack 4 and has two optional values: Production and development. Mode cannot be default. You can select either of the following:

  1. productionMode:
    • All possible optimizations, such as code compression/scope enhancement, are provided by default
    • Does not supportwatching
    • process.env.NODE_ENVYou do not need to define the value ofproduction
   /** webpack.production.config.js **/
   // webpack 2/3 
   module.exports = {
       plugins: [
        new UglifyJsPlugin(/* ... */),
        new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("production") }),
        new webpack.optimize.ModuleConcatenationPlugin(),
        new webpack.NoEmitOnErrorsPlugin()
       ]
     }
     
   // webpack 4  
   module.exports = {
    mode: 'production'
   }Copy the code
  1. developmentMode:
    • Optimized for incremental build speed and development experience
    • process.env.NODE_ENVYou do not need to define the value ofdevelopment
    • Support for comments and hints in development mode, and support for Source Maps under Eval
   /** webpack.development.config.js **/
   // webpack 2/3 
   module.exports = {
       plugins: [
        new webpack.NamedModulesPlugin(),
        new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("development") })
       ]
     }
     
   // webpack 4  
   module.exports = {
    mode: 'development'
   }Copy the code

In addition, WebPack 4 provides a hidden (None) mode in which all optimizations are disabled

SideEffects set

Webpack 4 introduces support for sideEffects: False in package.json. When this field is added to a module’s package.json, it indicates that the module has no side effects, which means that WebPack can safely clean up the code used for re-exports.

JSON

Webpack 4 supports not only native JSON processing, but also Tree Shaking for JSON. When using the ESM syntax import JSON, WebPack eliminates unused exports from the JSON Module.

In addition, if you want to convert JSON to JS with loader, you need to set type to javascript/auto:

module.rules: [
    {
      test: /\.special\.json$/,
      type: "javascript/auto",
      use: "special-loader"
    }
]Copy the code

configuration

  • Removed some common built-in plugins:
    • NoEmitOnErrorsPlugin – > optimization. NoEmitOnErrors (production mode by default)
    • ModuleConcatenationPlugin – > optimization. ConcatenateModules (production mode by default)
    • NamedModulesPlugin – > optimization. NamedModules (development mode by default).
    • Deleted CommonsChunkPlugin, instead, the optimization splitChunks and optimization runtimeChunk, this provides fine-grained caching policy control
  • You can usemodule.rules[].resolveTo configure the resolution, which is merged with the global configuration.
  • optimization.minimizeA switch for controlling the variable. The default value is on in production mode and off in development mode.
  • optimization.minimizerUse for configuring minimizers and options.
  • A number of configuration options that support placeholders now support a functional form
  • The wrongoptions.dependenciesThe configuration will report an error
  • sideEffectsCan be achieved bymodule.rulescover
  • output.hashFunctionCan be a constructor for custom hash functions. Unencrypted hash functions can also be provided for performance reasons
  • output.globalObjectGlobal object references can be configured at run time
  • The default configuration
    • Webpack defaults to follow.wasm..mjs..js.jsonThe extension of the sequence to find modules.
    • output.pathinfoIt is turned on by default in development mode
    • In the production environment, memory caching is disabled by default
    • entryThe default value for./src.output.pathThe default value for./dist
    • When selecting the mode option, the default isproduction

To optimize the

  • uglifyjs-webpack-pluginRelease V1 to support ES2015
  • Use JSONP arrays instead of JSONP functions – > asynchronous support
  • Webpack itself can also remove useless code. In Webpack 2/3, useless code is removed when Uglify is used. In WebPack 4, webpack can also (in some cases) remove useless code to avoidimport()Crashes caused when useless code is referenced
  • The scoped module will generate less code

performance

  • By default, UglifyJS will cache and parallelize by default (fully implemented caching and parallelization will be implemented in WebPack 5)
  • Multiple performance improvements, especially in incremental builds
  • To improve theRemoveParentModluesPluginThe performance of the
  • Unused modules no longer have unnecessary scope promotion
  • Add the ProfilingPlugin, which creates a file (in Chrome) containing the time consumed by each plugin
  • for ofInstead offorEach;Map/SetInstead ofObjects;includesInstead ofindexOf
  • The same task will be queued only once

A complete list of performance improvements and optimizations can be found in Release 4.0-beta.0

Removed features

  • removedmodule.loaders
  • removedloaderContext.options
  • removedCompilation.notCacheable
  • removedNoErrorsPlugin
  • removedDependency.isEqualResource
  • removedNewWatchingPlugin
  • removedCommonsChunkPlugin

The related resources

  • Webpack 4 Beta — Try it Today!
  • webpack 4-beta.0
  • Official migration draft
  • webpack 4: mode and optimization