都是我从官方文档里拼本身理解翻译过来的,借助翻译工具应该大概解析出来,可是能力强的仍是建议直接查看文档,毕竟我也不强,怕误导意思javascript
changelog-v5css
这一发布集中在如下方面:html
=> see here for a migration guide <=前端
全部在v4中被废弃的功能都被移除。java
迁移: 确保你的webpack4项目没有打印弃用警告node
这也有一些被废弃可是在v4中没有打印警告的东西react
新的废弃包括一个依赖代码以便于他们更容易被引用webpack
require.include
已经被废弃,当使用的时候会默认发出警告git
可使用Rule.parser.requireInclude
去改变行为: 容许, 废弃或者禁止github
在早期的时候,webpack的目标是容许大多数的nodejs模块在浏览器中运行,可是随着模块格局的改变,如今许多的模块使用都是为了前端的目的而编写,v<=4为许多的nodejs核心模块提供填充,一旦一个模块使用了任何的核心模块就会自动应用这些填充(i.e. the crypto
module).
虽然这使使用为nodejs而编写的模块变得更简单,可是它添加了巨大的填充到bundle中,但大多数状况下它们并非必要的
v5中止自动填充这些模块而专一于前端兼容模块
迁移:
browser
字段让包兼容,为浏览器提供替代的实现/依赖关系新增新的算法去实现长期缓存.这在生产环境被默认启用
chunkIds: "deterministic", moduleIds: "deterministic", mangleExports: "deterministic"
这算法以肯定的方式将短(3或4字节)数字IDs分配给模块和快,短(2字节)名称分配给导出,这是在块体积和长期缓存之间的权衡.
moduleIds/chunkIds/mangleExports: false
禁止默认行为,能够经过插件提供自定义算法。.注意在v4中moduleIds/chunkIds: false
没有自定义插件进行工做构建,而在v5你必须提供一种
迁移: 最好是使用chunkIds
, moduleIds
andmangleExports
,你也能够选择性使用旧的默认值: chunkIds: "size", moduleIds: "size", mangleExports: "size"
,这会生成更小的块,可是更常让长期缓存失效
注意: 在v4哈希模块id下降了gzip的性能,这与更改的模块命令有关,已经被修复了
注意: 在v5deterministic
id在生产环境默认被启用
v5如今当使用[contenthash]
会使用文件内容的真正散列,在此以前只是使用内部结构的散列,这只有在注释改变或者变量重命名才会对长期缓存产生积极影响.而这些更改在压缩以后是不可见的
开发模式中默认启用的新命名块id算法为块(和文件名)提供可读的名称。模块ID是由其相对于上下文的路径决定的。块ID由块的内容决定。
这样你就不用再用import(/* webpackChunkName: "name" */ "module")
去调试,可是,若是您但愿为生产环境控制文件名,那么它仍然是有意义的。
在生产环境中可使用 chunkIds:“named”
,但要确保不要意外地暴露有关模块名称的敏感信息。
迁移:若是您不喜欢在开发中更改文件名,您能够经过 chunkIds: "natural"
来使用旧的数字模式。
Webpack 5增长了一个名为“模块联合”的新特性,它容许多个Webpack构建版本一块儿工做。从运行时的角度来看,造成多个构建的模块就像一个巨大的链接模块图。从开发人员的指望模块能够从指定的远程构建导入和使用最小的限制。
For more details see this separate guide.
JSON模块如今与规范一致,若是使用了非默认导出会发出警告.JSON模块从严格的EcmaScript模块导入的时候再也不有命名导出
迁移: 使用默认导出
优化optimization.usedExports
删除未使用的属性,优化optimization.mangleExports
没有逻辑的属性
能够在Rule.parser.parse
指定自定义的JSON序列化去引入类JSON文件(例如toml、yaml、json5等)。
v5如今原生支持资源模块,这些模块要么将文件发送到输出文件夹中,要么将DataUri注入到javascript包中。不管哪一种方式,它们都提供一个URL来使用。
它们可以经由多种方式使用
import url from "./image.png"
,当匹配这些引入的时候须要在module.rules
设置type: "asset"
new URL("./image.png", import.meta.url)
所选择的语法也容许在不使用bundler的状况下运行代码。
import.meta.webpackHot
是 module.hot
的别名,能够在严格模式下执行import.meta.webpack
是webpack的主版本号import.meta.url
是当前文件的 file:
url (相似 __filename
不过是做为文件路径)当将资源的新URL与 new Worker
/new SharedWorker
/navigator.serviceWorker.register
组合时。webpack将自动为web worker建立一个新的入口点。
new Worker(new URL("./worker.js", import.meta.url))
所选择的语法也容许在不使用bundler的状况下运行代码。
Webpack 5支持处理请求中的协议。
data:
支持Base64或者被支持的原始编码. 在module.rules
Mimetype能够被映射到加载器和模块类型 . 例如: import x from "data:text/javascript,export default 42"
file:
支持http(s):
支持, 但须要选择经过 new webpack.experiments.schemesHttp(s)UriPlugin()
支持请求中的片断:例如: ./file.js#fragment
v5支持所谓的"异步模块", 这些模块不是同步计算的,而是异步和基于promise的
经由import
引入它们会被自动处理不须要额外的语法,并且几乎不存在明显的差别
经由require引入它们会返回promise导出解析
在webpack有多种使用异步模块的方式
Webpack 5增长了额外的external类型以涵盖更多的应用程序:
promise
: 一种表达结果的承诺, 外部模块是一个异步模块,解析后的值用做模块导出。
import
: 原生import
使用作加载指定的请求,而external模块是一种异步模块
script
: 经由<script>
加载一个url得到全局的导出变量(可选属性), external模块是一种异步模块
package.json中的 exports
和import
字段如今支持。
Yarn PnP is supported natively.
See more details in TODO.
Webpack 5容许传递目标列表,也支持目标的版本。
例如: target: "node14"
target: ["web", "es2020"]
这是一个提供webpack须要肯定的全部信息的简单方法:
测试数据格式已经改进可读性和冗长性,默认值已经获得了改进,变得更简洁,也更适合大型构建。
stats.chunkRelations
切换.files
和auxiliaryFiles
.stats.ids
切换.stats.modulesSort
切换..stats.chunkModulesSort
切换.stats.nestedModulesSort
切换.stats.hash
切换.stats.builtAt
启用. 它将在摘要中显示时间戳。stats.children
.CLI --progress
使用的`ProgressPlugin
已经作了一些改进,但也能够做为插件手动使用。
它过去只计算处理过的模块。如今它能够计算 entries
dependencies
and modules
。全部这些如今都默认显示。
它用于显示当前处理的模块。这致使了不少标准错误输出,并在一些控制台上产生了性能问题。如今默认状况下禁用(activeModules选项)。这也减小了垃圾信息的数量在控制台。如今,在构建模块期间写入标准错误的时间被限制为500ms。
分析模式也获得了升级,并将显示嵌套进度消息的时间。这使得插件形成性能问题时更容易发现。
一种新的添加选项percentBy
告诉ProgressPlugin
怎么计算进度比
new webpack.ProgressPlugin({ percentBy: "entries" });
为了使进度百分比更准确,ProgressPlugin缓存最后已知的模块总数,并在下一次构建中重用这个值。第一个版本将预热缓存,但接下来的版本将使用并更新这个值。
在webpack 4中,多个webpack运行时可能在同一个页面上发生冲突,由于它们使用相同的全局变量来加载块。要解决这个问题,须要为输出提供一个自定义名称output.jsonpFunction
配置。
Webpack 5会自动从package.json
name
推断出构建的惟一名称。并将其做为output.uniqueName
的默认值。
此值用于使全部潜在冲突的全局变量惟一。
迁移:考虑删除output.jsonpFunction
容许的状况下v5会自动决定output.publicPath
v5会从源码生成Typescript typings经过npm包暴露
迁移:删除@types/webpack
。当名称不一样时更新引用。
webpack如今可以跟踪访问导出的嵌套属性的访问。这能够在从新导出名称空间对象时改进tree-shaking(消除未使用和混乱的导出)。
// inner.js export const a = 1; export const b = 2; // module.js import * as inner from "./inner"; export { inner } // user.js import * as module from "./module"; console.log(module.inner.a);
在本例中,能够在生产模式中删除导出b。
webpack 4没有分析模块导出和导入之间的依赖关系。webpack 5有一个新的选项优化optimization.innerGraph
在生产模式中默认启用,它对模块中的符号运行分析,以找出从导出到导入的依赖关系。
像这种模块
import { something } from "./something"; function usingSomething() { return something; } export function test() { return usingSomething(); }
内部图算法将计算出只有在使用测试导出时才使用某些内容,这能够标记更多未使用的导出而且从块中删除
当设置sideEffects": false
会删除更多的模块,在这例子./something
当测试模块未使用会被删除
须要配置optimization.unusedExports
去得到更多关于未使用导出的信息
下面的符号会被分析
export default
/*#__PURE__*/
expressions反馈:若是你发如今这个分析中有什么缺失,请报告一个问题,咱们考虑增长它。
使用eval()将对模块进行此优化,由于evaled代码能够引用范围内的任何符号。
这种优化也称为深度范围分析。
webpack在分析CommonJs导出和require()调用时,能够选择不参加导出。
webpack 5增长了对一些CommonJs构造的支持,容许消除未使用的CommonJs导出,并从require()调用中跟踪引用的导出名称。
持如下构造:
exports|this|module.exports.xxx = ...
exports|this|module.exports = require("...")
(reexport)exports|this|module.exports.xxx = require("...").xxx
(reexport)Object.defineProperty(exports|this|module.exports, "xxx", ...)
require("abc").xxx
require("abc").xxx()
require()
a ESMflagged exportType (special handling for non-strict ESM import):
Object.defineProperty(exports|this|module.exports, "__esModule", { value: true|!0 })
exports|this|module.exports.__esModule = true|!0
当检测到不可分析的代码时,webpack会自动退出,而且彻底不跟踪这些模块的导出信息(出于性能缘由)。
Webpack 5如今可以(在默认状况下)分析和优化每一个运行时模块(一个运行时一般等于一个入口点)。这容许仅在真正须要导出的入口点中导出。入口点不会相互影响(只要每一个入口点使用运行时)
模块链接也适用于每一个运行时,以容许对每一个运行时进行不一样的链接。
模块链接已经成为第一类公民,任何模块和依赖项如今均可以实现它。最初webpack 5已经增长了对外部模块和json模块的支持,很快就会推出更多。
export *
已经改良到跟踪更多的信息而且再也不标记 default
导出使用
export *
当webpack检测到冲突导出的时候展现警告
import()
容许经由神奇的注释/* webpackExports: ["abc", "default"] */
手动tree shake模块
咱们试图经过改进两种模式之间的类似性,在开发模式下的构建性能和避免仅用于生产的问题之间找到一个好的折衷。
Webpack 5在这两种模式下都默认启用了sideEffects
优化。在webpack 4中,因为package.json中不正确的“反作用”标志,这种优化致使了一些仅用于生产的错误。在开发中启用这种优化能够更快更容易地找到这些问题。
在许多状况下,开发和生产发生在不一样的操做系统上,文件系统的大小写敏感性也不一样,因此webpack 5在出现奇怪的大小写问题时增长了一些警告/错误。
如今在输出中有一些选项。如今的环境。它们容许指定哪一个EcmaScript特性能够用于webpack生成的运行时代码。
一般不直接指定该选项,而是使用target选项。
webpack 4过去只发出ES5代码。webpack 5如今能够同时生成ES5和ES6/ES2015代码。
只支持现代浏览器将使用箭头函数生成更短的代码,使用const声明生成更多的spec-comform代码,使用TDZ做为导出默认值。
target
option在webpack 4中,target
是在“web”和“node”(以及其余一些)之间作出很是粗糙的选择。Webpack 5提供了更多的选项。
目标选项如今对生成代码的影响比之前更多:
externals
global, __filename, __dirname
)browser
field, exports
and imports
条件)在web
和node
之间作出对于这些事情的选择很是粗糙,咱们须要更多信息.所以,咱们容许指定最小版本,例如“node10.13”,并推断有关目标环境的更多属性。
如今容许使用一个数组合并多个target.webpack会决定全部target的最低属性配置,当使用不提供完整信息的目标(如“web”或“节点”(没有版本号))时,使用数组也颇有用。例如["web", "es2020"]
结合这两个部分目标。
有一个目标“browserslist”,它将使用browserslist数据来肯定环境的属性。当项目中有可用的browserslist配置时,默认也会使用此目标。当没有可用的配置时,“web”目标将被默认使用。
有些组合和特性还没有实现,将致使错误。它们是为未来的特性作准备。例子:
["web", "node"]
将致使一个通用的块加载方法,这是还没有实现["web", "node"]
+ output.module: true
将致使模块块加载方法,这是还没有实现"web"
将会致使 http(s):
导入被视为外部模块, 这是还没有实现 (应变方法: externalsPresets: { web: false, webAsync: true }
, 这会使用 import()
替代).模块如今以一种比显示单个数字更好的方式表示大小。此外,如今有不一样类型的尺寸。
SplitChunksPlugin如今知道怎么用minSize
和maxSize
去处理那些不一样尺寸,默认只有Javascript
尺寸会被处理,不过你能够用多个值去管理他们
minSize: { javascript: 30000, style: 50000, }
迁移:检查构建中使用的大小类型,并在splitChunks中配置它们。minSize
和splitChunks.maxSize
可选。
这是一种文件系统缓存,能够选择性的再如下配置使用
cache: { // 1. Set cache type to filesystem type: "filesystem", buildDependencies: { // 2. Add your config as buildDependency to get cache invalidation on config change config: [__filename] // 3. If you have other things the build depends on you can add them here // Note that webpack, loaders and all modules referenced from your config are automatically added } }
重要提示:
默认状况下,webpack假设只有包管理器修改了webpack所在的node_modules
目录。node_modules
跳过了散列和时间戳。相反,出于性能缘由,只使用包名和版本,符号连接(如npm/yarn link)是好的。不要直接编辑node_modules
中的文件,除非您选择不使用snapshot.immutablePaths: []
进行此优化。当使用Yarn PnP webpack假设yarn缓存是不可变的(它一般是)。您可使用snapshot.immutablePaths: []
选择退出此优化。
缓存将存储在node_modules/.cache/webpack
(当使用node_modules时)resp. .yarn/.cache/webpack
(当使用Yarn PnP时)。你可能永远都不须要手动删除它。
许多内部插件也会使用持久缓存。示例:SourceMapDevToolPlugin
(缓存生成的SourceMap), ProgressPlugin
(缓存大量模块)
持久缓存将根据使用状况自动建立多个缓存文件,以优化对缓存的读写访问。
Compiler如今须要在使用完以后关闭,Compiler在进入和离开idle的时候有针对它们状态的钩子,插件可能用这些钩子去作不重要的工做(例如, 把持久缓存慢慢地存储到硬盘). 在Compiler关闭以后 - 全部剩下的工做会被尽量快的完成,一个回调信号表示结束.
插件和它们各自的做者应该预料到一些使用者可能会忘记去关闭Compiler,因此,全部工做最终应该都在idle阶段完成.当工做完成的时候应该阻止进程退出.
webpack()
在被传递回调时自动调用 close
。
迁移:在使用node.js API时,确保调用Compiler.close
后关闭。
webpack一般会在第一次构建期间emit全部的输出文件而在后面的增量构建(监听)会跳过写入没改变的文件,假定webpack运行期间没有其余东西改变输出文件
随着持久缓存的增长,即便在重启webpack进程时,也应该提供watch-like的体验,可是,若是认为即便在webpack不运行的状况下,也没有其余东西改变输出目录,那就太过度了。
因此如今webpack如今会检测在输出目录的现有文件并将它们的内容与内存中的输出文件进行比较,只有当它们改变的时候才会写入文件,这只会在第一次构建完成,任何增量构建老是在webpack运行进程生成新的资源写入文件
咱们假定webpack和插件只有在内容发生改变才会生成新的资源,缓存应该确保当输入是相等的时候没有新的资源生成,不听从这个建议会下降性能
文件被标记immutable
(包括内容hash),当已存在相同名字的文件的时候将永远不会被写入,咱们假定当文件内容改变的时候内容hash会被改变,这一般是对的,但在webpack或者插件开发阶段不老是正确
在webpack 4中,一些特性是不可用的,例如Node.js目标。其中一些如今已经能够了。
因为没法加载多个初始文件,node.js不能在初始块中进行SplitChunks。如今是可能的。入口文件如今将加载附加文件和运行时chunk。
只容许启动单个文件的目标(如node、WebWorker、electron main)如今支持由运行时自动加载引导所需的依赖部分。
这容许使用 splitChunks
chunks: "all"
来处理这些目标”。
注意,因为块加载是异步的,这使得初始计算也异步。当使用output.library
会是一个问题,由于导出值如今是一个Promise, 因为alpha.14这不适用于target: "node"
, 由于chunk加载是同步
enhanced-resolve
更新到v5, 有下面提提高:
false
如今是可能的不包含JS代码的块,将再也不生成JS文件。
并非全部的特性都从一开始就是稳定的。在webpack 4中,咱们添加了一些实验性的特性,并在更新日志中指出这些特性还处于试验阶段,但从配置中并不老是能清楚地看出这些特性是否还处于试验阶段。
在webpack 5中有一个新的experiments
配置选项,它容许启用实验特性。这能够清楚地说明哪些选项是启用的/使用的。
虽然webpack遵循语义版本控制,但它会对实验性特性进行例外处理。在小型webpack版本中,实验性的特性可能包含破坏性的变化。当发生这种状况时,咱们将在更改日志中添加一个明确的说明。这将容许咱们更快地迭代实验特性,同时也容许咱们在主要版本上停留更长的时间以得到稳定的特性。
webpack 5将附带如下实验:
experiments.syncWebAssembly
)新的WebAssembly支持根据更新的规范( experiments.asyncWebAssembly
)
Top Level Await 阶段3草案 (experiments.topLevelAwait
)
await
将使模块成为异步模块Emitting bundle as module (experiments.outputModule
)
<script type="module">
延迟加载,并在模块模式下最小化注意,这也意味着默认状况下禁用WebAssembly支持。
最小支持的node.js版本从6增长到10.13.0(LTS)。
迁移:升级到可用的最新node.js版本。
entry: {}
allows an empty object now (to allow to use plugins to add entries)target
supports an array, versions and browserslistcache: Object
removed: Setting to a memory-cache object is no longer possiblecache.type
added: It's now possible to choose between "memory"
and "filesystem"
New configuration options for cache.type = "filesystem" added:
cache.cacheDirectory
cache.name
cache.version
cache.store
cache.hashAlgorithm
cache.idleTimeout
cache.idleTimeoutForIntialStore
cache.buildDependencies
snapshot.resolveBuildDependencies
addedsnapshot.resolve
addedsnapshot.module
addedsnapshot.managedPaths
addedsnapshot.immutablePaths
addedresolve.cache
added: Allows to disable/enable the safe resolve cacheresolve.concord
removedresolve.alias
values can be arrays or false
nowresolve.restrictions
added: Allows to restrict potential resolve resultsresolve.fallback
added: Allow to alias requests that failed to resolveresolve.preferRelative
added: Allows to resolve modules requests are relative requests tooAutomatic polyfills for native node.js modules were removed
node.Buffer
removednode.console
removednode.process
removednode.*
(node.js native module) removedresolve.alias
and ProvidePlugin
. Errors will give hints. (Refer to node-libs-browser for polyfills & mocks used in v4)output.filename
can now be a functionoutput.assetModuleFilename
addedoutput.jsonpScriptType
renamed to output.scriptType
devtool
is more strictfalse | eval | [inline-|hidden-|eval-][nosources-][cheap-[module-]]source-map
optimization.chunkIds: "deterministic"
addedoptimization.moduleIds: "deterministic"
addedoptimization.moduleIds: "hashed"
deprecatedoptimization.moduleIds: "total-size"
removedDeprecated flags for module and chunk ids were removed
optimization.hashedModuleIds
removedoptimization.namedChunks
removed (NamedChunksPlugin
too)optimization.namedModules
removed (NamedModulesPlugin
too)optimization.occurrenceOrder
removedchunkIds
and moduleIds
optimization.splitChunks test no longer matches chunk name
(module, { chunkGraph }) => chunkGraph.getModuleChunks(module).some(chunk => chunk.name === "name")
optimization.splitChunks
minRemainingSize
was addedoptimization.splitChunks
filename
can now be a functionoptimization.splitChunks
sizes can now be objects with a size per source typeminSize
minRemainingSize
maxSize
maxAsyncSize
maxInitialSize
optimization.splitChunks
maxAsyncSize
and maxInitialSize
added next to maxSize
: allows to specify different max sizes for initial and async chunksoptimization.splitChunks
name: true
removed: Automatic names are no longer supportedchunkIds: "named"
will give your files useful names for debuggingoptimization.splitChunks.cacheGroups[].idHint
added: Gives a hint how the named chunk id should be chosenoptimization.splitChunks
automaticNamePrefix
removedidHint
insteadoptimization.splitChunks
filename
is no longer restricted to initial chunksoptimization.splitChunks
usedExports
added to include used exports when comparing modulesoptimization.splitChunks.defaultSizeTypes
added: Specified the size types when using numbers for sizesoptimization.mangleExports
addedoptimization.minimizer
"..."
can be used to reference the defaultsoptimization.usedExports
"global"
value added to allow to disable the analysis per runtime and instead do it globally (better performance)optimization.noEmitOnErrors
renamed to optimization.emitOnErrors
and logic invertedoptimization.realContentHash
addedoutput.devtoolLineToLine
removedoutput.chunkFilename: Function
is now allowedoutput.hotUpdateChunkFilename: Function
is now forbidden: It never worked anyway.output.hotUpdateMainFilename: Function
is now forbidden: It never worked anyway.output.importFunctionName: string
specifies the name used as replacement for import()
to allow polyfilling for non-suppored environmentsoutput.charset
added: setting it to false omit the charset
property on script tagsoutput.hotUpdateFunction
renamed to output.hotUpdateGlobal
output.jsonpFunction
renamed to output.chunkLoadingGlobal
output.chunkCallbackFunction
renamed to output.chunkLoadingGlobal
output.chunkLoading
addedoutput.enabledChunkLoadingTypes
addedoutput.chunkFormat
addedmodule.rules
resolve
and parser
will merge in a different way (objects are deeply merged, array may include "..."
to reference to prev value)module.rules
parser.worker
added: Allows to configure the worker supportedmodule.rules
query
and loaders
were removedmodule.rules
options
passing a string is deprecatedmodule.rules
mimetype
added: allows to match a mimetype of a DataUrimodule.rules
descriptionData
added: allows to match a data from package.jsonmodule.defaultRules
"..."
can be used to reference the defaultsstats.chunkRootModules
added: Show root modules for chunksstats.orphanModules
added: Show modules which are not emittedstats.runtime
added: Show runtime modulesstats.chunkRelations
added: Show parent/children/sibling chunksstats.errorStack
added: Show webpack-internal stack trace of errorsstats.preset
added: select a presetstats.relatedAssets
added: show assets that are related to other assets (e. g. SourceMaps)stats.warningsFilter
deprecated in favor of ignoreWarnings
BannerPlugin.banner
signature changeddata.basename
removed
data.query
removedfilename
SourceMapDevToolPlugin
lineToLine
removed[hash]
as hash for the full compilation is now deprecated[fullhash]
instead or better use another hash option[modulehash]
is deprecated[hash]
instead [moduleid]
is deprecated[id]
instead [filebase]
removed[base]
insteadNew placeholders for file-based templates (i. e. SourceMapDevToolPlugin)
[name]
[base]
[path]
[ext]
externals
when passing a function, it has now a different signature ({ context, request }, callback)externalsPresets
addedexperiments
added (see Experiments section above)watchOptions.followSymlinks
addedwatchOptions.ignored
can now be a RegExpwebpack.util.serialization
is now exposed.target
is now "browserslist"
by default when a browserslist config is availablemodule.unsafeCache
is now only enabled for node_modules
by defaultoptimization.moduleIds
defaults to deterministic
in production mode, instead of size
optimization.chunkIds
defaults to deterministic
in production mode, instead of total-size
optimization.nodeEnv
defaults to false
in none
modeoptimization.splitChunks.minSize
defaults to 20k
in productionoptimization.splitChunks.enforceSizeThreshold
defaults to 50k
in productionoptimization.splitChunks
minRemainingSize
defaults to minSizeoptimization.splitChunks
maxAsyncRequests
and maxInitialRequests
defaults was been increased to 30optimization.splitChunks.cacheGroups.vendors
has be renamed to optimization.splitChunks.cacheGroups.defaultVendors
optimization.splitChunks.cacheGroups.defaultVendors.reuseExistingChunk
now defaults to true
resolve(Loader).cache
defaults to true
when cache
is usedresolve(Loader).cacheWithContext
defaults to false
resolveLoader.extensions
remove .json
node.global
node.__filename
and node.__dirname
defaults to false
in node-target
sstats.errorStack
defaults to false
this.getOptions
这个新的API应该简化加载器中选项的使用。它容许经过一个JSON模式进行验证。详情请参见https://github.com/webpack/we...
下面的变化只与插件做者相关:
webpack 5中的插件如今在缺省配置被应用以前就已经被应用了。这容许插件应用它们本身的默认值,或者充当配置预置。
但这也是一个破坏性的改变,由于插件在应用时不能依赖于配置值的设置。
迁移:仅在插件挂钩中访问配置。或者最好避免访问配置,并经过构造函数接受选项。
大部分运行时代码被转移到所谓的“runtime modules”中。这些特殊模块负责添加运行时代码.它们能够添加到任何块中,但当前老是添加到运行时块中。“Runtime Requirements”控制将哪些运行时模块(或核心运行时部分)添加到包中。这确保只有使用的运行时代码被添加到包中。未来,运行时模块还能够添加到按需加载块中,以便在须要时加载运行时代码
在大多数状况下,核心运行时容许内嵌入口模块,而不是用`__webpack_require__
调用它。若是包中没有其余模块,那么就不须要其余的__webpack_require__
了.这与模块链接很好地结合在一块儿,即将多个模块链接成单个模块。
在最好的状况下,根本不须要运行时代码。
迁移:若是你将运行时代码注入到webpack运行时的插件中,能够考虑使用RuntimeModules。
添加了一个序列化机制来容许webpack中复杂对象的序列化,它具备可选择的语义,所以应该被序列化的类须要显式地标记(并实现它们的序列化).对于大多数模块,全部依赖项和一些错误已经这样作了。
迁移:在使用自定义模块或依赖项时,建议将它们序列化,以便从持久缓存中获益
添加了带有插件接口的缓存类。这个类可用于对缓存进行读写。根据配置的不一样,不一样的插件能够向缓存添加功能。
MemoryCachePlugin
添加内存缓存,FileCachePlugin
添加持久(文件系统)缓存
FileCachePlugin
使用序列化机制来向/从磁盘中持久化和恢复缓存项
带有钩子的类会冻结它们的钩子对象,所以再也不可能以这种方式添加自定义钩子。
迁移:推荐的添加自定义钩子的方法是使用WeakMap和静态 getXXXHooks(XXX)
(即 getCompilationHook(compile)
)方法。内部类使用与自定义钩子相同的机制。
webpack 3插件的兼容层已经被删除。它已经被webpack 4弃用了
一些较少使用的tapable api被删除或弃用。
迁移:使用新的tapable API。
在密封过程的几个步骤中,有多个不一样阶段的挂钩。即。optimizeDependenciesBasic` `optimizeDependencies` and `optimizeDependenciesAdvanced
,这些已经被移除,取而代之的是一个能够与stage
选项一块儿使用的单一钩子。有关可能的阶段,请参阅 OptimizationStages
。
迁移:将钩子挂入剩余的钩子。你能够添加一个 stage
选项。
Bundle模板已经被重构。MainTemplate/ChunkTemplate/ModuleTemplate被弃用,JavascriptModulesPlugin如今负责JS模板的处理。
在重构以前,JS的输出由Main/ChunkTemplate处理,而另外一个输出(如WASM、CSS)由插件处理。看起来JS是第一类,而另外一个输出是第二类。重构改变了全部的输出都由它们的插件处理。
仍然能够链接到模板的某些部分。这些钩子如今在JavascriptModulesPlugin中,而不是Main/ChunkTemplate中。(是的,插件也能够有钩子。我称它们为附着的钩子。)
有一个编译层,因此Main/Chunk/ModuleTemplate仍然存在,但只委托tap调用到新的钩子位置。
迁移:遵循弃用消息中的建议。大多指向不一样位置的钩子。
若是一个对象做为入口点被传递,它的值多是一个字符串,字符串数组或者一个描述符:
module.exports = { entry: { catalog: { import: './catalog.js', } } };
描述符语法能够用来向入口点传递其余选项。
默认状况下,从output.filename
提取条目块的输出文件名。可是你能够为一个特定的条目指定一个自定义输出文件名:
module.exports = { entry: { about: { import: './about.js', filename: 'pages/[name][ext]' } } };
默认状况下,每一个entry chunk存储它使用的全部模块。经过dependOn
-option,您能够从一个entry chunk到另外一个共享模块:
module.exports = { entry: { app: { import: './app.js', dependOn: 'react-vendors' }, 'react-vendors': ['react', 'react-dom', 'prop-types'] } };
app chunk 将不包含react-vendors
拥有的模块。
入口描述符容许为每一个入口点传递不一样的library
选项。
module.exports = { entry: { commonjs: { import: './lib.js', library: { type: "commonjs-module" } }, amd: { import: './lib.js', library: { type: "amd" } } } };
入口描述符容许为每一个入口指定runtime
, 当指定时,将建立具备此名称的chunk,其中仅包含该入口的runtime代码,当多个入口指定相同的runtime
,该chunk将为全部这些入口包含一个公共runtime,这意味着它们能够一块儿使用同一个html页面
module.exports = { entry: { app: { import: './app.js', runtime: "app-runtime" } } };
条目描述符容许为每一个入口指定一个 chunkLoading
。这个入口的运行时将使用它来加载块。
module.exports = { entry: { app: { import: './app.js' }, worker: { import: './worker.js', chunkLoading: "importScripts" } } };
webpack用于在编译阶段以特定的方式对模块和块进行排序,以增量顺序分配id。如今状况已经不同了。order将再也不用于id生成,相反,id生成的彻底控制在插件中。
用来优化模块和块顺序的钩子被删除了。
迁移:在编译阶段不能再依赖模块和块的顺序。
有一个打印弃用警告的压缩层。
迁移:使用Set而不是数组方法。
这个新类可用于以缓存的方式访问关于文件系统的信息。目前,它容许请求文件和目录时间戳。若是可能的话,时间戳的信息从监视器传输,不然由文件系统访问决定。
在将来,请求文件内容哈希将被添加,模块将可以检查文件内容的有效性,而不是文件哈希。
迁移:使用file/fileSystemInfo
代替file/contextTimestamps
。
如今能够对目录进行imestamping,这容许对ContextModules进行序列化。
Compiler.modifiedFiles
已经添加了(在 Compiler.removedFiles
以后),以便更容易地引用更改后的文件。
在compiler.inputFileSystem
和compiler.outputFileSystem
以后。对于全部不被视为输入或输出的fs操做,好比写入记录、缓存或分析输出,有一个新的 compiler.intermediateFileSystem
文件系统如今有了fs接口,而且再也不须要额外的方法,如join或mkdirp。可是若是它们有像join或dirname这样的方法,就会使用它们。
HMR runtime已被重构为Runtime Modules。 HotUpdateChunkTemplate
已经合并到 ChunkTemplate
中。ChunkTemplates和插件如今也应该处理 HotUpdateChunks
。
HMR runtime的javascript部分已经从核心中分离出来。其余模块类型如今也能够以本身的方式处理HMR。在将来,这将容许为像mini-css-extract-plugin或WASM模块提供。
迁移:因为这是一个新引入的功能,因此不须要迁移。
import.meta.webpackHot
与 module.hot
公开相同的API。这也适用于严格的ESM模块(.mjs, type: "module" in package.json)不访问模块。
webpack用函数调用函数的方式去处理模块,以及限制并发的semaphore
。Compilation.semaphore
已经被移除,异步队列如今处理工做排队和处理。每一步都有一个单独的队列:
Compilation.factorizeQueue
: 为一组依赖项调用模块工厂Compilation.addModuleQueue
: 为一组依赖项调用模块工厂Compilation.buildQueue
: 若有必要,构建模块(可能将模块存储到缓存中)Compilation.rebuildQueue
: 若是手动触发,则再次构建模块。Compilation.processDependenciesQueue
: 处理模块的依赖关系。这些队列有一些钩子来监视和拦截做业处理。
未来,多个编译器可能一块儿工做,而job orchestration能够经过拦截这些队列来完成。
迁移:因为这是一个新引入的功能,因此不须要迁移。
webpack内部如今包含了一些日志记录统计数据。可使用 stats.logging
and infrastructureLogging
选项来启用这些消息。
webpack用于将解析后的模块存储在依赖项中,并将包含的模块存储在chunk中。如今状况已经不同了。全部关于模块图中模块如何链接的信息如今都存储在ModuleGraph类中。全部关于模块如何与chunk链接的信息如今都存储在ChunkGraph类中。依赖于块图的信息也存储在相关类中。
这意味着如下关于模块的信息已经被移动
webpack过去从缓存中恢复断开模块与图的链接这已经没有必要了。模块不存储关于图形的信息,这能够在技术上用于多个图形。这使得缓存更容易。
大多数更改都有一个兼容层,在使用时它会打印一个弃用警告。
迁移:使用ModuleGraph和ChunkGraph上的新api
DependenciesBlockVariables
变量被移除,取而代之的是InitFragments。
DependencyTemplates
如今能够添加InitFragments
来将代码注入到模块源代码的顶部。InitFragments
容许删除重复数据。
迁移:使用InitFragments而不是在一个负索引处插入一些东西到源中。
模块如今必须经过 Module.getSourceTypes()
来定义它们支持的源类型。根据这一点,不一样的插件使用这些类型调用 source()
,也就是说,对于源代码类型 javascript
, JavascriptModulesPlugin
将源代码嵌入到包中。源类型 webassembly
将使 WebAssemblyModulesPlugin
发出一个wasm文件。还支持自定义源类型.也就是说,迷你css-extract-plugin可能会使用源代码类型样式表将源代码嵌入到css文件中。
模块类型和源类型之间没有关系。即模块类型 json
也使用源类型 javascript
和模块类型 webassembly/experimental
使用源类型 javascript
和webassembly
。
迁移:自定义模块须要实现这些新的接口方法。
如今的Stats preset
, default
, json
and toString
都是经过插件系统来实现的。将当前状态转换为插件。
迁移:您如今能够自定义它,而不是替换整个Stats功能。如今能够将额外的信息添加到stats json中,而不是编写单独的文件。
webpack使用的观察者被重构了。它之前使用 chokidar
和本机依赖 fsevents
(仅在OSX上)。如今它只基于本地node.js fs
。这意味着webpack中没有原生依赖关系。
它还在监视时捕获关于文件系统的更多信息。它如今能够捕捉时光网时间,查看事件时间,以及丢失文件的信息。为此,WatchFileSystem API作了一点改动。在它上面,咱们还将数组转换为集合,将对象转换为映射。
webpack如今替换了Compilation.assets
的源代码。使用 SizeOnlySource
变量来减小内存使用的资源。
Multiple assets emit different content to the same filename
会警告错误
关于模块导出信息的存储方式已被重构。ModuleGraph如今为每一个模块提供了一个ExportsInfo,它存储每一个导出的信息/它还存储关于未知导出的信息,以及模块是否仅以反作用的方式使用。
对于每一个导出,存储如下信息:
optimization.usedExports
)optimization.providedExports
)optimization.mangleExports
)嵌套的导出信息,若是导出是一个自己附加了信息的对象
import * as X from "..."; export { X };
如今,编译将代码生成做为单独的编译阶段。它再也不隐藏在 Module.source()
or Module.getRuntimeRequirements()
里面
这将使流程更干净。它还容许报告此阶段的进展,并在分析时使代码生成更加可见。
迁移: Module.source()
and Module.getRuntimeRequirements()
被废弃,使用Module.codeGeneration()
替代
当ASI发生时,webpack会检测到,并在没有插入分号时生成更短的代码.Object(...)
-> (0, ...)
webpack将多个导出getter合并到一个运行时函数调用中:
r.d(x, "a", () => a); r.d(x, "b", () => b);
-> r.d(x, {a: () => a, b: () => b});
webpack过去有一个方法和类型来表示依赖项的引用(Compilation.getDependencyReference
returning a DependencyReference
). 此类型用于包括关于此引用的全部信息,如已导入导出的被引用模块,若是它是弱引用,还包括一些排序相关信息。
将全部这些信息捆绑在一块儿使得获取参考变得昂贵,并且每次人们须要一条信息时,它也常常被调用。
在webpack 5中,这部分代码基被重构,方法被分解。
Dependency.getReferencedExports()
得到。Dependency
类上有一个weak
标志HarmonyImportDependencies
相关,能够经过 sourceOrder
属性得到如今在 NormalModules
中有一种新的依赖类型:表示依赖
这些依赖关系只在代码生成阶段使用,而在模块图构建阶段不使用。所以它们永远不会有引用的模块或影响导出/导入。
处理这些依赖关系的成本更低,webpack尽量使用它们
它将被废弃。使用
alias: { xyz$: false }
或者使用绝对路径 [path.resolve(__dirname, "....")]: false
Compiler.name
: 当生成带有绝对路径的编译器名称时,请确保使用|或!名字的两个部分。
SystemPlugin
默认被禁用
Rule.parser.system: true
ModuleConcatenationPlugin
: 因为DependencyVariables
已经被删除,因此链接再也不被阻止
module
, global
, process
或ProvidePlugin的状况下链接exec
从加载器上下文中删除
Stats.presetToOptions
移除
compilation.createStatsOptions
替代SingleEntryPlugin
andSingleEntryDependency
移除
EntryPlugin
and EntryDependency
ExtendedAPIPlugin
移除
webpack_hash__
和webpack_chunkname__
能够一直使用,运行时代码被注入到须要的地方。ProgressPlugin
再也不为reportProgress
使用tapable context
ProgressPlugin.getReporter(compiler)
替代ProvidePlugin
再次为.mjs
文件启用Stats
json errors
and warnings
再也不包含字符串,而是包含信息分解为属性的对象。
message
Compilation.hooks.normalModuleLoader
废弃
NormalModule.getCompilationHooks(compilation).loader
替代NormalModuleFactory
钩子已经从瀑布模型改为流水模型, 改变和重命名返回瀑布函数的钩子移除compilationParams.compilationDependencies
compilation.file/context/missingDependencies
插件能够将依赖项添加到编译中compilationDependencies.add
到 fileDependencies.add
stats.assetsByChunkName[x]
如今是数组__webpack_get_script_filename__
函数添加为了得到script文件名getResolve(options)
会在加载器API用不一样的方式合并选项参数,参考module.rules
resolve
package.json的sideEffects
会被glob-to-regex
处理取代micromatch
checkContext
从IgnorePlugin
移除__webpack_exports_info__
API容许导出usage introspectionRemoved deprecated features
CachePlugin
Chunk.entryModule
is deprecated, use ChunkGraph insteadChunk.hasEntryModule
is deprecatedChunk.addModule
is deprecatedChunk.removeModule
is deprecatedChunk.getNumberOfModules
is deprecatedChunk.modulesIterable
is deprecatedChunk.compareTo
is deprecatedChunk.containsModule
is deprecatedChunk.getModules
is deprecatedChunk.remove
is deprecatedChunk.moveModule
is deprecatedChunk.integrate
is deprecatedChunk.canBeIntegrated
is deprecatedChunk.isEmpty
is deprecatedChunk.modulesSize
is deprecatedChunk.size
is deprecatedChunk.integratedSize
is deprecatedChunk.getChunkModuleMaps
is deprecatedChunk.hasModuleInGraph
is deprecatedChunk.updateHash
signature changedChunk.getChildIdsByOrders
signature changed (TODO: consider moving to ChunkGraph
)Chunk.getChildIdsByOrdersMap
signature changed (TODO: consider moving to ChunkGraph
)Chunk.getChunkModuleMaps
removedChunk.setModules
removedChunkGraph
addedChunkGroup.setParents
removedChunkGroup.containsModule
removedChunkGroup.remove
no longer disconnected the group from blockChunkGroup.compareTo
signature changedChunkGroup.getChildrenByOrders
signature changedChunkGroupindex and index renamed to pre/post order index
ChunkTemplate.hooks.modules
signature changedChunkTemplate.hooks.render
signature changedChunkTemplate.updateHashForChunk
signature changedCompilation.hooks.optimizeChunkOrder
removedCompilation.hooks.optimizeModuleOrder
removedCompilation.hooks.advancedOptimizeModuleOrder
removedCompilation.hooks.optimizeDependenciesBasic
removedCompilation.hooks.optimizeDependenciesAdvanced
removedCompilation.hooks.optimizeModulesBasic
removedCompilation.hooks.optimizeModulesAdvanced
removedCompilation.hooks.optimizeChunksBasic
removedCompilation.hooks.optimizeChunksAdvanced
removedCompilation.hooks.optimizeChunkModulesBasic
removedCompilation.hooks.optimizeChunkModulesAdvanced
removedCompilation.hooks.optimizeExtractedChunksBasic
removedCompilation.hooks.optimizeExtractedChunks
removedCompilation.hooks.optimizeExtractedChunksAdvanced
removedCompilation.hooks.afterOptimizeExtractedChunks
removedCompilation.hooks.stillValidModule
addedCompilation.hooks.statsPreset
addedCompilation.hooks.statsNormalize
addedCompilation.hooks.statsFactory
addedCompilation.hooks.statsPrinter
addedCompilation.fileDependencies
, Compilation.contextDependencies
and Compilation.missingDependencies
are now LazySetsCompilation.entries
removedCompilation.entryDependencies
insteadCompilation._preparedEntrypoints
removeddependencyTemplates
is now a DependencyTemplates
class instead of a raw Map
Compilation.fileTimestamps
and contextTimestamps
removedCompilation.fileSystemInfo
insteadCompilation.waitForBuildingFinished
removedCompilation.addModuleDependencies
removedCompilation.prefetch
removedCompilation.hooks.beforeHash
is now called after the hashes of modules are createdCompiliation.hooks.beforeModuleHash
insteadCompilation.applyModuleIds
removedCompilation.applyChunkIds
removedCompiler.root
added, which points to the root compilerCompiler.hooks.afterDone
addedSource.emitted
is no longer set by the CompilerCompilation.emittedAssets
insteadCompiler/Compilation.compilerPath
added: It's a unique name of the compiler in the compiler tree. (Unique to the root compiler scope)Module.needRebuild
deprecatedModule.needBuild
insteadDependency.getReference
signature changedDependency.getExports
signature changedDependency.getWarnings
signature changedDependency.getErrors
signature changedDependency.updateHash
signature changedDependency.module
removedDependencyTemplate
MultiEntryDependency
removedEntryDependency
addedEntryModuleNotFoundError
removedSingleEntryPlugin
removedEntryPlugin
addedGenerator.getTypes
addedGenerator.getSize
addedGenerator.generate
signature changedHotModuleReplacementPlugin.getParserHooks
addedParser
was moved to JavascriptParser
ParserHelpers
was moved to JavascriptParserHelpers
MainTemplate.hooks.moduleObj
removedMainTemplate.hooks.currentHash
removedMainTemplate.hooks.addModule
removedMainTemplate.hooks.requireEnsure
removedMainTemplate.hooks.globalHashPaths
removedMainTemplate.hooks.globalHash
removedMainTemplate.hooks.hotBootstrap
removedMainTemplate.hooks
some signatures changedModule.hash
deprecatedModule.renderedHash
deprecatedModule.reasons
removedModule.id
deprecatedModule.index
deprecatedModule.index2
deprecatedModule.depth
deprecatedModule.issuer
deprecatedModule.profile
removedModule.prefetched
removedModule.built
removedModule.used
removedModule.getUsedExports
insteadModule.usedExports deprecated
Module.getUsedExports
insteadModule.optimizationBailout
deprecatedModule.exportsArgument
removedModule.optional
deprecatedModule.disconnect
removedModule.unseal
removedModule.setChunks
removedModule.addChunk
deprecatedModule.removeChunk
deprecatedModule.isInChunk
deprecatedModule.isEntryModule
deprecatedModule.getChunks
deprecatedModule.getNumberOfChunks
deprecatedModule.chunksIterable
deprecatedModule.hasEqualsChunks
removedModule.useSourceMap
moved to NormalModule
Module.addReason
removedModule.removeReason
removedModule.rewriteChunkInReasons
removedModule.isUsed
removedisModuleUsed
, isExportUsed
and getUsedName
insteadModule.updateHash
signature changedModule.sortItems
removedModule.unbuild
removedinvalidateBuild
insteadModule.getSourceTypes
addedModule.getRuntimeRequirements
addedModule.size
signature changedModuleFilenameHelpers.createFilename
signature changedModuleProfile
class added with more dataModuleReason
removedModuleTemplate.hooks
signatures changedModuleTemplate.render
signature changedCompiler.dependencies
removedMultiCompiler.setDependencies
insteadMultiModule
removedMultiModuleFactory
removedNormalModuleFactory.fileDependencies
, NormalModuleFactory.contextDependencies
and NormalModuleFactory.missingDependencies
are now LazySetsRuntimeTemplate
methods now take runtimeRequirements
argumentsserve
property is removedStats.jsonToString
removedStats.filterWarnings
removedStats.getChildOptions
removedStats
helper methods removedStats.toJson
signature changed (second argument removed)ExternalModule.external
removedHarmonyInitDependency
removedDependency.getInitFragments
deprecatedapply
initFragements
insteadHarmonyImportSpecifierDependency.redirectedId removed
setId
insteadTesting
async-node
node
web
webworker
store: "instant"
and store: "pack"
resolvedModuleId
resolvedModuleIdentifier
and resolvedModule
to reasons in Stats which point to the module before optimizations like scope hoistingresolvedModule
in Stats toString outputfile/context/missingDependencies
in Compilation
are no longer sorted for performance reasonsCompiler.assetEmitted
has an improved second argument with more informationminChunkSize
option from LimitChunkCountPlugin
reorganize from javascript related files into sub-directory
webpack.JavascriptModulesPlugin
-> webpack.javascript.JavascriptModulesPlugin
__system_context__
as context from System.js when using System.js as libraryTargetassetInfo
from emitAsset
will now merge when nested objects or arrays are used[query]
is now a valid placeholder when for paths based on a filename
like assetsCompilation.deleteAsset
to correctly delete an assets and non-shared related assetsrequire("webpack-sources")
as require("webpack").sources