Home > Web Front-end > JS Tutorial > body text

New features of webpack 4.0.0-beta.0 version (detailed tutorial)

亚连
Release: 2018-06-06 14:06:29
Original
1624 people have browsed it

This article mainly introduces the new features of webpack 4.0.0-beta.0 version. Now I share it with you and give you a reference.

Front-end technology has mushroomed in recent years, and we are constantly learning and growing under this trend. The continuous development of front-end technology has provided us with many conveniences. For example: the emergence of JSX provides us with a clear and intuitive way to describe component trees, the emergence of LESS/SASS improves our ability to write CSS, and the emergence of AMD/CommonJS/ES6 facilitates our modular development. However, we need to use other tools to convert these tools into native languages ​​​​to run on the browser. In order to better integrate these different resources, we need a packaging tool, and webpack is the product of this demand.
Webpack can be regarded as a module packager. What it does is: analyze your project structure, find JavaScript modules and other extension languages ​​​​that browsers cannot run directly (Scss, TypeScript, etc.), and package them into a suitable format for browser use. Currently, webpack has released a total of three stable versions. Starting from the end of August 2017, after a five-month development cycle, the webpack team recently released the beta version of webpack 4.0.0 by adding a large number of new features, bug fixes, and problem improvements. If you are interested in webpack, let's learn about the new features of webpack 4.0.0-beta.0.
P.S. All code demonstration codes below are based on webpack 4.0.0-beta.0.

1. Install webpack v4.0.0-beta.0

If you use yarn:

yarn add webpack@next webpack-cli --dev
Copy after login

If you use npm:

npm install webpack@next webpack-cli --save-dev
Copy after login

2, webpack 4.0.0.beta.0 new features introduction

Here are some new features that you will definitely be interested in characteristic. If you still feel unsatisfied after reading this chapter, you can view the complete changelog here.

This chapter will introduce webpack 4.0.0-beta.0 from the following parts.

2.1 Environment

Webpack running environment upgrade. Node.js 4 version is no longer supported. Source code upgraded to a higher ECMAScript version.

According to the webpack package.json configuration, the minimum supported version of Node.js is displayed: "node": ">=6.11.5"

2.2 Module

Webpack module type and .mjs support:

For a long time, JS has been the only module type in webapck. Because of this, developers cannot efficiently package other types of files. Currently, webpack implements five module types, each of which has its own advantages and can be used as needed (will be explained in detail later).

  1. javascript/auto: (default in webpack3) supports all JS module systems: CommonJS, AMD, ESM.

  2. javascript/esm: EcmaScript module, all other module systems are unavailable (default in .mjs files).

  3. javascript/dynamic: CommonJS and EcmaScript modules are not supported.

  4. json: JSON data, which can be imported through require and import (default for .json files).

  5. webassembly/experimental: WebAssembly mode (currently in the experimental stage, default for .wasm files).

Usage:

type in module.rules is a newly added attribute used to support different module types.

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

In addition, webpack now parses extensions in the order of .wasm, .mjs, .js, and .json.

javascript/esm is more strict in handling ESM than javascript/auto:
This is reflected in two aspects: 1. The imported name must exist in the imported module. 2. Dynamic modules (non-ESM, such as CommonJS) can only be imported through the default import. All other imports (including namespace imports) will report an error.

2.3 Usage

You must select a mode in "Development or Production" (there is a hidden mode none, which can disable all functions).

1) Production mode does not support monitoring, and development mode is optimized for fast incremental reconstruction.
2) Production mode also supports module concatenation, that is, variable promotion (this feature has been implemented in webpack 3).
3) Supports comments and prompts in development mode, and supports eval's source map.

Move the CLI into webpack-cli. You need to install webpack-cli to use the CLI.

You can configure your own custom mode using optimization.* flags.

webpackInclude and webpackExclude can support import() through magic annotations, which allow filtering files when using dynamic expressions.
Using System.import() will issue a warning:

1) You can use Rule.parser.system:true to turn off the warning.
2) You can also use Rule.parser.system:false to turn off System.import().

For plugins migrated to the new plugin system ProgressPlugin now displays the plugin name.

webpack can now handle JSON natively. If you use loader to convert json to js, ​​you need to set: type: "javascript/auto". Of course, webpack can still work normally without loader.

2.4 Configuration

Deleted some common built-in plug-ins:

1) NoEmitOnErrorsPlugin -> optimization.noEmitOnErrors (default in production mode).
2) ModuleConcatenationPlugin -> optimization.concatenateModules (default in production mode).
3) NamedModulesPlugin -> optimization.namedModules (default in development mode).

