diff --git a/lib/AbstractMethodError.js b/lib/AbstractMethodError.js index 527d224a473..e149cd600f3 100644 --- a/lib/AbstractMethodError.js +++ b/lib/AbstractMethodError.js @@ -13,9 +13,8 @@ const CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/; * @param {string=} method method name * @returns {string} message */ -function createMessage(method) { - return `Abstract method${method ? ` ${method}` : ""}. Must be overridden.`; -} +const createMessage = (method) => + `Abstract method${method ? ` ${method}` : ""}. Must be overridden.`; /** * @constructor diff --git a/lib/DefinePlugin.js b/lib/DefinePlugin.js index c52558d7518..3cae3084762 100644 --- a/lib/DefinePlugin.js +++ b/lib/DefinePlugin.js @@ -127,10 +127,10 @@ class RuntimeValue { * @param {DestructuringAssignmentProperties | undefined} properties properties * @returns {Set | undefined} used keys */ -function getObjKeys(properties) { +const getObjKeys = (properties) => { if (!properties) return; return new Set([...properties].map((p) => p.id)); -} +}; /** @typedef {Set | null} ObjKeys */ /** @typedef {boolean | undefined | null} AsiSafe */ diff --git a/lib/RuntimeTemplate.js b/lib/RuntimeTemplate.js index 3b868e5deac..d713de7f293 100644 --- a/lib/RuntimeTemplate.js +++ b/lib/RuntimeTemplate.js @@ -325,9 +325,7 @@ class RuntimeTemplate { forEach(variable, array, body) { return this.supportsForOf() ? `for(const ${variable} of ${array}) {\n${Template.indent(body)}\n}` - : `${array}.forEach(function(${variable}) {\n${Template.indent( - body - )}\n});`; + : `${array}.forEach((${variable}) => {\n${Template.indent(body)}\n});`; } /** diff --git a/lib/async-modules/AwaitDependenciesInitFragment.js b/lib/async-modules/AwaitDependenciesInitFragment.js index a0a25a8e832..59ca019f4d6 100644 --- a/lib/async-modules/AwaitDependenciesInitFragment.js +++ b/lib/async-modules/AwaitDependenciesInitFragment.js @@ -55,7 +55,7 @@ class AwaitDependenciesInitFragment extends InitFragment { const asyncModuleValues = [...this.dependencies.values()].join(", "); const templateInput = [ - `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${asyncModuleValues}]);` + `const __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${asyncModuleValues}]);` ]; if ( @@ -63,7 +63,7 @@ class AwaitDependenciesInitFragment extends InitFragment { !runtimeTemplate.supportsDestructuring() ) { templateInput.push( - "var __webpack_async_dependencies_result__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);" + "const __webpack_async_dependencies_result__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);" ); for (const [index, importVar] of importVars.entries()) { templateInput.push( diff --git a/lib/container/ContainerEntryModule.js b/lib/container/ContainerEntryModule.js index 987025d3a4c..b552299f071 100644 --- a/lib/container/ContainerEntryModule.js +++ b/lib/container/ContainerEntryModule.js @@ -226,7 +226,7 @@ class ContainerEntryModule extends Module { `var init = ${runtimeTemplate.basicFunction("shareScope, initScope", [ `if (!${RuntimeGlobals.shareScopeMap}) return;`, `var name = ${JSON.stringify(this._shareScope)}`, - `var oldScope = ${RuntimeGlobals.shareScopeMap}[name];`, + `const oldScope = ${RuntimeGlobals.shareScopeMap}[name];`, 'if(oldScope && oldScope !== shareScope) throw new Error("Container initialization failed as it has already been initialized with a different share scope");', `${RuntimeGlobals.shareScopeMap}[name] = shareScope;`, `return ${RuntimeGlobals.initializeSharing}(name, initScope);` diff --git a/lib/container/FallbackModule.js b/lib/container/FallbackModule.js index 29dd647b9f0..66dee1fa9ef 100644 --- a/lib/container/FallbackModule.js +++ b/lib/container/FallbackModule.js @@ -134,9 +134,9 @@ class FallbackModule extends Module { chunkGraph.getModuleId(/** @type {Module} */ (moduleGraph.getModule(dep))) ); const code = Template.asString([ - `var ids = ${JSON.stringify(ids)};`, - "var error, result, i = 0;", - `var loop = ${runtimeTemplate.basicFunction("next", [ + `const ids = ${JSON.stringify(ids)};`, + "let error, result, i = 0;", + `const loop = ${runtimeTemplate.basicFunction("next", [ "while(i < ids.length) {", Template.indent([ `try { next = ${RuntimeGlobals.require}(ids[i++]); } catch(e) { return handleError(e); }`, @@ -145,11 +145,11 @@ class FallbackModule extends Module { "}", "if(error) throw error;" ])}`, - `var handleResult = ${runtimeTemplate.basicFunction("result", [ + `const handleResult = ${runtimeTemplate.basicFunction("result", [ "if(result) return result;", "return loop();" ])};`, - `var handleError = ${runtimeTemplate.basicFunction("e", [ + `const handleError = ${runtimeTemplate.basicFunction("e", [ "error = e;", "return loop();" ])};`, diff --git a/lib/container/RemoteRuntimeModule.js b/lib/container/RemoteRuntimeModule.js index c44e8ccf71a..fdd9cfc7e21 100644 --- a/lib/container/RemoteRuntimeModule.js +++ b/lib/container/RemoteRuntimeModule.js @@ -76,9 +76,9 @@ class RemoteRuntimeModule extends RuntimeModule { `if(${RuntimeGlobals.hasOwnProperty}(chunkMapping, chunkId)) {`, Template.indent([ `chunkMapping[chunkId].forEach(${runtimeTemplate.basicFunction("id", [ - `var getScope = ${RuntimeGlobals.currentRemoteGetScope};`, + `let getScope = ${RuntimeGlobals.currentRemoteGetScope};`, "if(!getScope) getScope = [];", - "var data = idToExternalAndNameMapping[id];", + "const data = idToExternalAndNameMapping[id];", "if(getScope.indexOf(data) >= 0) return;", "getScope.push(data);", "if(data.p) return promises.push(data.p);", @@ -98,10 +98,10 @@ class RemoteRuntimeModule extends RuntimeModule { [ "try {", Template.indent([ - "var promise = fn(arg1, arg2);", + "const promise = fn(arg1, arg2);", "if(promise && promise.then) {", Template.indent([ - `var p = promise.then(${runtimeTemplate.returningFunction( + `const p = promise.then(${runtimeTemplate.returningFunction( "next(result, d)", "result" )}, onError);`, diff --git a/lib/css/CssLoadingRuntimeModule.js b/lib/css/CssLoadingRuntimeModule.js index 2af0c8aa8ae..ab04f22e9a5 100644 --- a/lib/css/CssLoadingRuntimeModule.js +++ b/lib/css/CssLoadingRuntimeModule.js @@ -191,18 +191,18 @@ class CssLoadingRuntimeModule extends RuntimeModule { : "// data-webpack is not used as build has no uniqueName", withLoading || withHmr ? Template.asString([ - 'var loadingAttribute = "data-webpack-loading";', + 'const loadingAttribute = "data-webpack-loading";', `var loadStylesheet = ${runtimeTemplate.basicFunction( `chunkId, url, done${ withFetchPriority ? ", fetchPriority" : "" }${withHmr ? ", hmr" : ""}`, [ - 'var link, needAttach, key = "chunk-" + chunkId;', + 'let link, needAttach; const key = "chunk-" + chunkId;', withHmr ? "if(!hmr) {" : "", - 'var links = document.getElementsByTagName("link");', - "for(var i = 0; i < links.length; i++) {", + 'const links = document.getElementsByTagName("link");', + "for(let i = 0; i < links.length; i++) {", Template.indent([ - "var l = links[i];", + "const l = links[i];", `if(l.rel == "stylesheet" && (${ withHmr ? 'l.href.startsWith(url) || l.getAttribute("href").startsWith(url)' @@ -235,7 +235,7 @@ class CssLoadingRuntimeModule extends RuntimeModule { )};`, "if(link.getAttribute(loadingAttribute)) {", Template.indent([ - `var timeout = setTimeout(onLinkComplete.bind(null, undefined, { type: 'timeout', target: link }), ${loadTimeout});`, + `const timeout = setTimeout(onLinkComplete.bind(null, undefined, { type: 'timeout', target: link }), ${loadTimeout});`, "link.onerror = onLinkComplete.bind(null, link.onerror);", "link.onload = onLinkComplete.bind(null, link.onload);" ]), @@ -256,7 +256,7 @@ class CssLoadingRuntimeModule extends RuntimeModule { `chunkId, promises${withFetchPriority ? " , fetchPriority" : ""}`, [ "// css chunk loading", - `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, + `let installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, 'if(installedChunkData !== 0) { // 0 means "already installed".', Template.indent([ "", @@ -270,17 +270,17 @@ class CssLoadingRuntimeModule extends RuntimeModule { : `if(${hasCssMatcher("chunkId")}) {`, Template.indent([ "// setup Promise in chunk cache", - `var promise = new Promise(${runtimeTemplate.expressionFunction( + `const promise = new Promise(${runtimeTemplate.expressionFunction( "installedChunkData = installedChunks[chunkId] = [resolve, reject]", "resolve, reject" )});`, "promises.push(installedChunkData[2] = promise);", "", "// start chunk loading", - `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`, + `const url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkCssFilename}(chunkId);`, "// create error before stack unwound to get useful stacktrace later", - "var error = new Error();", - `var loadingEnded = ${runtimeTemplate.basicFunction( + "const error = new Error();", + `const loadingEnded = ${runtimeTemplate.basicFunction( "event", [ `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId)) {`, @@ -291,8 +291,8 @@ class CssLoadingRuntimeModule extends RuntimeModule { Template.indent([ 'if(event.type !== "load") {', Template.indent([ - "var errorType = event && event.type;", - "var realHref = event && event.target && event.target.href;", + "const errorType = event && event.type;", + "const realHref = event && event.target && event.target.href;", "error.message = 'Loading css chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realHref + ')';", "error.name = 'ChunkLoadError';", "error.type = errorType;", @@ -349,7 +349,7 @@ class CssLoadingRuntimeModule extends RuntimeModule { : "", linkPrefetch.call( Template.asString([ - "var link = document.createElement('link');", + "const link = document.createElement('link');", charset ? "link.charset = 'utf-8';" : "", crossOriginLoading ? `link.crossOrigin = ${JSON.stringify( @@ -389,7 +389,7 @@ class CssLoadingRuntimeModule extends RuntimeModule { : "", linkPreload.call( Template.asString([ - "var link = document.createElement('link');", + "const link = document.createElement('link');", charset ? "link.charset = 'utf-8';" : "", `if (${RuntimeGlobals.scriptNonce}) {`, Template.indent( @@ -422,20 +422,20 @@ class CssLoadingRuntimeModule extends RuntimeModule { : "// no preloaded", withHmr ? Template.asString([ - "var oldTags = [];", - "var newTags = [];", + "const oldTags = [];", + "const newTags = [];", `var applyHandler = ${runtimeTemplate.basicFunction("options", [ `return { dispose: ${runtimeTemplate.basicFunction("", [ "while(oldTags.length) {", Template.indent([ - "var oldTag = oldTags.pop();", + "const oldTag = oldTags.pop();", "if(oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);" ]), "}" ])}, apply: ${runtimeTemplate.basicFunction("", [ "while(newTags.length) {", Template.indent([ - "var newTag = newTags.pop();", + "const newTag = newTags.pop();", "newTag.sheet.disabled = false" ]), "}" @@ -458,9 +458,9 @@ class CssLoadingRuntimeModule extends RuntimeModule { : "", "applyHandlers.push(applyHandler);", `chunkIds.forEach(${runtimeTemplate.basicFunction("chunkId", [ - `var filename = ${RuntimeGlobals.getChunkCssFilename}(chunkId);`, - `var url = ${RuntimeGlobals.publicPath} + filename;`, - "var oldTag = loadStylesheet(chunkId, url);", + `const filename = ${RuntimeGlobals.getChunkCssFilename}(chunkId);`, + `const url = ${RuntimeGlobals.publicPath} + filename;`, + "const oldTag = loadStylesheet(chunkId, url);", "if(!oldTag) return;", `promises.push(new Promise(${runtimeTemplate.basicFunction( "resolve, reject", @@ -470,8 +470,8 @@ class CssLoadingRuntimeModule extends RuntimeModule { [ 'if(event.type !== "load") {', Template.indent([ - "var errorType = event && event.type;", - "var realHref = event && event.target && event.target.href;", + "const errorType = event && event.type;", + "const realHref = event && event.target && event.target.href;", "error.message = 'Loading css hot update chunk ' + chunkId + ' failed.\\n(' + errorType + ': ' + realHref + ')';", "error.name = 'ChunkLoadError';", "error.type = errorType;", diff --git a/lib/css/CssModulesPlugin.js b/lib/css/CssModulesPlugin.js index 89341e1a908..ac88bc01069 100644 --- a/lib/css/CssModulesPlugin.js +++ b/lib/css/CssModulesPlugin.js @@ -411,7 +411,7 @@ class CssModulesPlugin { const hmrCode = Template.asString([ "", - `var __webpack_css_exports__ = ${stringifiedExports};`, + `const __webpack_css_exports__ = ${stringifiedExports};`, "// only invalidate when locals change", "if (module.hot.data && module.hot.data.__webpack_css_exports__ && module.hot.data.__webpack_css_exports__ != __webpack_css_exports__) {", Template.indent("module.hot.invalidate();"), diff --git a/lib/esm/ModuleChunkLoadingRuntimeModule.js b/lib/esm/ModuleChunkLoadingRuntimeModule.js index 453320c8111..69688a671a9 100644 --- a/lib/esm/ModuleChunkLoadingRuntimeModule.js +++ b/lib/esm/ModuleChunkLoadingRuntimeModule.js @@ -205,7 +205,7 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule { hasJsMatcher !== false ? Template.indent([ "// import() chunk loading for javascript", - `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, + `const installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`, 'if(installedChunkData !== 0) { // 0 means "already installed".', Template.indent([ "", @@ -269,7 +269,7 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule { "installedChunks[chunkId] = null;", linkPrefetch.call( Template.asString([ - "var link = document.createElement('link');", + "const link = document.createElement('link');", charset ? "link.charset = 'utf-8';" : "", crossOriginLoading ? `link.crossOrigin = ${JSON.stringify( @@ -309,7 +309,7 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule { "installedChunks[chunkId] = null;", linkPreload.call( Template.asString([ - "var link = document.createElement('link');", + "const link = document.createElement('link');", charset ? "link.charset = 'utf-8';" : "", `if (${RuntimeGlobals.scriptNonce}) {`, Template.indent( @@ -364,10 +364,10 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule { "resolve, reject", [ "// start update chunk loading", - `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId);`, + `const url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId);`, `var onResolve = ${runtimeTemplate.basicFunction("obj", [ - `var updatedModules = obj.${RuntimeGlobals.esmModules};`, - `var updatedRuntime = obj.${RuntimeGlobals.esmRuntime};`, + `const updatedModules = obj.${RuntimeGlobals.esmModules};`, + `const updatedRuntime = obj.${RuntimeGlobals.esmRuntime};`, "if(updatedRuntime) currentUpdateRuntime.push(updatedRuntime);", "for(var moduleId in updatedModules) {", Template.indent([ @@ -382,7 +382,7 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule { "resolve(obj);" ])};`, `var onReject = ${runtimeTemplate.basicFunction("error", [ - "var errorMsg = error.message || 'unknown reason';", + "const errorMsg = error.message || 'unknown reason';", "error.message = 'Loading hot update chunk ' + chunkId + ' failed.\\n(' + errorMsg + ')';", "error.name = 'ChunkLoadError';", "reject(error);" diff --git a/lib/hmr/LazyCompilationPlugin.js b/lib/hmr/LazyCompilationPlugin.js index a7791899b58..f182b74a0bf 100644 --- a/lib/hmr/LazyCompilationPlugin.js +++ b/lib/hmr/LazyCompilationPlugin.js @@ -239,10 +239,10 @@ class LazyCompilationProxyModule extends Module { request: clientDep.userRequest, runtimeRequirements })}`, - `var data = ${JSON.stringify(this.data)};` + `const data = ${JSON.stringify(this.data)};` ]); const keepActive = Template.asString([ - `var dispose = client.keepAlive({ data: data, active: ${JSON.stringify( + `const dispose = client.keepAlive({ data: data, active: ${JSON.stringify( Boolean(block) )}, module: module, onError: onError });` ]); @@ -277,8 +277,8 @@ class LazyCompilationProxyModule extends Module { } else { source = Template.asString([ client, - "var resolveSelf, onError;", - "module.exports = new Promise(function(resolve, reject) { resolveSelf = resolve; onError = reject; });", + "let resolveSelf, onError;", + "module.exports = new Promise((resolve, reject) => { resolveSelf = resolve; onError = reject; });", "if (module.hot) {", Template.indent([ "module.hot.accept();", diff --git a/lib/javascript/CommonJsChunkFormatPlugin.js b/lib/javascript/CommonJsChunkFormatPlugin.js index 9ce41aa1a33..34a5115051a 100644 --- a/lib/javascript/CommonJsChunkFormatPlugin.js +++ b/lib/javascript/CommonJsChunkFormatPlugin.js @@ -106,11 +106,11 @@ class CommonJsChunkFormatPlugin { runtimeTemplate.supportsArrowFunction() ? "() => " : "function() " }{\n` ); - entrySource.add("var exports = {};\n"); + entrySource.add("const exports = {};\n"); entrySource.add(source); entrySource.add(";\n\n// load runtime\n"); entrySource.add( - `var ${RuntimeGlobals.require} = require(${JSON.stringify( + `const ${RuntimeGlobals.require} = require(${JSON.stringify( runtimePath )});\n` ); diff --git a/lib/javascript/JavascriptModulesPlugin.js b/lib/javascript/JavascriptModulesPlugin.js index 699e0d7b228..45cef625e33 100644 --- a/lib/javascript/JavascriptModulesPlugin.js +++ b/lib/javascript/JavascriptModulesPlugin.js @@ -1507,7 +1507,7 @@ class JavascriptModulesPlugin { ) ? Template.asString([ `var execOptions = { id: moduleId, module: module, factory: __webpack_modules__[moduleId], require: ${RuntimeGlobals.require} };`, - `${RuntimeGlobals.interceptModuleExecution}.forEach(function(handler) { handler(execOptions); });`, + `${RuntimeGlobals.interceptModuleExecution}.forEach((handler) => { handler(execOptions); });`, "module = execOptions.module;", "execOptions.factory.call(module.exports, module, module.exports, execOptions.require);" ]) diff --git a/lib/library/AssignLibraryPlugin.js b/lib/library/AssignLibraryPlugin.js index f8f00df1803..298f87e661f 100644 --- a/lib/library/AssignLibraryPlugin.js +++ b/lib/library/AssignLibraryPlugin.js @@ -342,12 +342,12 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin { let exports = RuntimeGlobals.exports; if (exportAccess) { result.add( - `var __webpack_exports_export__ = ${RuntimeGlobals.exports}${exportAccess};\n` + `const __webpack_exports_export__ = ${RuntimeGlobals.exports}${exportAccess};\n` ); exports = "__webpack_exports_export__"; } - result.add(`for(var __webpack_i__ in ${exports}) {\n`); + result.add(`for(const __webpack_i__ in ${exports}) {\n`); const hasProvided = provided.length > 0; if (hasProvided) { result.add( @@ -368,7 +368,7 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin { ); } else if (options.name ? this.named === "copy" : this.unnamed === "copy") { result.add( - `var __webpack_export_target__ = ${accessWithInit( + `const __webpack_export_target__ = ${accessWithInit( fullNameResolved, this._getPrefix(compilation).length, true @@ -378,13 +378,13 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin { let exports = RuntimeGlobals.exports; if (exportAccess) { result.add( - `var __webpack_exports_export__ = ${RuntimeGlobals.exports}${exportAccess};\n` + `const __webpack_exports_export__ = ${RuntimeGlobals.exports}${exportAccess};\n` ); exports = "__webpack_exports_export__"; } result.add( - `for(var __webpack_i__ in ${exports}) __webpack_export_target__[__webpack_i__] = ${exports}[__webpack_i__];\n` + `for(const __webpack_i__ in ${exports}) __webpack_export_target__[__webpack_i__] = ${exports}[__webpack_i__];\n` ); result.add( `if(${exports}.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });\n` diff --git a/lib/library/SystemLibraryPlugin.js b/lib/library/SystemLibraryPlugin.js index 38096209174..e9627e964ce 100644 --- a/lib/library/SystemLibraryPlugin.js +++ b/lib/library/SystemLibraryPlugin.js @@ -161,7 +161,7 @@ class SystemLibraryPlugin extends AbstractLibraryPlugin { ); instructions.push( Template.asString([ - "Object.keys(module).forEach(function(key) {", + "Object.keys(module).forEach((key) => {", Template.indent([ `if(${name}.indexOf(key) >= 0)`, Template.indent(`${external}[key] = module[key];`) @@ -172,7 +172,7 @@ class SystemLibraryPlugin extends AbstractLibraryPlugin { } else { instructions.push( Template.asString([ - "Object.keys(module).forEach(function(key) {", + "Object.keys(module).forEach((key) => {", Template.indent([`${external}[key] = module[key];`]), "});" ]) diff --git a/lib/library/UmdLibraryPlugin.js b/lib/library/UmdLibraryPlugin.js index e0269e02713..b7489a1c0ae 100644 --- a/lib/library/UmdLibraryPlugin.js +++ b/lib/library/UmdLibraryPlugin.js @@ -332,11 +332,11 @@ class UmdLibraryPlugin extends AbstractLibraryPlugin { )} = factory(${externalsRootArray(externals)});\n` : ` else {\n${ externals.length > 0 - ? ` var a = typeof exports === 'object' ? factory(${externalsRequireArray( + ? ` const a = typeof exports === 'object' ? factory(${externalsRequireArray( "commonjs" )}) : factory(${externalsRootArray(externals)});\n` - : " var a = factory();\n" - } for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n` + + : " const a = factory();\n" + } for(const i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n` + " }\n" }})(${runtimeTemplate.outputOptions.globalObject}, ${ runtimeTemplate.supportsArrowFunction() diff --git a/lib/node/ReadFileChunkLoadingRuntimeModule.js b/lib/node/ReadFileChunkLoadingRuntimeModule.js index f4e82e4232e..fd7da487b38 100644 --- a/lib/node/ReadFileChunkLoadingRuntimeModule.js +++ b/lib/node/ReadFileChunkLoadingRuntimeModule.js @@ -170,10 +170,10 @@ class ReadFileChunkLoadingRuntimeModule extends RuntimeModule { : `if(${hasJsMatcher("chunkId")}) {`, Template.indent([ "// load the chunk and return promise to it", - "var promise = new Promise(function(resolve, reject) {", + "const promise = new Promise((resolve, reject) => {", Template.indent([ "installedChunkData = installedChunks[chunkId] = [resolve, reject];", - `var filename = require(${runtimeTemplate.renderNodePrefixForCoreModule("path")}).join(__dirname, ${JSON.stringify( + `const filename = require(${runtimeTemplate.renderNodePrefixForCoreModule("path")}).join(__dirname, ${JSON.stringify( rootOutputDir )} + ${ RuntimeGlobals.getChunkScriptFilename @@ -215,9 +215,9 @@ class ReadFileChunkLoadingRuntimeModule extends RuntimeModule { ? Template.asString([ "function loadUpdateChunk(chunkId, updatedModulesList) {", Template.indent([ - "return new Promise(function(resolve, reject) {", + "return new Promise((resolve, reject) => {", Template.indent([ - `var filename = require(${runtimeTemplate.renderNodePrefixForCoreModule("path")}).join(__dirname, ${JSON.stringify( + `const filename = require(${runtimeTemplate.renderNodePrefixForCoreModule("path")}).join(__dirname, ${JSON.stringify( rootOutputDir )} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId));`, `require(${runtimeTemplate.renderNodePrefixForCoreModule("fs")}).readFile(filename, 'utf-8', function(err, content) {`, @@ -255,9 +255,9 @@ class ReadFileChunkLoadingRuntimeModule extends RuntimeModule { ? Template.asString([ `${RuntimeGlobals.hmrDownloadManifest} = function() {`, Template.indent([ - "return new Promise(function(resolve, reject) {", + "return new Promise((resolve, reject) => {", Template.indent([ - `var filename = require(${runtimeTemplate.renderNodePrefixForCoreModule("path")}).join(__dirname, ${JSON.stringify( + `const filename = require(${runtimeTemplate.renderNodePrefixForCoreModule("path")}).join(__dirname, ${JSON.stringify( rootOutputDir )} + ${RuntimeGlobals.getUpdateManifestFilename}());`, `require(${runtimeTemplate.renderNodePrefixForCoreModule("fs")}).readFile(filename, 'utf-8', function(err, content) {`, diff --git a/lib/node/ReadFileCompileAsyncWasmPlugin.js b/lib/node/ReadFileCompileAsyncWasmPlugin.js index bf8f273d813..8b5741d1e1b 100644 --- a/lib/node/ReadFileCompileAsyncWasmPlugin.js +++ b/lib/node/ReadFileCompileAsyncWasmPlugin.js @@ -72,7 +72,7 @@ class ReadFileCompileAsyncWasmPlugin { ]) : (path) => Template.asString([ - "new Promise(function (resolve, reject) {", + "new Promise((resolve, reject) => {", Template.indent([ "try {", Template.indent([ diff --git a/lib/node/ReadFileCompileWasmPlugin.js b/lib/node/ReadFileCompileWasmPlugin.js index bbc1f4dd7de..e3ee864f430 100644 --- a/lib/node/ReadFileCompileWasmPlugin.js +++ b/lib/node/ReadFileCompileWasmPlugin.js @@ -75,7 +75,7 @@ class ReadFileCompileWasmPlugin { ]) : (path) => Template.asString([ - "new Promise(function (resolve, reject) {", + "new Promise((resolve, reject) => {", Template.indent([ `var { readFile } = require(${compilation.runtimeTemplate.renderNodePrefixForCoreModule("fs")});`, `var { join } = require(${compilation.runtimeTemplate.renderNodePrefixForCoreModule("path")});`, diff --git a/lib/node/RequireChunkLoadingRuntimeModule.js b/lib/node/RequireChunkLoadingRuntimeModule.js index e748a8cee03..9f6cdb48966 100644 --- a/lib/node/RequireChunkLoadingRuntimeModule.js +++ b/lib/node/RequireChunkLoadingRuntimeModule.js @@ -127,8 +127,8 @@ class RequireChunkLoadingRuntimeModule extends RuntimeModule { "", withLoading || withExternalInstallChunk ? `var installChunk = ${runtimeTemplate.basicFunction("chunk", [ - "var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;", - "for(var moduleId in moreModules) {", + "const moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;", + "for(const moduleId in moreModules) {", Template.indent([ `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, Template.indent([ @@ -138,7 +138,7 @@ class RequireChunkLoadingRuntimeModule extends RuntimeModule { ]), "}", `if(runtime) runtime(${RuntimeGlobals.require});`, - "for(var i = 0; i < chunkIds.length; i++)", + "for(let i = 0; i < chunkIds.length; i++)", Template.indent("installedChunks[chunkIds[i]] = 1;"), withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "" ])};` @@ -193,9 +193,9 @@ class RequireChunkLoadingRuntimeModule extends RuntimeModule { `var update = require(${JSON.stringify(rootOutputDir)} + ${ RuntimeGlobals.getChunkUpdateScriptFilename }(chunkId));`, - "var updatedModules = update.modules;", - "var runtime = update.runtime;", - "for(var moduleId in updatedModules) {", + "const updatedModules = update.modules;", + "const runtime = update.runtime;", + "for(const moduleId in updatedModules) {", Template.indent([ `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`, Template.indent([ diff --git a/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js b/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js index 12f53e16add..c8135235f09 100644 --- a/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js +++ b/lib/prefetch/ChunkPrefetchTriggerRuntimeModule.js @@ -28,12 +28,12 @@ class ChunkPrefetchTriggerRuntimeModule extends RuntimeModule { const compilation = /** @type {Compilation} */ (this.compilation); const { runtimeTemplate } = compilation; const body = [ - "var chunks = chunkToChildrenMap[chunkId];", + "const chunks = chunkToChildrenMap[chunkId];", `Array.isArray(chunks) && chunks.map(${RuntimeGlobals.prefetchChunk});` ]; return Template.asString([ Template.asString([ - `var chunkToChildrenMap = ${JSON.stringify(chunkMap, null, "\t")};`, + `const chunkToChildrenMap = ${JSON.stringify(chunkMap, null, "\t")};`, `${ RuntimeGlobals.ensureChunkHandlers }.prefetch = ${runtimeTemplate.expressionFunction( diff --git a/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js b/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js index 311fc9a4910..0854f8d9bf3 100644 --- a/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js +++ b/lib/prefetch/ChunkPreloadTriggerRuntimeModule.js @@ -28,12 +28,12 @@ class ChunkPreloadTriggerRuntimeModule extends RuntimeModule { const compilation = /** @type {Compilation} */ (this.compilation); const { runtimeTemplate } = compilation; const body = [ - "var chunks = chunkToChildrenMap[chunkId];", + "const chunks = chunkToChildrenMap[chunkId];", `Array.isArray(chunks) && chunks.map(${RuntimeGlobals.preloadChunk});` ]; return Template.asString([ Template.asString([ - `var chunkToChildrenMap = ${JSON.stringify(chunkMap, null, "\t")};`, + `const chunkToChildrenMap = ${JSON.stringify(chunkMap, null, "\t")};`, `${ RuntimeGlobals.ensureChunkHandlers }.preload = ${runtimeTemplate.basicFunction("chunkId", body)};` diff --git a/lib/runtime/AsyncModuleRuntimeModule.js b/lib/runtime/AsyncModuleRuntimeModule.js index 441480ba088..bfc6731a96c 100644 --- a/lib/runtime/AsyncModuleRuntimeModule.js +++ b/lib/runtime/AsyncModuleRuntimeModule.js @@ -28,19 +28,19 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule { const fn = RuntimeGlobals.asyncModule; const defer = this._deferInterop; return Template.asString([ - 'var hasSymbol = typeof Symbol === "function";', - 'var webpackQueues = hasSymbol ? Symbol("webpack queues") : "__webpack_queues__";', - `var webpackExports = ${ + 'const hasSymbol = typeof Symbol === "function";', + 'const webpackQueues = hasSymbol ? Symbol("webpack queues") : "__webpack_queues__";', + `const webpackExports = ${ defer ? `${RuntimeGlobals.asyncModuleExportSymbol}= ` : "" }hasSymbol ? Symbol("webpack exports") : "${RuntimeGlobals.exports}";`, - 'var webpackError = hasSymbol ? Symbol("webpack error") : "__webpack_error__";', + 'const webpackError = hasSymbol ? Symbol("webpack error") : "__webpack_error__";', defer - ? `var webpackDone = ${RuntimeGlobals.asyncModuleDoneSymbol} = hasSymbol ? Symbol("webpack done") : "__webpack_done__";` + ? `const webpackDone = ${RuntimeGlobals.asyncModuleDoneSymbol} = hasSymbol ? Symbol("webpack done") : "__webpack_done__";` : "", defer - ? `var webpackDefer = ${RuntimeGlobals.makeDeferredNamespaceObjectSymbol} = hasSymbol ? Symbol("webpack defer") : "__webpack_defer__";` + ? `const webpackDefer = ${RuntimeGlobals.makeDeferredNamespaceObjectSymbol} = hasSymbol ? Symbol("webpack defer") : "__webpack_defer__";` : "", - `var resolveQueue = ${runtimeTemplate.basicFunction("queue", [ + `const resolveQueue = ${runtimeTemplate.basicFunction("queue", [ "if(queue && queue.d < 1) {", Template.indent([ "queue.d = 1;", @@ -55,7 +55,7 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule { ]), "}" ])}`, - `var wrapDeps = ${runtimeTemplate.returningFunction( + `const wrapDeps = ${runtimeTemplate.returningFunction( `deps.map(${runtimeTemplate.basicFunction("dep", [ 'if(dep !== null && typeof dep === "object") {', Template.indent([ @@ -63,17 +63,17 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule { ? Template.asString([ "if(!dep[webpackQueues] && dep[webpackDefer]) {", Template.indent([ - "var asyncDeps = dep[webpackDefer];", - `var hasUnresolvedAsyncSubgraph = asyncDeps.some(${runtimeTemplate.basicFunction( + "const asyncDeps = dep[webpackDefer];", + `const hasUnresolvedAsyncSubgraph = asyncDeps.some(${runtimeTemplate.basicFunction( "id", [ - "var cache = __webpack_module_cache__[id];", + "const cache = __webpack_module_cache__[id];", "return !cache || cache[webpackDone] === false;" ] )});`, "if (hasUnresolvedAsyncSubgraph) {", Template.indent([ - "var d = dep;", + "const d = dep;", "dep = {", Template.indent([ "then(callback) {", @@ -95,7 +95,7 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule { "if(dep[webpackQueues]) return dep;", "if(dep.then) {", Template.indent([ - "var queue = [];", + "const queue = [];", "queue.d = 0;", `dep.then(${runtimeTemplate.basicFunction("r", [ "obj[webpackExports] = r;", @@ -104,7 +104,7 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule { "obj[webpackError] = e;", "resolveQueue(queue);" ])});`, - "var obj = {};", + "const obj = {};", defer ? "obj[webpackDefer] = false;" : "", `obj[webpackQueues] = ${runtimeTemplate.expressionFunction( "fn(queue)", @@ -115,7 +115,7 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule { "}" ]), "}", - "var ret = {};", + "const ret = {};", `ret[webpackQueues] = ${runtimeTemplate.emptyFunction()};`, "ret[webpackExports] = dep;", "return ret;" @@ -125,12 +125,12 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule { `${fn} = ${runtimeTemplate.basicFunction("module, body, hasAwait", [ "var queue;", "hasAwait && ((queue = []).d = -1);", - "var depQueues = new Set();", - "var exports = module.exports;", - "var currentDeps;", - "var outerResolve;", - "var reject;", - `var promise = new Promise(${runtimeTemplate.basicFunction( + "const depQueues = new Set();", + "const exports = module.exports;", + "let currentDeps;", + "let outerResolve;", + "let reject;", + `const promise = new Promise(${runtimeTemplate.basicFunction( "resolve, rej", ["reject = rej;", "outerResolve = resolve;"] )});`, @@ -150,7 +150,7 @@ class AsyncModuleRuntimeModule extends HelperRuntimeModule { "return d[webpackExports];" ])})` )}`, - `var promise = new Promise(${runtimeTemplate.basicFunction( + `const promise = new Promise(${runtimeTemplate.basicFunction( "resolve", [ `fn = ${runtimeTemplate.expressionFunction( diff --git a/lib/runtime/AutoPublicPathRuntimeModule.js b/lib/runtime/AutoPublicPathRuntimeModule.js index 0433194fb09..62b807bf5bb 100644 --- a/lib/runtime/AutoPublicPathRuntimeModule.js +++ b/lib/runtime/AutoPublicPathRuntimeModule.js @@ -47,7 +47,7 @@ class AutoPublicPathRuntimeModule extends RuntimeModule { ? `if (typeof ${importMetaName}.url === "string") scriptUrl = ${importMetaName}.url` : Template.asString([ `if (${RuntimeGlobals.global}.importScripts) scriptUrl = ${RuntimeGlobals.global}.location + "";`, - `var document = ${RuntimeGlobals.global}.document;`, + `const document = ${RuntimeGlobals.global}.document;`, "if (!scriptUrl && document) {", Template.indent([ // Technically we could use `document.currentScript instanceof window.HTMLScriptElement`, @@ -57,10 +57,10 @@ class AutoPublicPathRuntimeModule extends RuntimeModule { Template.indent("scriptUrl = document.currentScript.src;"), "if (!scriptUrl) {", Template.indent([ - 'var scripts = document.getElementsByTagName("script");', + 'const scripts = document.getElementsByTagName("script");', "if(scripts.length) {", Template.indent([ - "var i = scripts.length - 1;", + "let i = scripts.length - 1;", "while (i > -1 && (!scriptUrl || !/^http(s?):/.test(scriptUrl))) scriptUrl = scripts[i--].src;" ]), "}" diff --git a/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js b/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js index b5f09df7952..18ba240ddb5 100644 --- a/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js +++ b/lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js @@ -45,11 +45,11 @@ class CreateFakeNamespaceObjectRuntimeModule extends HelperRuntimeModule { "if((mode & 16) && typeof value.then === 'function') return value;" ]), "}", - "var ns = Object.create(null);", + "const ns = Object.create(null);", `${RuntimeGlobals.makeNamespaceObject}(ns);`, - "var def = {};", + "const def = {};", "leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];", - "for(var current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {", + "for(let current = mode & 2 && value; (typeof current == 'object' || typeof current == 'function') && !~leafPrototypes.indexOf(current); current = getProto(current)) {", Template.indent([ `Object.getOwnPropertyNames(current).forEach(${runtimeTemplate.expressionFunction( `def[key] = ${runtimeTemplate.returningFunction("value[key]", "")}`, diff --git a/lib/runtime/LoadScriptRuntimeModule.js b/lib/runtime/LoadScriptRuntimeModule.js index 57df714069d..5854ad9afe9 100644 --- a/lib/runtime/LoadScriptRuntimeModule.js +++ b/lib/runtime/LoadScriptRuntimeModule.js @@ -109,9 +109,9 @@ class LoadScriptRuntimeModule extends HelperRuntimeModule { ]); return Template.asString([ - "var inProgress = {};", + "const inProgress = {};", uniqueName - ? `var dataWebpackPrefix = ${JSON.stringify(`${uniqueName}:`)};` + ? `const dataWebpackPrefix = ${JSON.stringify(`${uniqueName}:`)};` : "// data-webpack is not used as build has no uniqueName", "// loadScript function to load a script via script tag", `${fn} = ${runtimeTemplate.basicFunction( @@ -120,13 +120,13 @@ class LoadScriptRuntimeModule extends HelperRuntimeModule { }`, [ "if(inProgress[url]) { inProgress[url].push(done); return; }", - "var script, needAttach;", + "let script, needAttach;", "if(key !== undefined) {", Template.indent([ - 'var scripts = document.getElementsByTagName("script");', - "for(var i = 0; i < scripts.length; i++) {", + 'const scripts = document.getElementsByTagName("script");', + "for(let i = 0; i < scripts.length; i++) {", Template.indent([ - "var s = scripts[i];", + "const s = scripts[i];", `if(s.getAttribute("src") == url${ uniqueName ? ' || s.getAttribute("data-webpack") == dataWebpackPrefix + key' @@ -149,7 +149,7 @@ class LoadScriptRuntimeModule extends HelperRuntimeModule { "// avoid mem leaks in IE.", "script.onerror = script.onload = null;", "clearTimeout(timeout);", - "var doneFns = inProgress[url];", + "const doneFns = inProgress[url];", "delete inProgress[url];", "script.parentNode && script.parentNode.removeChild(script);", `doneFns && doneFns.forEach(${runtimeTemplate.returningFunction( @@ -159,7 +159,7 @@ class LoadScriptRuntimeModule extends HelperRuntimeModule { "if(prev) return prev(event);" ]) )}`, - `var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), ${loadTimeout});`, + `const timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), ${loadTimeout});`, "script.onerror = onScriptComplete.bind(null, script.onerror);", "script.onload = onScriptComplete.bind(null, script.onload);", "needAttach && document.head.appendChild(script);" diff --git a/lib/runtime/MakeDeferredNamespaceObjectRuntime.js b/lib/runtime/MakeDeferredNamespaceObjectRuntime.js index b1d91e422fd..b05c7477cc8 100644 --- a/lib/runtime/MakeDeferredNamespaceObjectRuntime.js +++ b/lib/runtime/MakeDeferredNamespaceObjectRuntime.js @@ -43,7 +43,7 @@ function getOptimizedDeferredModule( // we can also do this if exportsType is "dynamic" and there is a "__esModule" property on it. exportsType === "namespace" || exportsType === "dynamic" ? Template.indent([ - `var exports = ${init};`, + `const exports = ${init};`, `${ exportsType === "dynamic" ? "if (exports.__esModule) " : "" }Object.defineProperty(this, "a", { value: exports });`, @@ -63,7 +63,7 @@ function getOptimizedDeferredModule( const strictModuleCache = [ "if (cachedModule && cachedModule.error === undefined) {", Template.indent([ - "var exports = cachedModule.exports;", + "const exports = cachedModule.exports;", "if (mode == 0) return exports;", `if (mode == 1) return ${RuntimeGlobals.createFakeNamespaceObject}(exports);`, `if (mode == 2) return ${RuntimeGlobals.createFakeNamespaceObject}(exports, 2);`, @@ -103,7 +103,7 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule { "// mode: 2 => default-with-named (esm-cjs compat)", "// mode: 3 => dynamic (if exports has __esModule, then esm, otherwise default-with-named)", "", - "var cachedModule = __webpack_module_cache__[moduleId];", + "const cachedModule = __webpack_module_cache__[moduleId];", ...(strictError ? strictModuleCache : nonStrictModuleCache), "", `var init = ${runtimeTemplate.basicFunction("", [ @@ -174,7 +174,7 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule { ])},`, `ownKeys: ${runtimeTemplate.basicFunction("", [ init, - `var keys = Reflect.ownKeys(ns).filter(${runtimeTemplate.expressionFunction('x !== "then"', "x")}).concat([Symbol.toStringTag]);`, + `const keys = Reflect.ownKeys(ns).filter(${runtimeTemplate.expressionFunction('x !== "then"', "x")}).concat([Symbol.toStringTag]);`, "return keys;" ])},`, `getOwnPropertyDescriptor: ${runtimeTemplate.basicFunction("_, name", [ @@ -186,7 +186,7 @@ class MakeDeferredNamespaceObjectRuntimeModule extends HelperRuntimeModule { ]), "}", init, - "var desc = Reflect.getOwnPropertyDescriptor(ns, name);", + "const desc = Reflect.getOwnPropertyDescriptor(ns, name);", 'if (mode == 2 && name == "default" && !desc) {', Template.indent("desc = { value: ns, configurable: true };"), "}", diff --git a/lib/runtime/RelativeUrlRuntimeModule.js b/lib/runtime/RelativeUrlRuntimeModule.js index 92e32daed98..363d38511f2 100644 --- a/lib/runtime/RelativeUrlRuntimeModule.js +++ b/lib/runtime/RelativeUrlRuntimeModule.js @@ -24,16 +24,16 @@ class RelativeUrlRuntimeModule extends HelperRuntimeModule { return Template.asString([ `${RuntimeGlobals.relativeUrl} = function RelativeURL(url) {`, Template.indent([ - 'var realUrl = new URL(url, "x:/");', - "var values = {};", - "for (var key in realUrl) values[key] = realUrl[key];", + 'const realUrl = new URL(url, "x:/");', + "const values = {};", + "for (const key in realUrl) values[key] = realUrl[key];", "values.href = url;", 'values.pathname = url.replace(/[?#].*/, "");', 'values.origin = values.protocol = "";', `values.toString = values.toJSON = ${runtimeTemplate.returningFunction( "url" )};`, - "for (var key in values) Object.defineProperty(this, key, { enumerable: true, configurable: true, value: values[key] });" + "for (const key in values) Object.defineProperty(this, key, { enumerable: true, configurable: true, value: values[key] });" ]), "};", `${RuntimeGlobals.relativeUrl}.prototype = URL.prototype;` diff --git a/lib/runtime/StartupChunkDependenciesRuntimeModule.js b/lib/runtime/StartupChunkDependenciesRuntimeModule.js index 7ff03978353..c17e47e7245 100644 --- a/lib/runtime/StartupChunkDependenciesRuntimeModule.js +++ b/lib/runtime/StartupChunkDependenciesRuntimeModule.js @@ -34,7 +34,7 @@ class StartupChunkDependenciesRuntimeModule extends RuntimeModule { const compilation = /** @type {Compilation} */ (this.compilation); const { runtimeTemplate } = compilation; return Template.asString([ - `var next = ${RuntimeGlobals.startup};`, + `const next = ${RuntimeGlobals.startup};`, `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction( "", !this.asyncChunkLoading diff --git a/lib/runtime/StartupEntrypointRuntimeModule.js b/lib/runtime/StartupEntrypointRuntimeModule.js index ab36f0cec60..e20ef2fec77 100644 --- a/lib/runtime/StartupEntrypointRuntimeModule.js +++ b/lib/runtime/StartupEntrypointRuntimeModule.js @@ -28,7 +28,7 @@ class StartupEntrypointRuntimeModule extends RuntimeModule { RuntimeGlobals.startupEntrypoint } = ${runtimeTemplate.basicFunction("result, chunkIds, fn", [ "// arguments: chunkIds, moduleId are deprecated", - "var moduleId = chunkIds;", + "const moduleId = chunkIds;", `if(!fn) chunkIds = result, fn = ${runtimeTemplate.returningFunction( `${RuntimeGlobals.require}(${RuntimeGlobals.entryModuleId} = moduleId)` )};`, @@ -37,13 +37,13 @@ class StartupEntrypointRuntimeModule extends RuntimeModule { `return Promise.all(chunkIds.map(${RuntimeGlobals.ensureChunk}, ${ RuntimeGlobals.require })).then(${runtimeTemplate.basicFunction("", [ - "var r = fn();", + "const r = fn();", "return r === undefined ? result : r;" ])})` ] : [ `chunkIds.map(${RuntimeGlobals.ensureChunk}, ${RuntimeGlobals.require})`, - "var r = fn();", + "const r = fn();", "return r === undefined ? result : r;" ]) ])}`; diff --git a/lib/sharing/ConsumeSharedRuntimeModule.js b/lib/sharing/ConsumeSharedRuntimeModule.js index 1da174b62d1..9d992fb9c4c 100644 --- a/lib/sharing/ConsumeSharedRuntimeModule.js +++ b/lib/sharing/ConsumeSharedRuntimeModule.js @@ -121,8 +121,8 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { `var findLatestVersion = ${runtimeTemplate.basicFunction( "scope, key, eager", [ - "var versions = eager ? eagerOnly(scope[key]) : scope[key];", - `var key = Object.keys(versions).reduce(${runtimeTemplate.basicFunction( + "const versions = eager ? eagerOnly(scope[key]) : scope[key];", + `const key = Object.keys(versions).reduce(${runtimeTemplate.basicFunction( "a, b", ["return !a || versionLt(a, b) ? b : a;"] )}, 0);`, @@ -132,8 +132,8 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { `var findSatisfyingVersion = ${runtimeTemplate.basicFunction( "scope, key, requiredVersion, eager", [ - "var versions = eager ? eagerOnly(scope[key]) : scope[key];", - `var key = Object.keys(versions).reduce(${runtimeTemplate.basicFunction( + "const versions = eager ? eagerOnly(scope[key]) : scope[key];", + `const key = Object.keys(versions).reduce(${runtimeTemplate.basicFunction( "a, b", [ "if (!satisfy(requiredVersion, b)) return a;", @@ -146,7 +146,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { `var findSingletonVersionKey = ${runtimeTemplate.basicFunction( "scope, key, eager", [ - "var versions = eager ? eagerOnly(scope[key]) : scope[key];", + "const versions = eager ? eagerOnly(scope[key]) : scope[key];", `return Object.keys(versions).reduce(${runtimeTemplate.basicFunction( "a, b", ["return !a || (!versions[a].loaded && versionLt(a, b)) ? b : a;"] @@ -162,7 +162,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { `var getInvalidVersionMessage = ${runtimeTemplate.basicFunction( "scope, scopeName, key, requiredVersion, eager", [ - "var versions = scope[key];", + "const versions = scope[key];", 'return "No satisfying version (" + rangeToString(requiredVersion) + ")" + (eager ? " for eager consumption" : "") + " of shared module " + key + " found in shared scope " + scopeName + ".\\n" +', `\t"Available versions: " + Object.keys(versions).map(${runtimeTemplate.basicFunction( "key", @@ -187,7 +187,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { Template.asString([ "function(scopeName, key, eager, c, d) {", Template.indent([ - `var promise = ${RuntimeGlobals.initializeSharing}(scopeName);`, + `const promise = ${RuntimeGlobals.initializeSharing}(scopeName);`, // if we require eager shared, we expect it to be already loaded before it requested, no need to wait the whole scope loaded. "if (promise && promise.then && !eager) { ", Template.indent([ @@ -216,7 +216,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { "scopeName, scope, key, eager, requiredVersion, fallback", [ "if (!exists(scope, key)) return useFallback(scopeName, key, fallback);", - "var satisfyingVersion = findSatisfyingVersion(scope, key, requiredVersion, eager);", + "const satisfyingVersion = findSatisfyingVersion(scope, key, requiredVersion, eager);", "if (satisfyingVersion) return get(satisfyingVersion);", "warn(getInvalidVersionMessage(scope, scopeName, key, requiredVersion, eager))", "return get(findLatestVersion(scope, key, eager));" @@ -226,7 +226,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { "scopeName, scope, key, eager, requiredVersion, fallback", [ "if (!exists(scope, key)) return useFallback(scopeName, key, fallback);", - "var satisfyingVersion = findSatisfyingVersion(scope, key, requiredVersion, eager);", + "const satisfyingVersion = findSatisfyingVersion(scope, key, requiredVersion, eager);", "if (satisfyingVersion) return get(satisfyingVersion);", "if (fallback) return fallback();", "fail(getInvalidVersionMessage(scope, scopeName, key, requiredVersion, eager));" @@ -236,7 +236,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { "scopeName, scope, key, eager, fallback", [ "if (!exists(scope, key)) return useFallback(scopeName, key, fallback);", - "var version = findSingletonVersionKey(scope, key, eager);", + "const version = findSingletonVersionKey(scope, key, eager);", "return get(scope[key][version]);" ] )});`, @@ -244,7 +244,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { "scopeName, scope, key, eager, requiredVersion, fallback", [ "if (!exists(scope, key)) return useFallback(scopeName, key, fallback);", - "var version = findSingletonVersionKey(scope, key, eager);", + "const version = findSingletonVersionKey(scope, key, eager);", "if (!satisfy(requiredVersion, version)) {", Template.indent([ "warn(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion));" @@ -257,7 +257,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { "scopeName, scope, key, eager, requiredVersion, fallback", [ "if (!exists(scope, key)) return useFallback(scopeName, key, fallback);", - "var version = findSingletonVersionKey(scope, key, eager);", + "const version = findSingletonVersionKey(scope, key, eager);", "if (!satisfy(requiredVersion, version)) {", Template.indent([ "fail(getInvalidSingletonVersionMessage(scope, key, version, requiredVersion));" @@ -266,7 +266,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { "return get(scope[key][version]);" ] )});`, - "var installedModules = {};", + "const installedModules = {};", "var moduleToHandlerMapping = {", Template.indent( Array.from( @@ -278,7 +278,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { initialConsumes.length > 0 ? Template.asString([ - `var initialConsumes = ${JSON.stringify(initialConsumes)};`, + `const initialConsumes = ${JSON.stringify(initialConsumes)};`, `initialConsumes.forEach(${runtimeTemplate.basicFunction("id", [ `${ RuntimeGlobals.moduleFactories @@ -286,7 +286,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { "// Handle case when module is used sync", "installedModules[id] = 0;", `delete ${RuntimeGlobals.moduleCache}[id];`, - "var factory = moduleToHandlerMapping[id]();", + "const factory = moduleToHandlerMapping[id]();", 'if(typeof factory !== "function") throw new Error("Shared module is not available for eager consumption: " + id);', "module.exports = factory();" ])}` @@ -300,7 +300,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { null, "\t" )};`, - "var startedInstallModules = {};", + "const startedInstallModules = {};", `${ RuntimeGlobals.ensureChunkHandlers }.consumes = ${runtimeTemplate.basicFunction("chunkId, promises", [ @@ -335,7 +335,7 @@ class ConsumeSharedRuntimeModule extends RuntimeModule { ])};`, "try {", Template.indent([ - "var promise = moduleToHandlerMapping[id]();", + "const promise = moduleToHandlerMapping[id]();", "if(promise.then) {", Template.indent( "promises.push(installedModules[id] = promise.then(onFactory)['catch'](onError));" diff --git a/lib/sharing/ShareRuntimeModule.js b/lib/sharing/ShareRuntimeModule.js index 3e8d524d32c..a1918fca552 100644 --- a/lib/sharing/ShareRuntimeModule.js +++ b/lib/sharing/ShareRuntimeModule.js @@ -70,14 +70,14 @@ class ShareRuntimeModule extends RuntimeModule { } return Template.asString([ `${RuntimeGlobals.shareScopeMap} = {};`, - "var initPromises = {};", - "var initTokens = {};", + "const initPromises = {};", + "const initTokens = {};", `${RuntimeGlobals.initializeSharing} = ${runtimeTemplate.basicFunction( "name, initScope", [ "if(!initScope) initScope = [];", "// handling circular init calls", - "var initToken = initTokens[name];", + "let initToken = initTokens[name];", "if(!initToken) initToken = initTokens[name] = {};", "if(initScope.indexOf(initToken) >= 0) return;", "initScope.push(initToken);", @@ -86,43 +86,43 @@ class ShareRuntimeModule extends RuntimeModule { "// creates a new share scope if needed", `if(!${RuntimeGlobals.hasOwnProperty}(${RuntimeGlobals.shareScopeMap}, name)) ${RuntimeGlobals.shareScopeMap}[name] = {};`, "// runs all init snippets from all modules reachable", - `var scope = ${RuntimeGlobals.shareScopeMap}[name];`, - `var warn = ${ + `const scope = ${RuntimeGlobals.shareScopeMap}[name];`, + `const warn = ${ ignoreBrowserWarnings ? runtimeTemplate.basicFunction("", "") : runtimeTemplate.basicFunction("msg", [ 'if (typeof console !== "undefined" && console.warn) console.warn(msg);' ]) };`, - `var uniqueName = ${JSON.stringify(uniqueName || undefined)};`, - `var register = ${runtimeTemplate.basicFunction( + `const uniqueName = ${JSON.stringify(uniqueName || undefined)};`, + `const register = ${runtimeTemplate.basicFunction( "name, version, factory, eager", [ - "var versions = scope[name] = scope[name] || {};", - "var activeVersion = versions[version];", + "const versions = scope[name] = scope[name] || {};", + "const activeVersion = versions[version];", "if(!activeVersion || (!activeVersion.loaded && (!eager != !activeVersion.eager ? eager : uniqueName > activeVersion.from))) versions[version] = { get: factory, from: uniqueName, eager: !!eager };" ] )};`, - `var initExternal = ${runtimeTemplate.basicFunction("id", [ - `var handleError = ${runtimeTemplate.expressionFunction( + `const initExternal = ${runtimeTemplate.basicFunction("id", [ + `const handleError = ${runtimeTemplate.expressionFunction( 'warn("Initialization of sharing external failed: " + err)', "err" )};`, "try {", Template.indent([ - `var module = ${RuntimeGlobals.require}(id);`, + `const module = ${RuntimeGlobals.require}(id);`, "if(!module) return;", - `var initFn = ${runtimeTemplate.returningFunction( + `const initFn = ${runtimeTemplate.returningFunction( `module && module.init && module.init(${RuntimeGlobals.shareScopeMap}[name], initScope)`, "module" )}`, "if(module.then) return promises.push(module.then(initFn, handleError));", - "var initResult = initFn(module);", + "const initResult = initFn(module);", "if(initResult && initResult.then) return promises.push(initResult['catch'](handleError));" ]), "} catch(err) { handleError(err); }" ])}`, - "var promises = [];", + "const promises = [];", "switch(name) {", ...[...initCodePerScope] .sort(([a], [b]) => compareStrings(a, b)) diff --git a/lib/util/semver.js b/lib/util/semver.js index c026651bf7c..949b58e6e0b 100644 --- a/lib/util/semver.js +++ b/lib/util/semver.js @@ -265,8 +265,8 @@ module.exports.parseRange = (str) => { /** @type {SemVerRangeItem[][]} */ const items = []; const r = /[-0-9A-Za-z]\s+/g; - var start = 0; - var match; + let start = 0; + let match; while ((match = r.exec(str))) { const end = match.index + 1; items.push( diff --git a/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js b/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js index 4f683dbb46c..be352f6c008 100644 --- a/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js +++ b/lib/wasm-async/AsyncWasmLoadingRuntimeModule.js @@ -85,8 +85,8 @@ class AsyncWasmLoadingRuntimeModule extends RuntimeModule { this.generateBeforeLoadBinaryCode ? this.generateBeforeLoadBinaryCode(wasmModuleSrcPath) : "", - `var req = ${loader};`, - `var fallback = ${runtimeTemplate.returningFunction( + `const req = ${loader};`, + `const fallback = ${runtimeTemplate.returningFunction( Template.asString(["req", Template.indent(fallback)]) )};`, concat( diff --git a/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js b/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js index 5e5eefd9be5..37e538879cb 100644 --- a/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js +++ b/lib/wasm-sync/WasmChunkLoadingRuntimeModule.js @@ -338,20 +338,20 @@ class WasmChunkLoadingRuntimeModule extends RuntimeModule { `${fn}.wasm = function(chunkId, promises) {`, Template.indent([ "", - "var wasmModules = wasmModuleMap[chunkId] || [];", + "const wasmModules = wasmModuleMap[chunkId] || [];", "", "wasmModules.forEach(function(wasmModuleId, idx) {", Template.indent([ - "var installedWasmModuleData = installedWasmModules[wasmModuleId];", + "const installedWasmModuleData = installedWasmModules[wasmModuleId];", "", '// a Promise means "currently loading" or "already loaded".', "if(installedWasmModuleData)", Template.indent(["promises.push(installedWasmModuleData);"]), "else {", Template.indent([ - "var importObject = wasmImportObjects[wasmModuleId]();", - `var req = ${this.generateLoadBinaryCode(wasmModuleSrcPath)};`, - "var promise;", + "const importObject = wasmImportObjects[wasmModuleId]();", + `const req = ${this.generateLoadBinaryCode(wasmModuleSrcPath)};`, + "let promise;", this.supportsStreaming ? Template.asString([ "if(importObject && typeof importObject.then === 'function' && typeof WebAssembly.compileStreaming === 'function') {", @@ -374,7 +374,7 @@ class WasmChunkLoadingRuntimeModule extends RuntimeModule { : Template.asString([ "if(importObject && typeof importObject.then === 'function') {", Template.indent([ - "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", + "const bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", "promise = Promise.all([", Template.indent([ "bytesPromise.then(function(bytes) { return WebAssembly.compile(bytes); }),", @@ -391,7 +391,7 @@ class WasmChunkLoadingRuntimeModule extends RuntimeModule { ]), "} else {", Template.indent([ - "var bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", + "const bytesPromise = req.then(function(x) { return x.arrayBuffer(); });", "promise = bytesPromise.then(function(bytes) {", Template.indent([ `return WebAssembly.instantiate(bytes, ${createImportObject( diff --git a/lib/wasm-sync/WebAssemblyJavascriptGenerator.js b/lib/wasm-sync/WebAssemblyJavascriptGenerator.js index f5615dfeeb3..353a4281584 100644 --- a/lib/wasm-sync/WebAssemblyJavascriptGenerator.js +++ b/lib/wasm-sync/WebAssemblyJavascriptGenerator.js @@ -190,7 +190,7 @@ class WebAssemblyJavascriptGenerator extends Generator { [ '"use strict";', "// Instantiate WebAssembly module", - `var wasmExports = ${RuntimeGlobals.wasmInstances}[${module.moduleArgument}.id];`, + `const wasmExports = ${RuntimeGlobals.wasmInstances}[${module.moduleArgument}.id];`, exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused ? `${RuntimeGlobals.makeNamespaceObject}(${module.exportsArgument});` diff --git a/lib/web/JsonpChunkLoadingRuntimeModule.js b/lib/web/JsonpChunkLoadingRuntimeModule.js index d043dd93e8a..4fe19f20333 100644 --- a/lib/web/JsonpChunkLoadingRuntimeModule.js +++ b/lib/web/JsonpChunkLoadingRuntimeModule.js @@ -168,7 +168,7 @@ class JsonpChunkLoadingRuntimeModule extends RuntimeModule { : `if(${hasJsMatcher("chunkId")}) {`, Template.indent([ "// setup Promise in chunk cache", - `var promise = new Promise(${runtimeTemplate.expressionFunction( + `const promise = new Promise(${runtimeTemplate.expressionFunction( "installedChunkData = installedChunks[chunkId] = [resolve, reject]", "resolve, reject" )});`, @@ -177,7 +177,7 @@ class JsonpChunkLoadingRuntimeModule extends RuntimeModule { "// start chunk loading", `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`, "// create error before stack unwound to get useful stacktrace later", - "var error = new Error();", + "const error = new Error();", `var loadingEnded = ${runtimeTemplate.basicFunction( "event", [ @@ -320,7 +320,7 @@ class JsonpChunkLoadingRuntimeModule extends RuntimeModule { "// start update chunk loading", `var url = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId);`, "// create error before stack unwound to get useful stacktrace later", - "var error = new Error();", + "const error = new Error();", `var loadingEnded = ${runtimeTemplate.basicFunction("event", [ "if(waitingUpdateResolves[chunkId]) {", Template.indent([ diff --git a/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js b/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js index 0a0699744ae..61f4a4bba55 100644 --- a/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js +++ b/lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js @@ -165,8 +165,8 @@ class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { )};` : "", "", - `var chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`, - "var parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);", + `const chunkLoadingGlobal = ${chunkLoadingGlobalExpr} = ${chunkLoadingGlobalExpr} || [];`, + "const parentChunkLoadingFunction = chunkLoadingGlobal.push.bind(chunkLoadingGlobal);", "chunkLoadingGlobal.push = installChunk;" ]) : "// no chunk loading", @@ -175,7 +175,7 @@ class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule { ? Template.asString([ "function loadUpdateChunk(chunkId, updatedModulesList) {", Template.indent([ - "var success = false;", + "let success = false;", `${globalObject}[${JSON.stringify( compilation.outputOptions.hotUpdateGlobal )}] = ${runtimeTemplate.basicFunction("_, moreModules, runtime", [