From 423e89b2c75972d325a275f2b04824a43d75bd60 Mon Sep 17 00:00:00 2001 From: "alexander.akait" Date: Tue, 30 Jul 2024 23:09:42 +0300 Subject: [PATCH] style: improve style of code --- eslint.config.js | 19 +++++- lib/BannerPlugin.js | 2 +- lib/ChunkGraph.js | 4 +- lib/Compilation.js | 6 +- lib/ContextModule.js | 12 ++-- lib/ContextModuleFactory.js | 6 +- lib/DefinePlugin.js | 2 +- lib/DllReferencePlugin.js | 6 +- lib/ExportsInfo.js | 10 +-- lib/ExternalModule.js | 14 ++-- lib/FileSystemInfo.js | 8 +-- lib/HotModuleReplacementPlugin.js | 8 +-- lib/ModuleFilenameHelpers.js | 8 +-- lib/ModuleRestoreError.js | 2 +- lib/ModuleStoreError.js | 2 +- lib/MultiCompiler.js | 4 +- lib/NormalModule.js | 32 ++++----- lib/NormalModuleFactory.js | 20 +++--- lib/SourceMapDevToolPlugin.js | 14 ++-- lib/TemplatedPathPlugin.js | 4 +- lib/WebpackOptionsApply.js | 4 +- lib/buildChunkGraph.js | 12 ++-- lib/cache/IdleFileCachePlugin.js | 19 ++---- lib/cli.js | 10 +-- lib/config/defaults.js | 25 +++---- lib/css/CssExportsGenerator.js | 6 +- lib/css/CssModulesPlugin.js | 10 +-- lib/css/CssParser.js | 15 ++-- lib/css/walkCssTokens.js | 6 +- .../AMDDefineDependencyParserPlugin.js | 2 +- lib/dependencies/ContextDependencyHelpers.js | 8 +-- .../HarmonyImportSpecifierDependency.js | 2 +- lib/dependencies/ImportDependency.js | 2 +- lib/dependencies/ProvidedDependency.js | 2 +- lib/dependencies/WorkerPlugin.js | 8 +-- lib/esm/ModuleChunkFormatPlugin.js | 2 +- lib/javascript/BasicEvaluatedExpression.js | 2 +- lib/javascript/JavascriptModulesPlugin.js | 68 +++++++++---------- lib/javascript/JavascriptParser.js | 16 ++--- lib/javascript/JavascriptParserHelpers.js | 2 +- lib/json/JsonGenerator.js | 4 +- lib/library/AmdLibraryPlugin.js | 7 +- lib/library/AssignLibraryPlugin.js | 5 +- lib/library/JsonpLibraryPlugin.js | 3 +- lib/library/ModernModuleLibraryPlugin.js | 3 +- lib/library/ModuleLibraryPlugin.js | 3 +- lib/library/SystemLibraryPlugin.js | 5 +- lib/logging/runtime.js | 2 +- lib/optimize/AggressiveMergingPlugin.js | 2 +- lib/optimize/ConcatenatedModule.js | 30 ++++---- lib/optimize/ModuleConcatenationPlugin.js | 6 +- lib/optimize/RealContentHashPlugin.js | 2 +- lib/optimize/RemoveParentModulesPlugin.js | 4 +- lib/optimize/SplitChunksPlugin.js | 38 +++++------ lib/performance/SizeLimitsPlugin.js | 4 +- lib/serialization/BinaryMiddleware.js | 1 + lib/serialization/MapObjectSerializer.js | 2 +- lib/serialization/SetObjectSerializer.js | 2 +- lib/sharing/ConsumeSharedPlugin.js | 12 ++-- lib/sharing/utils.js | 2 +- lib/util/TupleSet.js | 4 +- lib/util/comparators.js | 4 +- lib/util/deterministicGrouping.js | 6 +- lib/util/smartGrouping.js | 4 +- setup/setup.js | 4 +- test/BinaryMiddleware.unittest.js | 2 +- test/ChangesAndRemovals.test.js | 3 +- test/ConfigTestCases.template.js | 12 ++-- test/ContextModuleFactory.unittest.js | 4 +- test/NormalModule.unittest.js | 2 +- test/TestCases.template.js | 6 +- test/helpers/FakeDocument.js | 4 +- test/helpers/expectWarningFactory.js | 2 +- test/helpers/warmup-webpack.js | 2 +- 74 files changed, 309 insertions(+), 291 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index 63f46e48b..8e0f6527a 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -75,7 +75,7 @@ module.exports = [ ecmaVersion: 2018, globals: { ...globals.node, - ...globals.es2015, + ...globals.es2018, WebAssembly: true } }, @@ -102,6 +102,14 @@ module.exports = [ ], "no-inner-declarations": "error", "no-loop-func": "off", + "prefer-const": [ + "error", + { + destructuring: "all", + ignoreReadBeforeAssign: true + } + ], + "object-shorthand": "error", "n/no-missing-require": ["error", { allowModules: ["webpack"] }], "n/no-unsupported-features/node-builtins": [ "error", @@ -167,6 +175,10 @@ module.exports = [ ...globals.browser, ...globals.es5 } + }, + rules: { + "prefer-const": "off", + "object-shorthand": "off" } }, { @@ -174,7 +186,7 @@ module.exports = [ languageOptions: { ecmaVersion: 2020, globals: { - ...globals.es2015 + ...globals.es2020 } } }, @@ -206,7 +218,8 @@ module.exports = [ { allowExperimental: true } - ] + ], + "object-shorthand": "off" } }, { diff --git a/lib/BannerPlugin.js b/lib/BannerPlugin.js index 7b2704941..7c3723be4 100644 --- a/lib/BannerPlugin.js +++ b/lib/BannerPlugin.js @@ -111,7 +111,7 @@ class BannerPlugin { const comment = compilation.getPath(banner, data); compilation.updateAsset(file, old => { - let cached = cache.get(old); + const cached = cache.get(old); if (!cached || cached.comment !== comment) { const source = options.footer ? new ConcatSource(old, "\n", comment) diff --git a/lib/ChunkGraph.js b/lib/ChunkGraph.js index 24af427d5..afed5f45a 100644 --- a/lib/ChunkGraph.js +++ b/lib/ChunkGraph.js @@ -159,7 +159,7 @@ const getModulesSize = modules => { * @returns {Record} the sizes of the modules */ const getModulesSizes = modules => { - let sizes = Object.create(null); + const sizes = Object.create(null); for (const module of modules) { for (const type of module.getSourceTypes()) { sizes[type] = (sizes[type] || 0) + module.size(type); @@ -916,7 +916,7 @@ class ChunkGraph { const cgcB = this._getChunkGraphChunk(chunkB); const allModules = new Set(cgcA.modules); for (const m of cgcB.modules) allModules.add(m); - let modulesSize = getModulesSize(allModules); + const modulesSize = getModulesSize(allModules); const chunkOverhead = typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; const entryChunkMultiplicator = diff --git a/lib/Compilation.js b/lib/Compilation.js index ddb0820d1..c60541efa 100644 --- a/lib/Compilation.js +++ b/lib/Compilation.js @@ -580,7 +580,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si if (options.stage) { throw new Error(errorMessage("it's using the 'stage' option")); } - return { ...options, stage: stage }; + return { ...options, stage }; }; return createFakeHook( { @@ -2066,7 +2066,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si : originModule ? originModule.context : this.compiler.context, - dependencies: dependencies + dependencies }, (err, result) => { if (result) { @@ -4242,7 +4242,7 @@ Or do you want to use the entrypoints '${name}' and '${runtime}' independently o } // If there are still remaining references we have cycles and want to create a warning if (remaining > 0) { - let circularRuntimeChunkInfo = []; + const circularRuntimeChunkInfo = []; for (const info of runtimeChunksMap.values()) { if (info.remaining !== 0) { circularRuntimeChunkInfo.push(info); diff --git a/lib/ContextModule.js b/lib/ContextModule.js index 01ae0f322..1da14c7c8 100644 --- a/lib/ContextModule.js +++ b/lib/ContextModule.js @@ -534,8 +534,8 @@ class ContextModule extends Module { this.context ? [this.context] : typeof this.options.resource === "string" - ? [this.options.resource] - : /** @type {string[]} */ (this.options.resource), + ? [this.options.resource] + : /** @type {string[]} */ (this.options.resource), null, SNAPSHOT_OPTIONS, (err, snapshot) => { @@ -950,9 +950,9 @@ module.exports = webpackAsyncContext;`; /** @type {ContextElementDependency} */ (block.dependencies[0]); return { - dependency: dependency, + dependency, module: /** @type {Module} */ (moduleGraph.getModule(dependency)), - block: block, + block, userRequest: dependency.userRequest, chunks: undefined }; @@ -994,8 +994,8 @@ module.exports = webpackAsyncContext;`; const requestPrefix = hasNoChunk ? "Promise.resolve()" : hasMultipleOrNoChunks - ? `Promise.all(ids.slice(${chunksStartPosition}).map(${RuntimeGlobals.ensureChunk}))` - : `${RuntimeGlobals.ensureChunk}(ids[${chunksStartPosition}])`; + ? `Promise.all(ids.slice(${chunksStartPosition}).map(${RuntimeGlobals.ensureChunk}))` + : `${RuntimeGlobals.ensureChunk}(ids[${chunksStartPosition}])`; const returnModuleObject = this.getReturnModuleObjectSource( fakeMap, true, diff --git a/lib/ContextModuleFactory.js b/lib/ContextModuleFactory.js index f66de4e46..a54d0af31 100644 --- a/lib/ContextModuleFactory.js +++ b/lib/ContextModuleFactory.js @@ -93,8 +93,8 @@ module.exports = class ContextModuleFactory extends ModuleFactory { const contextDependencies = new LazySet(); this.hooks.beforeResolve.callAsync( { - context: context, - dependencies: dependencies, + context, + dependencies, layer: data.contextInfo.issuerLayer, resolveOptions, fileDependencies, @@ -160,7 +160,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory { resolveOptions || EMPTY_RESOLVE_OPTIONS, "dependencyType", dependencies[0].category - ) + ) : resolveOptions ); const loaderResolver = this.resolverFactory.get("loader"); diff --git a/lib/DefinePlugin.js b/lib/DefinePlugin.js index b8c30f726..ce283cda6 100644 --- a/lib/DefinePlugin.js +++ b/lib/DefinePlugin.js @@ -146,7 +146,7 @@ const stringifyObj = ( objKeys ) => { let code; - let arr = Array.isArray(obj); + const arr = Array.isArray(obj); if (arr) { code = `[${ /** @type {any[]} */ (obj) diff --git a/lib/DllReferencePlugin.js b/lib/DllReferencePlugin.js index 674a9457c..8d8724f83 100644 --- a/lib/DllReferencePlugin.js +++ b/lib/DllReferencePlugin.js @@ -101,7 +101,7 @@ class DllReferencePlugin { let content = "content" in this.options ? this.options.content : undefined; if ("manifest" in this.options) { - let manifestParameter = this.options.manifest; + const manifestParameter = this.options.manifest; let manifest; if (typeof manifestParameter === "string") { const data = this._compilationData.get(params); @@ -130,7 +130,7 @@ class DllReferencePlugin { normalModuleFactory ); new DelegatedModuleFactoryPlugin({ - source: source, + source, type: this.options.type, scope: this.options.scope, context: this.options.context || compiler.options.context, @@ -144,7 +144,7 @@ class DllReferencePlugin { "DllReferencePlugin", (compilation, params) => { if ("manifest" in this.options) { - let manifest = this.options.manifest; + const manifest = this.options.manifest; if (typeof manifest === "string") { const data = this._compilationData.get(params); // If there was an error parsing the manifest file, add the diff --git a/lib/ExportsInfo.js b/lib/ExportsInfo.js index 634240c31..cff31215b 100644 --- a/lib/ExportsInfo.js +++ b/lib/ExportsInfo.js @@ -662,13 +662,13 @@ class ExportsInfo { getUsed(name, runtime) { if (Array.isArray(name)) { if (name.length === 0) return this.otherExportsInfo.getUsed(runtime); - let info = this.getReadOnlyExportInfo(name[0]); + const info = this.getReadOnlyExportInfo(name[0]); if (info.exportsInfo && name.length > 1) { return info.exportsInfo.getUsed(name.slice(1), runtime); } return info.getUsed(runtime); } - let info = this.getReadOnlyExportInfo(name); + const info = this.getReadOnlyExportInfo(name); return info.getUsed(runtime); } @@ -684,7 +684,7 @@ class ExportsInfo { if (!this.isUsed(runtime)) return false; return name; } - let info = this.getReadOnlyExportInfo(name[0]); + const info = this.getReadOnlyExportInfo(name[0]); const x = info.getUsedName(name[0], runtime); if (x === false) return false; const arr = x === name[0] && name.length === 1 ? name : [x]; @@ -702,7 +702,7 @@ class ExportsInfo { return arr.concat(name.slice(1)); } } else { - let info = this.getReadOnlyExportInfo(name); + const info = this.getReadOnlyExportInfo(name); const usedName = info.getUsedName(name, runtime); return usedName; } @@ -1260,7 +1260,7 @@ class ExportInfo { */ _findTarget(moduleGraph, validTargetModuleFilter, alreadyVisited) { if (!this._target || this._target.size === 0) return undefined; - let rawTarget = this._getMaxTarget().values().next().value; + const rawTarget = this._getMaxTarget().values().next().value; if (!rawTarget) return undefined; /** @type {{ module: Module, export: string[] | undefined }} */ let target = { diff --git a/lib/ExternalModule.js b/lib/ExternalModule.js index b981fb0a9..76902288c 100644 --- a/lib/ExternalModule.js +++ b/lib/ExternalModule.js @@ -175,7 +175,7 @@ const getSourceForImportExternal = ( ? `, { assert: ${JSON.stringify( dependencyMeta.attributes, importAssertionReplacer - )} }` + )} }` : `, { with: ${JSON.stringify(dependencyMeta.attributes)} }` : ""; if (!Array.isArray(moduleAndSpecifiers)) { @@ -244,7 +244,7 @@ class ModuleExternalInitFragment extends InitFragment { ? ` assert ${JSON.stringify( dependencyMeta.attributes, importAssertionReplacer - )}` + )}` : ` with ${JSON.stringify(dependencyMeta.attributes)}` : "" };\n`, @@ -353,17 +353,17 @@ const getSourceForModuleExternal = ( runtime, runtimeTemplate ); - let expression = moduleRemapping || baseAccess; + const expression = moduleRemapping || baseAccess; return { expression, init: moduleRemapping ? `var x = ${runtimeTemplate.basicFunction( "y", `var x = {}; ${RuntimeGlobals.definePropertyGetters}(x, y); return x` - )} \nvar y = ${runtimeTemplate.returningFunction( + )} \nvar y = ${runtimeTemplate.returningFunction( runtimeTemplate.returningFunction("x"), "x" - )}` + )}` : undefined, runtimeRequirements: moduleRemapping ? RUNTIME_REQUIREMENTS_FOR_MODULE @@ -443,7 +443,7 @@ const getSourceForAmdOrUmdExternal = ( externalVariable, Array.isArray(request) ? request.join(".") : request, runtimeTemplate - ) + ) : undefined, expression: externalVariable }; @@ -703,7 +703,7 @@ class ExternalModule extends Module { /** @type {string} */ (runtimeTemplate.outputOptions.importMetaName), runtimeTemplate.supportNodePrefixForCoreModules() - ) + ) : getSourceForCommonJsExternal(request); case "amd": case "amd-require": diff --git a/lib/FileSystemInfo.js b/lib/FileSystemInfo.js index 851b38327..dbae0f0a9 100644 --- a/lib/FileSystemInfo.js +++ b/lib/FileSystemInfo.js @@ -1670,7 +1670,7 @@ class FileSystemInfo { const module = require.cache[path]; if (module && Array.isArray(module.children)) { children: for (const child of module.children) { - let childPath = child.filename; + const childPath = child.filename; if (childPath) { push({ type: RBDT_FILE, @@ -1682,7 +1682,7 @@ class FileSystemInfo { const context = dirname(this.fs, path); for (const modulePath of module.paths) { if (childPath.startsWith(modulePath)) { - let subPath = childPath.slice(modulePath.length + 1); + const subPath = childPath.slice(modulePath.length + 1); const packageMatch = /^(@[^\\/]+[\\/])[^\\/]+/.exec( subPath ); @@ -1755,7 +1755,7 @@ class FileSystemInfo { ); } else if (imp.d > -1) { // import() - let expr = source.substring(imp.s, imp.e).trim(); + const expr = source.substring(imp.s, imp.e).trim(); dependency = parseString(expr); } else { // e.g. import.meta @@ -3388,7 +3388,7 @@ class FileSystemInfo { : { ...timestamp, ...hash - }; + }; this._contextTshs.set(path, result); callback(null, result); }; diff --git a/lib/HotModuleReplacementPlugin.js b/lib/HotModuleReplacementPlugin.js index 3f64dc504..f1ff3397c 100644 --- a/lib/HotModuleReplacementPlugin.js +++ b/lib/HotModuleReplacementPlugin.js @@ -142,7 +142,7 @@ class HotModuleReplacementPlugin { (arg.items).filter(param => param.isString()); } /** @type {string[]} */ - let requests = []; + const requests = []; if (params.length > 0) { params.forEach((param, idx) => { const request = /** @type {string} */ (param.string); @@ -500,7 +500,7 @@ class HotModuleReplacementPlugin { : compilation.codeGenerationResults.getHash( module, chunk.runtime - ); + ); if (records.chunkModuleHashes[key] !== hash) { updatedModules.add(module, chunk); } @@ -629,7 +629,7 @@ class HotModuleReplacementPlugin { : compilation.codeGenerationResults.getHash( module, newRuntime - ); + ); if (hash !== oldHash) { if (module.type === WEBPACK_MODULE_TYPE_RUNTIME) { newRuntimeModules = newRuntimeModules || []; @@ -798,7 +798,7 @@ To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename Array.from(removedModules, m => chunkGraph.getModuleId(m) ) - ) + ) }; const source = new RawSource(JSON.stringify(hotUpdateMainJson)); diff --git a/lib/ModuleFilenameHelpers.js b/lib/ModuleFilenameHelpers.js index a67bf375e..7c8338a01 100644 --- a/lib/ModuleFilenameHelpers.js +++ b/lib/ModuleFilenameHelpers.js @@ -163,7 +163,7 @@ ModuleFilenameHelpers.createFilename = ( ? options : { moduleFilenameTemplate: options - }) + }) }; let absoluteResourcePath; @@ -212,9 +212,9 @@ ModuleFilenameHelpers.createFilename = ( if (typeof opts.moduleFilenameTemplate === "function") { return opts.moduleFilenameTemplate( lazyObject({ - identifier: identifier, - shortIdentifier: shortIdentifier, - resource: resource, + identifier, + shortIdentifier, + resource, resourcePath: memoize(resourcePath), absoluteResourcePath: memoize(absoluteResourcePath), loaders: memoize(loaders), diff --git a/lib/ModuleRestoreError.js b/lib/ModuleRestoreError.js index 449e617d5..2570862d4 100644 --- a/lib/ModuleRestoreError.js +++ b/lib/ModuleRestoreError.js @@ -17,7 +17,7 @@ class ModuleRestoreError extends WebpackError { constructor(module, err) { let message = "Module restore failed: "; /** @type {string | undefined} */ - let details = undefined; + const details = undefined; if (err !== null && typeof err === "object") { if (typeof err.stack === "string" && err.stack) { const stack = err.stack; diff --git a/lib/ModuleStoreError.js b/lib/ModuleStoreError.js index e00e1cbbf..26ca0c8b5 100644 --- a/lib/ModuleStoreError.js +++ b/lib/ModuleStoreError.js @@ -17,7 +17,7 @@ class ModuleStoreError extends WebpackError { constructor(module, err) { let message = "Module storing failed: "; /** @type {string | undefined} */ - let details = undefined; + const details = undefined; if (err !== null && typeof err === "object") { if (typeof err.stack === "string" && err.stack) { const stack = err.stack; diff --git a/lib/MultiCompiler.js b/lib/MultiCompiler.js index 650fb31fa..e09c8ba96 100644 --- a/lib/MultiCompiler.js +++ b/lib/MultiCompiler.js @@ -340,8 +340,8 @@ module.exports = class MultiCompiler { * @returns {Compiler[]} compilers */ const getReadyCompilers = () => { - let readyCompilers = []; - let list = remainingCompilers; + const readyCompilers = []; + const list = remainingCompilers; remainingCompilers = []; for (const c of list) { const dependencies = this.dependencies.get(c); diff --git a/lib/NormalModule.js b/lib/NormalModule.js index 900626177..7dece6fd5 100644 --- a/lib/NormalModule.js +++ b/lib/NormalModule.js @@ -142,14 +142,14 @@ const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => { const mapper = !sourceRoot ? source => source : sourceRoot.endsWith("/") - ? source => - source.startsWith("/") - ? `${sourceRoot.slice(0, -1)}${source}` - : `${sourceRoot}${source}` - : source => - source.startsWith("/") - ? `${sourceRoot}${source}` - : `${sourceRoot}/${source}`; + ? source => + source.startsWith("/") + ? `${sourceRoot.slice(0, -1)}${source}` + : `${sourceRoot}${source}` + : source => + source.startsWith("/") + ? `${sourceRoot}${source}` + : `${sourceRoot}/${source}`; const newSources = sourceMap.sources.map(source => contextifySourceUrl(context, mapper(source), associatedObjectForCache) ); @@ -743,7 +743,7 @@ class NormalModule extends Module { _module: this, _compilation: compilation, _compiler: compilation.compiler, - fs: fs + fs }; Object.assign(loaderContext, options.loader); @@ -859,7 +859,7 @@ class NormalModule extends Module { currentLoader ? compilation.runtimeTemplate.requestShortener.shorten( currentLoader.loader - ) + ) : "unknown" }) didn't return a Buffer or String` ); @@ -1161,10 +1161,10 @@ class NormalModule extends Module { if (absolute !== dep && ABSOLUTE_PATH_REGEX.test(absolute)) { (depWithoutGlob !== dep ? /** @type {NonNullable} */ - ( + ( /** @type {BuildInfo} */ (this.buildInfo) .contextDependencies - ) + ) : deps ).add(absolute); } @@ -1241,8 +1241,8 @@ class NormalModule extends Module { source, current: this, module: this, - compilation: compilation, - options: options + compilation, + options }); } catch (e) { handleParseError(/** @type {Error} */ (e)); @@ -1357,7 +1357,7 @@ class NormalModule extends Module { const source = this.error ? new RawSource( "throw new Error(" + JSON.stringify(this.error.message) + ");" - ) + ) : /** @type {Generator} */ (this.generator).generate(this, { dependencyTemplates, runtimeTemplate, @@ -1369,7 +1369,7 @@ class NormalModule extends Module { codeGenerationResults, getData, type - }); + }); if (source) { sources.set(type, new CachedSource(source)); diff --git a/lib/NormalModuleFactory.js b/lib/NormalModuleFactory.js index 1cf3ac0b2..eca339b28 100644 --- a/lib/NormalModuleFactory.js +++ b/lib/NormalModuleFactory.js @@ -479,8 +479,8 @@ class NormalModuleFactory extends ModuleFactory { noPreAutoLoaders || noPrePostAutoLoaders ? 2 : noAutoLoaders - ? 1 - : 0 + ? 1 + : 0 ) .split(/!+/); unresolvedResource = /** @type {string} */ (rawElements.pop()); @@ -652,7 +652,7 @@ class NormalModuleFactory extends ModuleFactory { } for (const loader of /** @type {LoaderItem[]} */ (preLoaders)) allLoaders.push(loader); - let type = /** @type {string} */ (settings.type); + const type = /** @type {string} */ (settings.type); const resolveOptions = settings.resolve; const layer = settings.layer; if (layer !== undefined && !layers) { @@ -763,7 +763,7 @@ class NormalModuleFactory extends ModuleFactory { resolveOptions || EMPTY_RESOLVE_OPTIONS, "dependencyType", dependencyType - ) + ) : resolveOptions ); this.resolveResource( @@ -1178,12 +1178,12 @@ If changing the source code is not an option there is also a resolve options cal const type = /\.mjs$/i.test(parsedResult.path) ? "module" : /\.cjs$/i.test(parsedResult.path) - ? "commonjs" - : /** @type {ResolveRequest} */ - (resolveRequest).descriptionFileData === undefined - ? undefined - : /** @type {ResolveRequest} */ - (resolveRequest).descriptionFileData.type; + ? "commonjs" + : /** @type {ResolveRequest} */ + (resolveRequest).descriptionFileData === undefined + ? undefined + : /** @type {ResolveRequest} */ + (resolveRequest).descriptionFileData.type; const resolved = { loader: parsedResult.path, type, diff --git a/lib/SourceMapDevToolPlugin.js b/lib/SourceMapDevToolPlugin.js index 613603825..c66ef9d65 100644 --- a/lib/SourceMapDevToolPlugin.js +++ b/lib/SourceMapDevToolPlugin.js @@ -317,8 +317,8 @@ class SourceMapDevToolPlugin { ModuleFilenameHelpers.createFilename( module, { - moduleFilenameTemplate: moduleFilenameTemplate, - namespace: namespace + moduleFilenameTemplate, + namespace }, { requestShortener, @@ -382,7 +382,7 @@ class SourceMapDevToolPlugin { module, { moduleFilenameTemplate: fallbackModuleFilenameTemplate, - namespace: namespace + namespace }, { requestShortener, @@ -457,7 +457,7 @@ class SourceMapDevToolPlugin { /** @type {string | false | (function(PathData, AssetInfo=): string)} */ let currentSourceMappingURLComment = sourceMappingURLComment; - let cssExtensionDetected = + const cssExtensionDetected = CSS_EXTENSION_DETECT_REGEXP.test(file); resetRegexpState(CSS_EXTENSION_DETECT_REGEXP); if ( @@ -473,7 +473,7 @@ class SourceMapDevToolPlugin { } const sourceMapString = JSON.stringify(sourceMap); if (sourceMapFilename) { - let filename = file; + const filename = file; const sourceMapContentHash = usesContentHash && /** @type {string} */ ( @@ -488,7 +488,7 @@ class SourceMapDevToolPlugin { outputFs, `/${options.fileContext}`, `/${filename}` - ) + ) : filename, contentHash: sourceMapContentHash }; @@ -503,7 +503,7 @@ class SourceMapDevToolPlugin { outputFs, dirname(outputFs, `/${file}`), `/${sourceMapFile}` - ); + ); /** @type {Source} */ let asset = new RawSource(source); if (currentSourceMappingURLComment !== false) { diff --git a/lib/TemplatedPathPlugin.js b/lib/TemplatedPathPlugin.js index a6febf2df..4ca6b51e8 100644 --- a/lib/TemplatedPathPlugin.js +++ b/lib/TemplatedPathPlugin.js @@ -155,7 +155,7 @@ const replacePathVariables = (path, data, assetInfo) => { // [ext] - .js if (typeof data.filename === "string") { // check that filename is data uri - let match = data.filename.match(/^data:([^;,]+)/); + const match = data.filename.match(/^data:([^;,]+)/); if (match) { const ext = mime.extension(match[1]); const emptyReplacer = replacer("", true); @@ -302,7 +302,7 @@ const replacePathVariables = (path, data, assetInfo) => { ? /** @type {ChunkGraph} */ (chunkGraph).getRenderedModuleHash( module, data.runtime - ) + ) : module.hash ), "hashWithLength" in module ? module.hashWithLength : undefined, diff --git a/lib/WebpackOptionsApply.js b/lib/WebpackOptionsApply.js index 3396462d1..46d4b6646 100644 --- a/lib/WebpackOptionsApply.js +++ b/lib/WebpackOptionsApply.js @@ -259,7 +259,7 @@ class WebpackOptionsApply extends OptionsApply { append: hidden ? false : undefined, module: moduleMaps ? true : cheap ? false : true, columns: cheap ? false : true, - noSources: noSources, + noSources, namespace: options.output.devtoolNamespace }).apply(compiler); } else if (options.devtool.includes("eval")) { @@ -336,7 +336,7 @@ class WebpackOptionsApply extends OptionsApply { options.externalsPresets.node ? "node" : "web" }.js` ) - }), + }), entries: !lazyOptions || lazyOptions.entries !== false, imports: !lazyOptions || lazyOptions.imports !== false, test: (lazyOptions && lazyOptions.test) || undefined diff --git a/lib/buildChunkGraph.js b/lib/buildChunkGraph.js index 129ed1639..e0bd85b80 100644 --- a/lib/buildChunkGraph.js +++ b/lib/buildChunkGraph.js @@ -330,12 +330,12 @@ const visitModules = ( let statConnectedChunkGroups = 0; let statProcessedChunkGroupsForMerging = 0; let statMergedAvailableModuleSets = 0; - let statForkedAvailableModules = 0; - let statForkedAvailableModulesCount = 0; - let statForkedAvailableModulesCountPlus = 0; - let statForkedMergedModulesCount = 0; - let statForkedMergedModulesCountPlus = 0; - let statForkedResultModulesCount = 0; + const statForkedAvailableModules = 0; + const statForkedAvailableModulesCount = 0; + const statForkedAvailableModulesCountPlus = 0; + const statForkedMergedModulesCount = 0; + const statForkedMergedModulesCountPlus = 0; + const statForkedResultModulesCount = 0; let statChunkGroupInfoUpdated = 0; let statChildChunkGroupsReconnected = 0; diff --git a/lib/cache/IdleFileCachePlugin.js b/lib/cache/IdleFileCachePlugin.js index 2bf004486..f63551383 100644 --- a/lib/cache/IdleFileCachePlugin.js +++ b/lib/cache/IdleFileCachePlugin.js @@ -38,7 +38,7 @@ class IdleFileCachePlugin { * @returns {void} */ apply(compiler) { - let strategy = this.strategy; + const strategy = this.strategy; const idleTimeout = this.idleTimeout; const idleTimeoutForInitialStore = Math.min( idleTimeout, @@ -202,18 +202,11 @@ class IdleFileCachePlugin { }s.` ); } - idleTimer = setTimeout( - () => { - idleTimer = undefined; - isIdle = true; - resolvedPromise.then(processIdleTasks); - }, - Math.min( - isInitialStore ? idleTimeoutForInitialStore : Infinity, - isLargeChange ? idleTimeoutAfterLargeChanges : Infinity, - idleTimeout - ) - ); + idleTimer = setTimeout(() => { + idleTimer = undefined; + isIdle = true; + resolvedPromise.then(processIdleTasks); + }, Math.min(isInitialStore ? idleTimeoutForInitialStore : Infinity, isLargeChange ? idleTimeoutAfterLargeChanges : Infinity, idleTimeout)); idleTimer.unref(); } ); diff --git a/lib/cli.js b/lib/cli.js index 150beab8a..4d4557b7b 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -298,7 +298,7 @@ const getArguments = (schema = webpackSchema) => { return 0; } if (Array.isArray(schemaPart.items)) { - let i = 0; + const i = 0; for (const item of schemaPart.items) { addedArguments += traverse( item, @@ -390,7 +390,7 @@ const cliAddedItems = new WeakMap(); const getObjectAndProperty = (config, schemaPath, index = 0) => { if (!schemaPath) return { value: config }; const parts = schemaPath.split("."); - let property = parts.pop(); + const property = parts.pop(); let current = config; let i = 0; for (const part of parts) { @@ -444,7 +444,7 @@ const getObjectAndProperty = (config, schemaPath, index = 0) => { current = value; i++; } - let value = current[property]; + const value = current[property]; if (property.endsWith("[]")) { const name = property.slice(0, -2); const value = current[name]; @@ -627,13 +627,13 @@ const processArguments = (args, config, values) => { currentProblems.push({ ...problem, argument: key, - value: value, + value, index: i }); } problems.push(...currentProblems); }; - let value = values[key]; + const value = values[key]; if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) { processValue(value[i], i); diff --git a/lib/config/defaults.js b/lib/config/defaults.js index 3b6c77bbe..10f92fa85 100644 --- a/lib/config/defaults.js +++ b/lib/config/defaults.js @@ -167,15 +167,15 @@ const applyWebpackOptionsDefaults = (options, compilerIndex) => { const { mode, name, target } = options; - let targetProperties = + const targetProperties = target === false ? /** @type {false} */ (false) : typeof target === "string" - ? getTargetProperties(target, /** @type {Context} */ (options.context)) - : getTargetsProperties( - /** @type {string[]} */ (target), - /** @type {Context} */ (options.context) - ); + ? getTargetProperties(target, /** @type {Context} */ (options.context)) + : getTargetsProperties( + /** @type {string[]} */ (target), + /** @type {Context} */ (options.context) + ); const development = mode === "development"; const production = mode === "production" || !mode; @@ -275,8 +275,8 @@ const applyWebpackOptionsDefaults = (options, compilerIndex) => { validExternalTypes.includes(options.output.library.type) ? /** @type {ExternalsType} */ (options.output.library.type) : options.output.module - ? "module" - : "var"; + ? "module" + : "var"; }); applyNodeDefaults(options.node, { @@ -340,7 +340,7 @@ const applyWebpackOptionsDefaults = (options, compilerIndex) => { node: targetProperties.node, nwjs: targetProperties.nwjs, electron: targetProperties.electron - } + } }; }; @@ -475,7 +475,7 @@ const applySnapshotDefaults = (snapshot, { production, futureDefaults }) => { process.versions.pnp === "3" ? [ /^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/ - ] + ] : [/^(.+?[\\/]node_modules[\\/])/] ); F(snapshot, "immutablePaths", () => @@ -912,8 +912,9 @@ const applyOutputDefaults = ( } catch (e) { if (/** @type {Error & { code: string }} */ (e).code !== "ENOENT") { /** @type {Error & { code: string }} */ - (e).message += - `\nwhile determining default 'output.uniqueName' from 'name' in ${pkgPath}`; + ( + e + ).message += `\nwhile determining default 'output.uniqueName' from 'name' in ${pkgPath}`; throw e; } return ""; diff --git a/lib/css/CssExportsGenerator.js b/lib/css/CssExportsGenerator.js index 019f79ce9..1af214e77 100644 --- a/lib/css/CssExportsGenerator.js +++ b/lib/css/CssExportsGenerator.js @@ -93,7 +93,7 @@ class CssExportsGenerator extends Generator { chunkGraph: generateContext.chunkGraph, module, runtime: generateContext.runtime, - runtimeRequirements: runtimeRequirements, + runtimeRequirements, concatenationScope: generateContext.concatenationScope, codeGenerationResults: generateContext.codeGenerationResults, initFragments, @@ -135,7 +135,7 @@ class CssExportsGenerator extends Generator { const usedIdentifiers = new Set(); for (const [name, v] of cssExportsData.exports) { let identifier = Template.toIdentifier(name); - let i = 0; + const i = 0; while (usedIdentifiers.has(identifier)) { identifier = Template.toIdentifier(name + i); } @@ -161,7 +161,7 @@ class CssExportsGenerator extends Generator { ); } const exports = []; - for (let [name, v] of cssExportsData.exports) { + for (const [name, v] of cssExportsData.exports) { exports.push(`\t${JSON.stringify(name)}: ${JSON.stringify(v)}`); } return new RawSource( diff --git a/lib/css/CssModulesPlugin.js b/lib/css/CssModulesPlugin.js index 1da2425c4..2e792f40a 100644 --- a/lib/css/CssModulesPlugin.js +++ b/lib/css/CssModulesPlugin.js @@ -146,7 +146,7 @@ const LZWEncode = str => { let encoded = ""; let phrase = str[0]; let code = 256; - let maxCode = "\uffff".charCodeAt(0); + const maxCode = "\uffff".charCodeAt(0); for (let i = 1; i < str.length; i++) { const c = str[i]; if (map.has(phrase + c)) { @@ -259,12 +259,12 @@ class CssModulesPlugin { generatorOptions.exportsConvention, generatorOptions.localIdentName, generatorOptions.esModule - ) + ) : new CssGenerator( generatorOptions.exportsConvention, generatorOptions.localIdentName, generatorOptions.esModule - ); + ); }); normalModuleFactory.hooks.createModuleClass .for(type) @@ -623,7 +623,7 @@ class CssModulesPlugin { const cacheEntry = this._moduleCache.get(moduleSourceContent); /** @type {Inheritance} */ - let inheritance = [[module.cssLayer, module.supports, module.media]]; + const inheritance = [[module.cssLayer, module.supports, module.media]]; if (module.inheritance) { inheritance.push(...module.inheritance); } @@ -720,7 +720,7 @@ class CssModulesPlugin { ? Array.from( exports, ([n, v]) => `${escapeCss(n)}:${escapeCss(v)}/` - ).join("") + ).join("") : "" }${esModule ? "&" : ""}${escapeCss(moduleId)}` ); diff --git a/lib/css/CssParser.js b/lib/css/CssParser.js index a1f086a5b..f8bc01a8a 100644 --- a/lib/css/CssParser.js +++ b/lib/css/CssParser.js @@ -206,7 +206,7 @@ class CssParser extends Parser { /** @type {[number, number] | undefined} */ let lastIdentifier = undefined; /** @type [string, number, number][] */ - let balanced = []; + const balanced = []; /** @type {undefined | { start: number, url?: string, urlStart?: number, urlEnd?: number, layer?: string, layerStart?: number, layerEnd?: number, supports?: string, supportsStart?: number, supportsEnd?: number, inSupports?:boolean, media?: string }} */ let importData = undefined; /** @type {boolean} */ @@ -320,7 +320,7 @@ class CssParser extends Parser { if (input.charCodeAt(pos) === CC_RIGHT_CURLY) break; pos = walkCssTokens.eatWhitespaceAndComments(input, pos); if (pos === input.length) return pos; - let start = pos; + const start = pos; let name; [pos, name] = eatText(input, pos, eatExportName); if (pos === input.length) return pos; @@ -428,7 +428,10 @@ class CssParser extends Parser { return isNextRulePrelude; }, url: (input, start, end, contentStart, contentEnd) => { - let value = normalizeUrl(input.slice(contentStart, contentEnd), false); + const value = normalizeUrl( + input.slice(contentStart, contentEnd), + false + ); switch (scope) { case CSS_MODE_IN_AT_IMPORT: { @@ -530,7 +533,7 @@ class CssParser extends Parser { (last[0].replace(/\\/g, "").toLowerCase() === "url" || IMAGE_SET_FUNCTION.test(last[0].replace(/\\/g, ""))) ) { - let value = normalizeUrl(input.slice(start + 1, end - 1), true); + const value = normalizeUrl(input.slice(start + 1, end - 1), true); // Ignore `url()`, `url('')` and `url("")`, they are valid by spec if (value.length === 0) { @@ -884,7 +887,7 @@ class CssParser extends Parser { } if (name === "var") { - let pos = walkCssTokens.eatWhitespaceAndComments(input, end); + const pos = walkCssTokens.eatWhitespaceAndComments(input, end); if (pos === input.length) return pos; const [newPos, name] = eatText(input, pos, eatNameInVar); if (!name.startsWith("--")) return end; @@ -920,7 +923,7 @@ class CssParser extends Parser { ) { modeData = balanced[balanced.length - 1] ? /** @type {"local" | "global"} */ - (balanced[balanced.length - 1][0]) + (balanced[balanced.length - 1][0]) : undefined; const dep = new ConstDependency("", [start, end]); module.addPresentationalDependency(dep); diff --git a/lib/css/walkCssTokens.js b/lib/css/walkCssTokens.js index 678aa98d6..9081da7c6 100644 --- a/lib/css/walkCssTokens.js +++ b/lib/css/walkCssTokens.js @@ -431,7 +431,7 @@ const consumePotentialPseudo = (input, pos, callbacks) => { if (!callbacks.isSelector(input, pos) || !_startsIdentifier(input, pos)) return pos; pos = _consumeIdentifier(input, pos, callbacks); - let cc = input.charCodeAt(pos); + const cc = input.charCodeAt(pos); if (cc === CC_LEFT_PARENTHESIS) { pos++; if (callbacks.pseudoFunction !== undefined) { @@ -723,7 +723,7 @@ module.exports.isIdentStartCodePoint = isIdentStartCodePoint; */ module.exports.eatComments = (input, pos) => { for (;;) { - let originalPos = pos; + const originalPos = pos; pos = consumeComments(input, pos, {}); if (originalPos === pos) { break; @@ -753,7 +753,7 @@ module.exports.eatWhitespace = (input, pos) => { */ module.exports.eatWhitespaceAndComments = (input, pos) => { for (;;) { - let originalPos = pos; + const originalPos = pos; pos = consumeComments(input, pos, {}); while (_isWhiteSpace(input.charCodeAt(pos))) { pos++; diff --git a/lib/dependencies/AMDDefineDependencyParserPlugin.js b/lib/dependencies/AMDDefineDependencyParserPlugin.js index 3e193fd1a..481c47d21 100644 --- a/lib/dependencies/AMDDefineDependencyParserPlugin.js +++ b/lib/dependencies/AMDDefineDependencyParserPlugin.js @@ -317,7 +317,7 @@ class AMDDefineDependencyParserPlugin { } } } - let fnRenames = new Map(); + const fnRenames = new Map(); if (array) { /** @type {Record} */ const identifiers = {}; diff --git a/lib/dependencies/ContextDependencyHelpers.js b/lib/dependencies/ContextDependencyHelpers.js index 19aa320db..b4c7935af 100644 --- a/lib/dependencies/ContextDependencyHelpers.js +++ b/lib/dependencies/ContextDependencyHelpers.js @@ -69,8 +69,8 @@ exports.create = ( ) => { if (param.isTemplateString()) { const quasis = /** @type {BasicEvaluatedExpression[]} */ (param.quasis); - let prefixRaw = /** @type {string} */ (quasis[0].string); - let postfixRaw = + const prefixRaw = /** @type {string} */ (quasis[0].string); + const postfixRaw = /** @type {string} */ (quasis.length > 1 ? quasis[quasis.length - 1].string : ""); @@ -180,10 +180,10 @@ exports.create = ( ((param.prefix && param.prefix.isString()) || (param.postfix && param.postfix.isString())) ) { - let prefixRaw = + const prefixRaw = /** @type {string} */ (param.prefix && param.prefix.isString() ? param.prefix.string : ""); - let postfixRaw = + const postfixRaw = /** @type {string} */ (param.postfix && param.postfix.isString() ? param.postfix.string : ""); const prefixRange = diff --git a/lib/dependencies/HarmonyImportSpecifierDependency.js b/lib/dependencies/HarmonyImportSpecifierDependency.js index 45f9cdf30..cc46aa131 100644 --- a/lib/dependencies/HarmonyImportSpecifierDependency.js +++ b/lib/dependencies/HarmonyImportSpecifierDependency.js @@ -345,7 +345,7 @@ HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependen if (dep.referencedPropertiesInDestructuring) { const prefixedIds = ids[0] === "default" ? ids.slice(1) : ids; - for (let { + for (const { id, shorthand, range diff --git a/lib/dependencies/ImportDependency.js b/lib/dependencies/ImportDependency.js index 1c814271e..1368d405a 100644 --- a/lib/dependencies/ImportDependency.js +++ b/lib/dependencies/ImportDependency.js @@ -124,7 +124,7 @@ ImportDependency.Template = class ImportDependencyTemplate extends ( ); const content = runtimeTemplate.moduleNamespacePromise({ chunkGraph, - block: block, + block, module: /** @type {Module} */ (moduleGraph.getModule(dep)), request: dep.request, strict: /** @type {BuildMeta} */ (module.buildMeta).strictHarmonyModule, diff --git a/lib/dependencies/ProvidedDependency.js b/lib/dependencies/ProvidedDependency.js index ae854479e..9f1d3f6e7 100644 --- a/lib/dependencies/ProvidedDependency.js +++ b/lib/dependencies/ProvidedDependency.js @@ -64,7 +64,7 @@ class ProvidedDependency extends ModuleDependency { * @returns {(string[] | ReferencedExport)[]} referenced exports */ getReferencedExports(moduleGraph, runtime) { - let ids = this.ids; + const ids = this.ids; if (ids.length === 0) return Dependency.EXPORTS_OBJECT_REFERENCED; return [ids]; } diff --git a/lib/dependencies/WorkerPlugin.js b/lib/dependencies/WorkerPlugin.js index 1d5e0e386..12d31802b 100644 --- a/lib/dependencies/WorkerPlugin.js +++ b/lib/dependencies/WorkerPlugin.js @@ -241,7 +241,7 @@ class WorkerPlugin { insertLocation: arg2 ? /** @type {Range} */ (arg2.range) : /** @type {Range} */ (arg1.range)[1] - }; + }; const { options: importOptions, errors: commentErrors } = parser.parseCommentOptions(/** @type {Range} */ (expr.range)); @@ -258,7 +258,7 @@ class WorkerPlugin { } /** @type {EntryOptions} */ - let entryOptions = {}; + const entryOptions = {}; if (importOptions) { if (importOptions.webpackIgnore !== undefined) { @@ -316,9 +316,9 @@ class WorkerPlugin { } if (entryOptions.runtime === undefined) { - let i = workerIndexMap.get(parser.state) || 0; + const i = workerIndexMap.get(parser.state) || 0; workerIndexMap.set(parser.state, i + 1); - let name = `${cachedContextify( + const name = `${cachedContextify( parser.state.module.identifier() )}|${i}`; const hash = createHash(compilation.outputOptions.hashFunction); diff --git a/lib/esm/ModuleChunkFormatPlugin.js b/lib/esm/ModuleChunkFormatPlugin.js index c3f2f471d..6012e58ca 100644 --- a/lib/esm/ModuleChunkFormatPlugin.js +++ b/lib/esm/ModuleChunkFormatPlugin.js @@ -103,7 +103,7 @@ class ModuleChunkFormatPlugin { compilation.outputOptions ), { - chunk: chunk, + chunk, contentHashType: "javascript" } ) diff --git a/lib/javascript/BasicEvaluatedExpression.js b/lib/javascript/BasicEvaluatedExpression.js index 320abeb59..7bb7077b5 100644 --- a/lib/javascript/BasicEvaluatedExpression.js +++ b/lib/javascript/BasicEvaluatedExpression.js @@ -292,7 +292,7 @@ class BasicEvaluatedExpression { if (this.isBigInt()) return `${this.bigint}`; if (this.isRegExp()) return `${this.regExp}`; if (this.isArray()) { - let array = []; + const array = []; for (const item of /** @type {BasicEvaluatedExpression[]} */ ( this.items )) { diff --git a/lib/javascript/JavascriptModulesPlugin.js b/lib/javascript/JavascriptModulesPlugin.js index df76ac615..a5903f2cc 100644 --- a/lib/javascript/JavascriptModulesPlugin.js +++ b/lib/javascript/JavascriptModulesPlugin.js @@ -684,8 +684,8 @@ class JavascriptModulesPlugin { return strictHeader ? new ConcatSource(strictHeader, source, ";") : renderContext.runtimeTemplate.isModule() - ? source - : new ConcatSource(source, ";"); + ? source + : new ConcatSource(source, ";"); } /** @@ -718,7 +718,7 @@ class JavascriptModulesPlugin { inlinedModules = new Set(chunkGraph.getChunkEntryModulesIterable(chunk)); } - let source = new ConcatSource(); + const source = new ConcatSource(); let prefix; if (iife) { if (runtimeTemplate.supportsArrowFunction()) { @@ -756,7 +756,7 @@ class JavascriptModulesPlugin { inlinedModules ? allModules.filter( m => !(/** @type {Set} */ (inlinedModules).has(m)) - ) + ) : allModules, module => this.renderModule(module, chunkRenderContext, hooks, true), prefix @@ -849,15 +849,15 @@ class JavascriptModulesPlugin { const exports = runtimeRequirements.has(RuntimeGlobals.exports); const webpackExports = exports && m.exportsArgument === RuntimeGlobals.exports; - let iife = innerStrict + const iife = innerStrict ? "it need to be in strict mode." : inlinedModules.size > 1 - ? // TODO check globals and top-level declarations of other entries and chunk modules - // to make a better decision - "it need to be isolated against other entry modules." - : exports && !webpackExports - ? `it uses a non-standard name for the exports (${m.exportsArgument}).` - : hooks.embedInRuntimeBailout.call(m, renderContext); + ? // TODO check globals and top-level declarations of other entries and chunk modules + // to make a better decision + "it need to be isolated against other entry modules." + : exports && !webpackExports + ? `it uses a non-standard name for the exports (${m.exportsArgument}).` + : hooks.embedInRuntimeBailout.call(m, renderContext); let footer; if (iife !== undefined) { startupSource.add( @@ -1047,7 +1047,7 @@ class JavascriptModulesPlugin { allowInlineStartup: true }; - let { header: buf, startup, beforeStartup, afterStartup } = result; + const { header: buf, startup, beforeStartup, afterStartup } = result; if (result.allowInlineStartup && moduleFactories) { startup.push( @@ -1323,14 +1323,14 @@ class JavascriptModulesPlugin { `${RuntimeGlobals.interceptModuleExecution}.forEach(function(handler) { handler(execOptions); });`, "module = execOptions.module;", "execOptions.factory.call(module.exports, module, module.exports, execOptions.require);" - ]) + ]) : runtimeRequirements.has(RuntimeGlobals.thisAsExports) - ? Template.asString([ - `__webpack_modules__[moduleId].call(module.exports, module, module.exports, ${RuntimeGlobals.require});` - ]) - : Template.asString([ - `__webpack_modules__[moduleId](module, module.exports, ${RuntimeGlobals.require});` - ]); + ? Template.asString([ + `__webpack_modules__[moduleId].call(module.exports, module, module.exports, ${RuntimeGlobals.require});` + ]) + : Template.asString([ + `__webpack_modules__[moduleId](module, module.exports, ${RuntimeGlobals.require});` + ]); const needModuleId = runtimeRequirements.has(RuntimeGlobals.moduleId); const needModuleLoaded = runtimeRequirements.has( RuntimeGlobals.moduleLoaded @@ -1343,7 +1343,7 @@ class JavascriptModulesPlugin { ? Template.indent([ "if (cachedModule.error !== undefined) throw cachedModule.error;", "return cachedModule.exports;" - ]) + ]) : Template.indent("return cachedModule.exports;"), "}", "// Create a new module (and put it into the cache)", @@ -1366,27 +1366,27 @@ class JavascriptModulesPlugin { "if(threw) delete __webpack_module_cache__[moduleId];" ]), "}" - ]) + ]) : outputOptions.strictModuleErrorHandling - ? Template.asString([ - "// Execute the module function", - "try {", - Template.indent(moduleExecution), - "} catch(e) {", - Template.indent(["module.error = e;", "throw e;"]), - "}" - ]) - : Template.asString([ - "// Execute the module function", - moduleExecution - ]), + ? Template.asString([ + "// Execute the module function", + "try {", + Template.indent(moduleExecution), + "} catch(e) {", + Template.indent(["module.error = e;", "throw e;"]), + "}" + ]) + : Template.asString([ + "// Execute the module function", + moduleExecution + ]), needModuleLoaded ? Template.asString([ "", "// Flag the module as loaded", `${RuntimeGlobals.moduleLoaded} = true;`, "" - ]) + ]) : "", "// Return the exports of the module", "return module.exports;" diff --git a/lib/javascript/JavascriptParser.js b/lib/javascript/JavascriptParser.js index 4d960f303..4af090f9c 100644 --- a/lib/javascript/JavascriptParser.js +++ b/lib/javascript/JavascriptParser.js @@ -1366,8 +1366,8 @@ class JavascriptParser extends Parser { if (expr.arguments.length !== 2) return; if (expr.arguments[0].type === "SpreadElement") return; if (expr.arguments[1].type === "SpreadElement") return; - let arg1 = this.evaluateExpression(expr.arguments[0]); - let arg2 = this.evaluateExpression(expr.arguments[1]); + const arg1 = this.evaluateExpression(expr.arguments[0]); + const arg2 = this.evaluateExpression(expr.arguments[1]); if (!arg1.isString() && !arg1.isRegExp()) return; const arg1Value = /** @type {string | RegExp} */ ( arg1.regExp || arg1.string @@ -1387,8 +1387,8 @@ class JavascriptParser extends Parser { .tap("JavascriptParser", (expr, param) => { if (!param.isString()) return; let arg1; - let result, - str = /** @type {string} */ (param.string); + let result; + const str = /** @type {string} */ (param.string); switch (expr.arguments.length) { case 1: if (expr.arguments[0].type === "SpreadElement") return; @@ -3415,7 +3415,7 @@ class JavascriptParser extends Parser { * @param {ImportExpression} expression import expression */ walkImportExpression(expression) { - let result = this.hooks.importCall.call(expression); + const result = this.hooks.importCall.call(expression); if (result === true) return; this.walkExpression(expression.source); @@ -4395,7 +4395,7 @@ class JavascriptParser extends Parser { const comments = /** @type {Comment[]} */ (this.comments); let idx = binarySearchBounds.ge(comments, rangeStart, compare); /** @type {Comment[]} */ - let commentsInRange = []; + const commentsInRange = []; while ( comments[idx] && /** @type {Range} */ (comments[idx].range)[1] <= rangeEnd @@ -4579,9 +4579,9 @@ class JavascriptParser extends Parser { if (comments.length === 0) { return EMPTY_COMMENT_OPTIONS; } - let options = {}; + const options = {}; /** @type {unknown[]} */ - let errors = []; + const errors = []; for (const comment of comments) { const { value } = comment; if (value && webpackCommentRegExp.test(value)) { diff --git a/lib/javascript/JavascriptParserHelpers.js b/lib/javascript/JavascriptParserHelpers.js index be85e9e14..c79d4f4d1 100644 --- a/lib/javascript/JavascriptParserHelpers.js +++ b/lib/javascript/JavascriptParserHelpers.js @@ -79,7 +79,7 @@ exports.evaluateToBoolean = value => { */ exports.evaluateToIdentifier = (identifier, rootInfo, getMembers, truthy) => { return function identifierExpression(expr) { - let evaluatedExpression = new BasicEvaluatedExpression() + const evaluatedExpression = new BasicEvaluatedExpression() .setIdentifier(identifier, rootInfo, getMembers) .setSideEffects(false) .setRange(/** @type {Range} */ (expr.range)); diff --git a/lib/json/JsonGenerator.js b/lib/json/JsonGenerator.js index 53af8d3a5..6ad43893e 100644 --- a/lib/json/JsonGenerator.js +++ b/lib/json/JsonGenerator.js @@ -68,7 +68,7 @@ const createObjectForExportsInfo = (data, exportsInfo, runtime) => { /** @type {Record} */ (reducedData)[name] = value; } if (isArray) { - let arrayLengthWhenUsed = + const arrayLengthWhenUsed = exportsInfo.getReadOnlyExportInfo("length").getUsed(runtime) !== UsageState.Unused ? data.length @@ -173,7 +173,7 @@ class JsonGenerator extends Generator { } const exportsInfo = moduleGraph.getExportsInfo(module); /** @type {RawJsonData} */ - let finalJson = + const finalJson = typeof data === "object" && data && exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused diff --git a/lib/library/AmdLibraryPlugin.js b/lib/library/AmdLibraryPlugin.js index 29643ef2e..8df186fab 100644 --- a/lib/library/AmdLibraryPlugin.js +++ b/lib/library/AmdLibraryPlugin.js @@ -67,10 +67,9 @@ class AmdLibraryPlugin extends AbstractLibraryPlugin { ); } } - return { - name: /** @type {string} */ (name), - amdContainer: /** @type {string} */ (amdContainer) - }; + const _name = /** @type {string} */ (name); + const _amdContainer = /** @type {string} */ (amdContainer); + return { name: _name, amdContainer: _amdContainer }; } /** diff --git a/lib/library/AssignLibraryPlugin.js b/lib/library/AssignLibraryPlugin.js index 8c8bc1b28..31de5ba93 100644 --- a/lib/library/AssignLibraryPlugin.js +++ b/lib/library/AssignLibraryPlugin.js @@ -143,8 +143,9 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin { ); } } + const _name = /** @type {string | string[]} */ (name); return { - name: /** @type {string | string[]} */ (name), + name: _name, export: library.export }; } @@ -295,7 +296,7 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin { const exportAccess = options.export ? propertyAccess( Array.isArray(options.export) ? options.export : [options.export] - ) + ) : ""; const result = new ConcatSource(source); if (staticExports) { diff --git a/lib/library/JsonpLibraryPlugin.js b/lib/library/JsonpLibraryPlugin.js index 2c6cab0a3..975787423 100644 --- a/lib/library/JsonpLibraryPlugin.js +++ b/lib/library/JsonpLibraryPlugin.js @@ -54,8 +54,9 @@ class JsonpLibraryPlugin extends AbstractLibraryPlugin { `Jsonp library name must be a simple string. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` ); } + const _name = /** @type {string} */ (name); return { - name: /** @type {string} */ (name) + name: _name }; } diff --git a/lib/library/ModernModuleLibraryPlugin.js b/lib/library/ModernModuleLibraryPlugin.js index b3fa9e66d..c07f52fa4 100644 --- a/lib/library/ModernModuleLibraryPlugin.js +++ b/lib/library/ModernModuleLibraryPlugin.js @@ -73,8 +73,9 @@ class ModernModuleLibraryPlugin extends AbstractLibraryPlugin { `Library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` ); } + const _name = /** @type {string} */ (name); return { - name: /** @type {string} */ (name) + name: _name }; } diff --git a/lib/library/ModuleLibraryPlugin.js b/lib/library/ModuleLibraryPlugin.js index 480014b0c..57afdc3e1 100644 --- a/lib/library/ModuleLibraryPlugin.js +++ b/lib/library/ModuleLibraryPlugin.js @@ -58,8 +58,9 @@ class ModuleLibraryPlugin extends AbstractLibraryPlugin { `Library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` ); } + const _name = /** @type {string} */ (name); return { - name: /** @type {string} */ (name) + name: _name }; } diff --git a/lib/library/SystemLibraryPlugin.js b/lib/library/SystemLibraryPlugin.js index 6a0df15bf..8a30cdf73 100644 --- a/lib/library/SystemLibraryPlugin.js +++ b/lib/library/SystemLibraryPlugin.js @@ -58,8 +58,9 @@ class SystemLibraryPlugin extends AbstractLibraryPlugin { `System.js library name must be a simple string or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` ); } + const _name = /** @type {string} */ (name); return { - name: /** @type {string} */ (name) + name: _name }; } @@ -187,7 +188,7 @@ class SystemLibraryPlugin extends AbstractLibraryPlugin { .join(",\n") ), "]," - ]); + ]); return new ConcatSource( Template.asString([ diff --git a/lib/logging/runtime.js b/lib/logging/runtime.js index 45fbb19ba..a54d984f6 100644 --- a/lib/logging/runtime.js +++ b/lib/logging/runtime.js @@ -10,7 +10,7 @@ const { Logger } = require("./Logger"); const createConsoleLogger = require("./createConsoleLogger"); /** @type {createConsoleLogger.LoggerOptions} */ -let currentDefaultLoggerOptions = { +const currentDefaultLoggerOptions = { level: "info", debug: false, console diff --git a/lib/optimize/AggressiveMergingPlugin.js b/lib/optimize/AggressiveMergingPlugin.js index b86f8b690..5d8258f65 100644 --- a/lib/optimize/AggressiveMergingPlugin.js +++ b/lib/optimize/AggressiveMergingPlugin.js @@ -51,7 +51,7 @@ class AggressiveMergingPlugin { chunks => { const chunkGraph = compilation.chunkGraph; /** @type {{a: Chunk, b: Chunk, improvement: number}[]} */ - let combinations = []; + const combinations = []; for (const a of chunks) { if (a.canBeInitial()) continue; for (const b of chunks) { diff --git a/lib/optimize/ConcatenatedModule.js b/lib/optimize/ConcatenatedModule.js index 8da57d74c..4b58f6db7 100644 --- a/lib/optimize/ConcatenatedModule.js +++ b/lib/optimize/ConcatenatedModule.js @@ -367,10 +367,10 @@ const getFinalBinding = ( const defaultExport = asCall ? `${info.interopDefaultAccessName}()` : asiSafe - ? `(${info.interopDefaultAccessName}())` - : asiSafe === false - ? `;(${info.interopDefaultAccessName}())` - : `${info.interopDefaultAccessName}.a`; + ? `(${info.interopDefaultAccessName}())` + : asiSafe === false + ? `;(${info.interopDefaultAccessName}())` + : `${info.interopDefaultAccessName}.a`; return { info, rawName: defaultExport, @@ -601,8 +601,8 @@ const getFinalName = ( return asiSafe ? `(0,${reference})` : asiSafe === false - ? `;(0,${reference})` - : `/*#__PURE__*/Object(${reference})`; + ? `;(0,${reference})` + : `/*#__PURE__*/Object(${reference})`; } return reference; } @@ -903,7 +903,9 @@ class ConcatenatedModule extends Module { * @returns {Iterable<{ connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true }>} imported modules in order */ const getConcatenatedImports = module => { - let connections = Array.from(moduleGraph.getOutgoingConnections(module)); + const connections = Array.from( + moduleGraph.getOutgoingConnections(module) + ); if (module === rootModule) { for (const c of moduleGraph.getOutgoingConnections(this)) connections.push(c); @@ -1077,7 +1079,7 @@ class ConcatenatedModule extends Module { /** @type {string} */ (rootModule.context), associatedObjectForCache ); - let identifiers = []; + const identifiers = []; for (const module of modules) { identifiers.push(cachedMakePathsRelative(module.identifier())); } @@ -1489,8 +1491,9 @@ class ConcatenatedModule extends Module { } */ ${finalName}`; } catch (e) { /** @type {Error} */ - (e).message += - `\nwhile generating the root export '${name}' (used name: '${used}')`; + ( + e + ).message += `\nwhile generating the root export '${name}' (used name: '${used}')`; throw e; } }); @@ -1593,7 +1596,7 @@ class ConcatenatedModule extends Module { nsObj.length > 0 ? `${RuntimeGlobals.definePropertyGetters}(${name}, {${nsObj.join( "," - )}\n});\n` + )}\n});\n` : ""; if (nsObj.length > 0) runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); @@ -1795,8 +1798,9 @@ ${defineGetters}` info.moduleScope = moduleScope; } catch (err) { /** @type {Error} */ - (err).message += - `\nwhile analyzing module ${m.identifier()} for concatenation`; + ( + err + ).message += `\nwhile analyzing module ${m.identifier()} for concatenation`; throw err; } } diff --git a/lib/optimize/ModuleConcatenationPlugin.js b/lib/optimize/ModuleConcatenationPlugin.js index 21ab26f4d..8833f9a57 100644 --- a/lib/optimize/ModuleConcatenationPlugin.js +++ b/lib/optimize/ModuleConcatenationPlugin.js @@ -291,8 +291,8 @@ class ModuleConcatenationPlugin { filteredRuntime === true ? chunkRuntime : filteredRuntime === false - ? undefined - : filteredRuntime; + ? undefined + : filteredRuntime; // create a configuration with the root const currentConfiguration = new ConcatConfiguration( @@ -399,7 +399,7 @@ class ModuleConcatenationPlugin { // Create a new ConcatenatedModule ConcatenatedModule.getCompilationHooks(compilation); - let newModule = ConcatenatedModule.create( + const newModule = ConcatenatedModule.create( rootModule, modules, concatConfiguration.runtime, diff --git a/lib/optimize/RealContentHashPlugin.js b/lib/optimize/RealContentHashPlugin.js index 23a6abd88..3466f40d9 100644 --- a/lib/optimize/RealContentHashPlugin.js +++ b/lib/optimize/RealContentHashPlugin.js @@ -215,7 +215,7 @@ class RealContentHashPlugin { [asset.referencedHashes, asset.ownHashes] = await cacheAnalyse.providePromise(name, etag, () => { const referencedHashes = new Set(); - let ownHashes = new Set(); + const ownHashes = new Set(); const inContent = content.match(hashRegExp); if (inContent) { for (const hash of inContent) { diff --git a/lib/optimize/RemoveParentModulesPlugin.js b/lib/optimize/RemoveParentModulesPlugin.js index 14f039110..cc177c777 100644 --- a/lib/optimize/RemoveParentModulesPlugin.js +++ b/lib/optimize/RemoveParentModulesPlugin.js @@ -41,7 +41,7 @@ function* getModulesFromMask(mask, ordinalModules) { // Consider the last 32 bits, since that's what Math.clz32 can handle let last32 = Number(BigInt.asUintN(32, mask)); while (last32 > 0) { - let last = Math.clz32(last32); + const last = Math.clz32(last32); // The number of trailing zeros is the number trimmed off the input mask + 31 - the number of leading zeros // The 32 is baked into the initial value of offset const moduleIndex = offset - last; @@ -148,7 +148,7 @@ class RemoveParentModulesPlugin { availableModulesMask = parentMask; changed = true; } else { - let newMask = availableModulesMask & parentMask; + const newMask = availableModulesMask & parentMask; if (newMask !== availableModulesMask) { changed = true; availableModulesMask = newMask; diff --git a/lib/optimize/SplitChunksPlugin.js b/lib/optimize/SplitChunksPlugin.js index 122b4ef04..5a83739e8 100644 --- a/lib/optimize/SplitChunksPlugin.js +++ b/lib/optimize/SplitChunksPlugin.js @@ -500,7 +500,7 @@ const normalizeCacheGroups = (cacheGroups, defaultSizeTypes) => { */ const fn = (module, context) => { /** @type {CacheGroupSource[]} */ - let results = []; + const results = []; for (const fn of handlers) { fn(module, context, results); } @@ -749,20 +749,20 @@ module.exports = class SplitChunksPlugin { cacheGroupSource.minChunks !== undefined ? cacheGroupSource.minChunks : cacheGroupSource.enforce - ? 1 - : this.options.minChunks, + ? 1 + : this.options.minChunks, maxAsyncRequests: cacheGroupSource.maxAsyncRequests !== undefined ? cacheGroupSource.maxAsyncRequests : cacheGroupSource.enforce - ? Infinity - : this.options.maxAsyncRequests, + ? Infinity + : this.options.maxAsyncRequests, maxInitialRequests: cacheGroupSource.maxInitialRequests !== undefined ? cacheGroupSource.maxInitialRequests : cacheGroupSource.enforce - ? Infinity - : this.options.maxInitialRequests, + ? Infinity + : this.options.maxInitialRequests, getName: cacheGroupSource.getName !== undefined ? cacheGroupSource.getName @@ -1210,7 +1210,7 @@ module.exports = class SplitChunksPlugin { // Walk through all modules for (const module of compilation.modules) { // Get cache group - let cacheGroups = this.options.getCacheGroups(module, context); + const cacheGroups = this.options.getCacheGroups(module, context); if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) { continue; } @@ -1428,13 +1428,13 @@ module.exports = class SplitChunksPlugin { chunk.isOnlyInitial() ? item.cacheGroup.maxInitialRequests : chunk.canBeInitial() - ? Math.min( - /** @type {number} */ - (item.cacheGroup.maxInitialRequests), - /** @type {number} */ - (item.cacheGroup.maxAsyncRequests) - ) - : item.cacheGroup.maxAsyncRequests + ? Math.min( + /** @type {number} */ + (item.cacheGroup.maxInitialRequests), + /** @type {number} */ + (item.cacheGroup.maxAsyncRequests) + ) + : item.cacheGroup.maxAsyncRequests ); if ( isFinite(maxRequests) && @@ -1482,7 +1482,7 @@ module.exports = class SplitChunksPlugin { usedChunks.size === 1 ) { const [chunk] = usedChunks; - let chunkSizes = Object.create(null); + const chunkSizes = Object.create(null); for (const module of chunkGraph.getChunkModulesIterable(chunk)) { if (!item.modules.has(module)) { for (const type of module.getSourceTypes()) { @@ -1569,21 +1569,21 @@ module.exports = class SplitChunksPlugin { oldMaxSizeSettings.minSize, item.cacheGroup._minSizeForMaxSize, Math.max - ) + ) : item.cacheGroup.minSize, maxAsyncSize: oldMaxSizeSettings ? combineSizes( oldMaxSizeSettings.maxAsyncSize, item.cacheGroup.maxAsyncSize, Math.min - ) + ) : item.cacheGroup.maxAsyncSize, maxInitialSize: oldMaxSizeSettings ? combineSizes( oldMaxSizeSettings.maxInitialSize, item.cacheGroup.maxInitialSize, Math.min - ) + ) : item.cacheGroup.maxInitialSize, automaticNameDelimiter: item.cacheGroup.automaticNameDelimiter, keys: oldMaxSizeSettings diff --git a/lib/performance/SizeLimitsPlugin.js b/lib/performance/SizeLimitsPlugin.js index d41d0d3e0..b1371a231 100644 --- a/lib/performance/SizeLimitsPlugin.js +++ b/lib/performance/SizeLimitsPlugin.js @@ -127,8 +127,8 @@ module.exports = class SizeLimitsPlugin { if (size > /** @type {number} */ (entrypointSizeLimit)) { entrypointsOverLimit.push({ - name: name, - size: size, + name, + size, files: entry.getFiles().filter(fileFilter) }); isOverSizeLimitSet.add(entry); diff --git a/lib/serialization/BinaryMiddleware.js b/lib/serialization/BinaryMiddleware.js index 4074836ae..c563f1bcb 100644 --- a/lib/serialization/BinaryMiddleware.js +++ b/lib/serialization/BinaryMiddleware.js @@ -1101,6 +1101,7 @@ class BinaryMiddleware extends SerializerMiddleware { } // avoid leaking memory in context + // eslint-disable-next-line prefer-const let _result = result; result = undefined; return _result; diff --git a/lib/serialization/MapObjectSerializer.js b/lib/serialization/MapObjectSerializer.js index cb5fa6b63..7caa4cdf4 100644 --- a/lib/serialization/MapObjectSerializer.js +++ b/lib/serialization/MapObjectSerializer.js @@ -29,7 +29,7 @@ class MapObjectSerializer { */ deserialize(context) { /** @type {number} */ - let size = context.read(); + const size = context.read(); /** @type {Map} */ const map = new Map(); /** @type {K[]} */ diff --git a/lib/serialization/SetObjectSerializer.js b/lib/serialization/SetObjectSerializer.js index 18cfa8ca5..bb56ded8d 100644 --- a/lib/serialization/SetObjectSerializer.js +++ b/lib/serialization/SetObjectSerializer.js @@ -26,7 +26,7 @@ class SetObjectSerializer { */ deserialize(context) { /** @type {number} */ - let size = context.read(); + const size = context.read(); /** @type {Set} */ const set = new Set(); for (let i = 0; i < size; i++) { diff --git a/lib/sharing/ConsumeSharedPlugin.js b/lib/sharing/ConsumeSharedPlugin.js index 7b5188c50..04e9b82fe 100644 --- a/lib/sharing/ConsumeSharedPlugin.js +++ b/lib/sharing/ConsumeSharedPlugin.js @@ -57,10 +57,10 @@ class ConsumeSharedPlugin { (item, key) => { if (Array.isArray(item)) throw new Error("Unexpected array in options"); /** @type {ConsumeOptions} */ - let result = + const result = item === key || !isRequiredVersion(item) ? // item is a request/key - { + { import: key, shareScope: options.shareScope || "default", shareKey: key, @@ -69,10 +69,10 @@ class ConsumeSharedPlugin { strictVersion: false, singleton: false, eager: false - } + } : // key is a request/key - // item is a version - { + // item is a version + { import: key, shareScope: options.shareScope || "default", shareKey: key, @@ -81,7 +81,7 @@ class ConsumeSharedPlugin { packageName: undefined, singleton: false, eager: false - }; + }; return result; }, (item, key) => ({ diff --git a/lib/sharing/utils.js b/lib/sharing/utils.js index b7f4a4d8e..acbcbe976 100644 --- a/lib/sharing/utils.js +++ b/lib/sharing/utils.js @@ -250,7 +250,7 @@ function canBeDecoded(str) { * @returns {string} dep version */ function getGitUrlVersion(gitUrl) { - let oriGitUrl = gitUrl; + const oriGitUrl = gitUrl; // github extreme shorthand if (RE_URL_GITHUB_EXTREME_SHORT.test(gitUrl)) { gitUrl = "github:" + gitUrl; diff --git a/lib/util/TupleSet.js b/lib/util/TupleSet.js index fe33c364a..a923f4011 100644 --- a/lib/util/TupleSet.js +++ b/lib/util/TupleSet.js @@ -62,7 +62,7 @@ class TupleSet { } const beforeLast = args[args.length - 2]; - let set = map.get(beforeLast); + const set = map.get(beforeLast); if (set === undefined) { return false; } @@ -86,7 +86,7 @@ class TupleSet { } const beforeLast = args[args.length - 2]; - let set = map.get(beforeLast); + const set = map.get(beforeLast); if (set === undefined) { return; } diff --git a/lib/util/comparators.js b/lib/util/comparators.js index ba636e4e9..0b91dc278 100644 --- a/lib/util/comparators.js +++ b/lib/util/comparators.js @@ -480,8 +480,8 @@ exports.compareChunksNatural = chunkGraph => { * @returns {-1|0|1} sorting comparator value */ exports.compareLocations = (a, b) => { - let isObjectA = typeof a === "object" && a !== null; - let isObjectB = typeof b === "object" && b !== null; + const isObjectA = typeof a === "object" && a !== null; + const isObjectB = typeof b === "object" && b !== null; if (!isObjectA || !isObjectB) { if (isObjectA) return 1; if (isObjectB) return -1; diff --git a/lib/util/deterministicGrouping.js b/lib/util/deterministicGrouping.js index 54f90a078..b16802604 100644 --- a/lib/util/deterministicGrouping.js +++ b/lib/util/deterministicGrouping.js @@ -397,14 +397,14 @@ module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { // going minSize from left and right // at least one node need to be included otherwise we get stuck let left = 1; - let leftSize = Object.create(null); + const leftSize = Object.create(null); addSizeTo(leftSize, group.nodes[0].size); while (left < group.nodes.length && isTooSmall(leftSize, minSize)) { addSizeTo(leftSize, group.nodes[left].size); left++; } let right = group.nodes.length - 2; - let rightSize = Object.create(null); + const rightSize = Object.create(null); addSizeTo(rightSize, group.nodes[group.nodes.length - 1].size); while (right >= 0 && isTooSmall(rightSize, minSize)) { addSizeTo(rightSize, group.nodes[right].size); @@ -452,7 +452,7 @@ module.exports = ({ maxSize, minSize, items, getSize, getKey }) => { let best = -1; let bestSimilarity = Infinity; let pos = left; - let rightSize = sumSize(group.nodes.slice(pos)); + const rightSize = sumSize(group.nodes.slice(pos)); // pos v v right // [ O O O ] O O O [ O O O ] diff --git a/lib/util/smartGrouping.js b/lib/util/smartGrouping.js index 8645f8a99..c8ae1e5ca 100644 --- a/lib/util/smartGrouping.js +++ b/lib/util/smartGrouping.js @@ -138,14 +138,14 @@ const smartGrouping = (items, groupConfigs) => { } } const targetGroupCount = (options && options.targetGroupCount) || 4; - let sizeValue = force + const sizeValue = force ? items.size : Math.min( items.size, (totalSize * 2) / targetGroupCount + itemsWithGroups.size - items.size - ); + ); if ( sizeValue > bestGroupSize || (force && (!bestGroupOptions || !bestGroupOptions.force)) diff --git a/setup/setup.js b/setup/setup.js index 2586dfd06..43aa314ee 100644 --- a/setup/setup.js +++ b/setup/setup.js @@ -67,7 +67,7 @@ function installYarnAsync() { function exec(command, args, description) { console.log(`Setup: ${description}`); return new Promise((resolve, reject) => { - let cp = require("child_process").spawn(command, args, { + const cp = require("child_process").spawn(command, args, { cwd: root, stdio: "inherit", shell: true @@ -88,7 +88,7 @@ function exec(command, args, description) { function execGetOutput(command, args, description) { console.log(`Setup: ${description}`); return new Promise((resolve, reject) => { - let cp = require("child_process").spawn(command, args, { + const cp = require("child_process").spawn(command, args, { cwd: root, stdio: [process.stdin, "pipe", process.stderr], shell: true diff --git a/test/BinaryMiddleware.unittest.js b/test/BinaryMiddleware.unittest.js index c395013b3..dfdcbe40a 100644 --- a/test/BinaryMiddleware.unittest.js +++ b/test/BinaryMiddleware.unittest.js @@ -108,7 +108,7 @@ describe("BinaryMiddleware", () => { for (const prepend of items) { for (const append of items) { if (c > 1 && append !== undefined) continue; - let data = [prepend, ...caseData, append].filter( + const data = [prepend, ...caseData, append].filter( x => x !== undefined ); if (data.length * c > 200000) continue; diff --git a/test/ChangesAndRemovals.test.js b/test/ChangesAndRemovals.test.js index b60ed9c50..d889ead2c 100644 --- a/test/ChangesAndRemovals.test.js +++ b/test/ChangesAndRemovals.test.js @@ -88,7 +88,6 @@ describe("ChangesAndRemovals", () => { it("should not track modified/removed files during initial watchRun", done => { const compiler = createSingleCompiler(); - let watcher; const watchRunFinished = new Promise(resolve => { compiler.hooks.watchRun.tap("ChangesAndRemovalsTest", compiler => { expect(getChanges(compiler)).toEqual({ @@ -98,7 +97,7 @@ describe("ChangesAndRemovals", () => { resolve(); }); }); - watcher = compiler.watch({ aggregateTimeout: 200 }, err => { + const watcher = compiler.watch({ aggregateTimeout: 200 }, err => { if (err) done(err); }); diff --git a/test/ConfigTestCases.template.js b/test/ConfigTestCases.template.js index be9a3c4d1..8ed1ceed0 100644 --- a/test/ConfigTestCases.template.js +++ b/test/ConfigTestCases.template.js @@ -266,7 +266,7 @@ const describeCases = config => { ? children.reduce( (all, { modules }) => all.concat(modules), modules || [] - ) + ) : modules; if ( allModules.some( @@ -565,7 +565,7 @@ const describeCases = config => { referencingModule.identifier ? referencingModule.identifier.slice( esmIdentifier.length + 1 - ) + ) : fileURLToPath(referencingModule.url) ), options, @@ -637,7 +637,7 @@ const describeCases = config => { ", " )}) {${content}\n})`; - let oldCurrentScript = document.currentScript; + const oldCurrentScript = document.currentScript; document.currentScript = new CurrentScript(subPath); const fn = runInNewContext ? vm.runInNewContext(code, globalContext, p) @@ -657,9 +657,9 @@ const describeCases = config => { ) { return testConfig.modules[module]; } else { - return require( - module.startsWith("node:") ? module.slice(5) : module - ); + return require(module.startsWith("node:") + ? module.slice(5) + : module); } }; diff --git a/test/ContextModuleFactory.unittest.js b/test/ContextModuleFactory.unittest.js index e294bb21c..1c57b1337 100644 --- a/test/ContextModuleFactory.unittest.js +++ b/test/ContextModuleFactory.unittest.js @@ -15,7 +15,7 @@ describe("ContextModuleFactory", () => { setTimeout(() => callback(null, ["/file"])); }; memfs.stat = (file, callback) => { - let err = new Error("fake ENOENT error"); + const err = new Error("fake ENOENT error"); err.code = "ENOENT"; setTimeout(() => callback(err, null)); }; @@ -39,7 +39,7 @@ describe("ContextModuleFactory", () => { setTimeout(() => callback(null, ["/file"])); }; memfs.stat = (file, callback) => { - let err = new Error("fake EACCES error"); + const err = new Error("fake EACCES error"); err.code = "EACCES"; setTimeout(() => callback(err, null)); }; diff --git a/test/NormalModule.unittest.js b/test/NormalModule.unittest.js index 948d40ff3..7c2408253 100644 --- a/test/NormalModule.unittest.js +++ b/test/NormalModule.unittest.js @@ -194,7 +194,7 @@ describe("NormalModule", () => { }); describe("#originalSource", () => { - let expectedSource = "some source"; + const expectedSource = "some source"; beforeEach(() => { normalModule._source = new RawSource(expectedSource); }); diff --git a/test/TestCases.template.js b/test/TestCases.template.js index 600f784b6..eb7deda26 100644 --- a/test/TestCases.template.js +++ b/test/TestCases.template.js @@ -70,7 +70,7 @@ const describeCases = config => { return true; }) .forEach(testName => { - let infraStructureLog = []; + const infraStructureLog = []; describe(testName, () => { const testDirectory = path.join( @@ -112,7 +112,7 @@ const describeCases = config => { emitOnErrors: true, minimizer: [terserForTesting], ...config.optimization - } + } : { removeAvailableModules: true, removeEmptyChunks: true, @@ -128,7 +128,7 @@ const describeCases = config => { chunkIds: "size", minimizer: [terserForTesting], ...config.optimization - }, + }, performance: { hints: false }, diff --git a/test/helpers/FakeDocument.js b/test/helpers/FakeDocument.js index fc653801f..210efb1df 100644 --- a/test/helpers/FakeDocument.js +++ b/test/helpers/FakeDocument.js @@ -33,7 +33,7 @@ module.exports = class FakeDocument { _onElementRemoved(element) { const type = element._type; - let list = this._elementsByTagName.get(type); + const list = this._elementsByTagName.get(type); const idx = list.indexOf(element); list.splice(idx, 1); } @@ -205,7 +205,7 @@ class FakeSheet { .replace(/^https:\/\/test\.cases\/path\//, "") .replace(/^https:\/\/example\.com\/public\/path\//, "") .replace(/^https:\/\/example\.com\//, "") - ); + ); let css = fs.readFileSync(filepath, "utf-8"); css = css.replace(/@import url\("([^"]+)"\);/g, (match, url) => { if (!/^https:\/\/test\.cases\/path\//.test(url)) { diff --git a/test/helpers/expectWarningFactory.js b/test/helpers/expectWarningFactory.js index ef801357c..7f0fda512 100644 --- a/test/helpers/expectWarningFactory.js +++ b/test/helpers/expectWarningFactory.js @@ -1,5 +1,5 @@ module.exports = () => { - let warnings = []; + const warnings = []; let oldWarn; beforeEach(done => { diff --git a/test/helpers/warmup-webpack.js b/test/helpers/warmup-webpack.js index 068500ede..5c8e89d32 100644 --- a/test/helpers/warmup-webpack.js +++ b/test/helpers/warmup-webpack.js @@ -1,7 +1,7 @@ describe("warmup", () => { it("should warmup webpack", done => { let webpack = require("../../"); - let END = new Error("end warmup"); + const END = new Error("end warmup"); webpack( { entry: "data:text/javascript,import 'data:text/javascript,'",