Removed the commonly used CommonsChunkPlugin -> optimization.splitChunks For those who need fine-grained control over caching strategies, optimization.splitChunks and optimization.runtimeChunks can be used. Resolution can now be configured using module.rules[].resolve. It is merged with the global configuration.

optimization.minimize is used to control the switch of minimizing. The default is on for production mode and off for development mode.

optimization.minimizer is used to configure minimizers and options.

Many configuration options that support placeholders now also support functional form.

Incorrect options.dependencies configuration will now throw an exception.

sideEffects can be overridden through module.rules.

Add output.globalObject configuration option to allow selection of global object references at runtime.

There is no need to explicitly set the entry and output attributes. Webpack sets the entry attribute to ./src and the output attribute to ./dist by default.

Remove module.loaders.

2.5 Optimization

uglifyjs-webpack-plugin has been upgraded to v 1 and supports ES6 syntax.

sideEffects:false can be configured in package.json. When this field is set, the flag has no side effects in the library used. This means webpack can safely clean out any re-exports from your code.

Use JSONP array instead of JSONP function –> Asynchronous support.

Introduced new optimization.splitChunks option.

Webpack can delete useless code. Previously, Uglify deleted useless code. Now webpack can also delete useless code. This effectively prevents crashes that occur after importing useless code.

The following are some internal optimizations:
1) Replace plugin calls with tap calls (new plugin system).
2) Migrate many deprecated plugins to the new plugin system API.
3) Add buildMeta.exportsType:default for the json module.
4) Removed unused methods in Parser (parserStringArray, parserCalculatedStringArray).

2.6 Performance

By default, UglifyJS defaults to caching and parallelization (caching and parallelization are not fully implemented, a milestone for webpack5).

A new version of the plug-in system has been released, so event hooks and handlers have become single.

Multiple performance improvements, especially faster incremental rebuilds.

Improved the performance of RemoveParentModluesPlugin.

2.7 Incompatible changes (plug-in, loader related)

New plug-in system:

1) The plug-in method is backward compatible
2) The plugin should now use Compiler.hooks.xxx.tap(, fn)

Chunk.chunks/parents/blocks is no longer an array. Uses a collection internally and has methods to access it.

Parser.scope.renames and Parser.scope.definitions are no longer objects/arrays, but Map/Sets.

The parser uses StackedSetMap (a data structure similar to LevelDB) instead of arrays.

Compiler.options are no longer set when applying plugins.

The construction parameters of all modules have changed.

Merge options into the options object of ContextModule and resolveDependencies.

Change and rename the dependencies of import()

Move Compiler.resolvers into a Compiler accessible through the plugin .resolverFactory.

Dependency.isEqualResource has been replaced by Dependency.getResourceIdentifier

Template methods are all static.

A new RuntimeTemplate class has been added, and outputOptions and requestShortener have been moved to this class.

1) Many methods have been updated to replace the use of RuntimeTemplate.
2) We plan to move the code that accesses the runtime into this new class

Module.meta has been replaced by Module.buildMeta

Module.buildInfo and Module.factoryMeta have been added

Some properties of the Module have been moved to the new object

Add loaderContext.rootContext pointing to the context option. Loaders can use this to create things relative to the application root.

When HMR is enabled, add the this.hot flag to the loader context.

buildMeta.harmony has been replaced with buildMeta.exportsType: namespace.

The chunk graph has changed:

Before: Chunks were joined with nested dependencies.
Now: The connection of ChunksGroups is related to the reference dependency, and is concatenated in order.
Before: AsyncDependenciesBlocks reference a list of Chunks in order.
Now: AsyncDependenciesBlocks reference a ChunkGroup.

★★ Note: The above contents are all about major changes in loaders and plugins.

3. Detailed explanation of key updates

3.1 Better default values

直到今日,webpack 总是要求显式地设置 entry 和 output 属性。webpack 4.0.0-beta.0 中,webpack 会自动设定你的 entry 属性为 ./src 以及 output 的属性为 ./dist。
这意味着您不再需要配置文件来启动 webpack。接下来我们为你演示webpack 4.0.0-beta.0的便捷操作:

1、我们需要安装好 webpack 之后,在 package.json 中添加如下脚本即可启动:

 "scripts": {
  "build": "webpack"
 },
Copy after login

2、在工程中添加简单示例代码如下图(整个工程没有 webpack 配置文件,即可运行打包):

3、打包过程中我们发现有新特性的提示:

WARNING in configuration
The 'mode' option has not been set. Set 'mode' option to 'development' or 'production' to enable defaults for this environment.

这就是我们下节要说的内容模式设置。

★★ 注意:入口默认为 ./src 如果缺少此文件夹会报错!

> webpack --mode production
ERROR in Entry module not found: Error: Can't resolve './src' in 'D:\workspace\github\Webpack-Example'

3.2 模式设置

以往的项目使用 webpack3 脚手架生成项目初始模板都会有两个甚至三个配置文件,比如
webpack.base.conf.js、webpack.prod.conf.js、webpack.dev.conf.js 而现在可以做到一个配置文件都不需要,直接在启动命令中传入参数 --mode development | production 达到区分不同模式的效果。

接下来修改 package.json 设置不同的模式:

 "scripts": {
   "dev": "webpack --mode development",
   "build": "webpack --mode production"
 },
Copy after login

重新执行 npm run dev 或 npm run build 即可看到不同的打包结果:

我们可以看到两种模式的结果完全不同,下面我们会更深入的按照我们真实的需求来讲解一些常用配置。

接下来这个配置是最常用到的,我们使用 webpack 的主要目的之一就是为了更好的支撑前段模块化的能力,既然需要模块化当然少不了代码分割,目前代码分割有以下几种:

  1. 通过 entry 分割不同入口,常用于多页应用;

  2. 通过 CommonsChunkPlugin 插件来分割不同功能模块;

  3. 通过动态 import 来分割。

下面我们主要讲解 webpack 4.0.0-beta.0 版本的重大变化删除了 CommonsChunkPlugin 插件。

3.3 删除 CommonsChunkPlugin

webpack 4.0.0-beta.0删除了 CommonsChunkPlugin,以支持两个新的选项(optimization.splitChunks 和 optimization.runtimeChunk)。

从webpack 4.0.0-beta.0 开始分割 Chunk 将不在使用 CommonsChunkPlugin 插件,而是使用 optimization 配置项,具体的实现原理可以参考 CommonsChunkPlugin。

由于还没有正式官方文档出来,以下是我们通过实践出的 optimization 配置方法:
其中用到了新增的 splitChunks 属性,此属性看字面意思就明白是分割代码块的选项,其下可配置项已在下面示例代码中列出(有兴趣的朋友可以自行实践):

entry: {
   vendor: ['lodash']
},
 
...
 
optimization: {
   splitChunks: {
   chunks: "initial", // 必须三选一: "initial" | "all"(默认就是all) | "async" 
   minSize: 0, // 最小尺寸,默认0
   minChunks: 1, // 最小 chunk ,默认1
   maxAsyncRequests: 1, // 最大异步请求数, 默认1
   maxInitialRequests : 1, // 最大初始化请求书,默认1
   name: function(){}, // 名称,此选项可接收 function
   cacheGroups:{ // 这里开始设置缓存的 chunks
     priority: 0, // 缓存组优先级
     vendor: { // key 为entry中定义的 入口名称
       chunks: "initial", // 必须三选一: "initial" | "all" | "async"(默认就是异步) 
       test: /react|lodash/, // 正则规则验证,如果符合就提取 chunk
       name: "vendor", // 要缓存的 分隔出来的 chunk 名称 
       minSize: 0,
       minChunks: 1,
       enforce: true,
       maxAsyncRequests: 1, // 最大异步请求数, 默认1
       maxInitialRequests : 1, // 最大初始化请求书,默认1
       reuseExistingChunk: true // 可设置是否重用该chunk(查看源码没有发现默认值)
     }
   }
 }
 },
Copy after login

以上就是 optimization.splitChunks 的所有可用的配置项属性。

总结

以上就是我们初步整理的关于 webpack 4.0.0-beta.0 的新特性,包含了一部分的官方更新日志的翻译,还有我们自己试验的一些属性。当然如果你有兴趣,也可以等到正式的官方文档发布之后进行实践。
如果上面的信息不能够完全满足你的兴趣,还请关注官方日志。在未来不到一个月的时间里,webpack 将对插件、加载器以及整个生态系统进行更加严格的测试,并发布最终的官方稳定版本。如果你喜欢 webpack,你可以参与使用 webpack 4.0.0-beta.0。测试阶段发现、解决的问题越多,正式版本才会更加稳定。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在angularjs数组中如何判断是否含有某个元素

在angular中如何使用json对象push到数组中的方法

在angularjs中如何实现table增加tr的方法

The above is the detailed content of New features of webpack 4.0.0-beta.0 version (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!