style: improve style of code

This commit is contained in:
alexander.akait 2024-07-30 23:09:42 +03:00
parent 7dc4d18848
commit 423e89b2c7
74 changed files with 309 additions and 291 deletions

View File

@ -75,7 +75,7 @@ module.exports = [
ecmaVersion: 2018, ecmaVersion: 2018,
globals: { globals: {
...globals.node, ...globals.node,
...globals.es2015, ...globals.es2018,
WebAssembly: true WebAssembly: true
} }
}, },
@ -102,6 +102,14 @@ module.exports = [
], ],
"no-inner-declarations": "error", "no-inner-declarations": "error",
"no-loop-func": "off", "no-loop-func": "off",
"prefer-const": [
"error",
{
destructuring: "all",
ignoreReadBeforeAssign: true
}
],
"object-shorthand": "error",
"n/no-missing-require": ["error", { allowModules: ["webpack"] }], "n/no-missing-require": ["error", { allowModules: ["webpack"] }],
"n/no-unsupported-features/node-builtins": [ "n/no-unsupported-features/node-builtins": [
"error", "error",
@ -167,6 +175,10 @@ module.exports = [
...globals.browser, ...globals.browser,
...globals.es5 ...globals.es5
} }
},
rules: {
"prefer-const": "off",
"object-shorthand": "off"
} }
}, },
{ {
@ -174,7 +186,7 @@ module.exports = [
languageOptions: { languageOptions: {
ecmaVersion: 2020, ecmaVersion: 2020,
globals: { globals: {
...globals.es2015 ...globals.es2020
} }
} }
}, },
@ -206,7 +218,8 @@ module.exports = [
{ {
allowExperimental: true allowExperimental: true
} }
] ],
"object-shorthand": "off"
} }
}, },
{ {

View File

@ -111,7 +111,7 @@ class BannerPlugin {
const comment = compilation.getPath(banner, data); const comment = compilation.getPath(banner, data);
compilation.updateAsset(file, old => { compilation.updateAsset(file, old => {
let cached = cache.get(old); const cached = cache.get(old);
if (!cached || cached.comment !== comment) { if (!cached || cached.comment !== comment) {
const source = options.footer const source = options.footer
? new ConcatSource(old, "\n", comment) ? new ConcatSource(old, "\n", comment)

View File

@ -159,7 +159,7 @@ const getModulesSize = modules => {
* @returns {Record<string, number>} the sizes of the modules * @returns {Record<string, number>} the sizes of the modules
*/ */
const getModulesSizes = modules => { const getModulesSizes = modules => {
let sizes = Object.create(null); const sizes = Object.create(null);
for (const module of modules) { for (const module of modules) {
for (const type of module.getSourceTypes()) { for (const type of module.getSourceTypes()) {
sizes[type] = (sizes[type] || 0) + module.size(type); sizes[type] = (sizes[type] || 0) + module.size(type);
@ -916,7 +916,7 @@ class ChunkGraph {
const cgcB = this._getChunkGraphChunk(chunkB); const cgcB = this._getChunkGraphChunk(chunkB);
const allModules = new Set(cgcA.modules); const allModules = new Set(cgcA.modules);
for (const m of cgcB.modules) allModules.add(m); for (const m of cgcB.modules) allModules.add(m);
let modulesSize = getModulesSize(allModules); const modulesSize = getModulesSize(allModules);
const chunkOverhead = const chunkOverhead =
typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000; typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000;
const entryChunkMultiplicator = const entryChunkMultiplicator =

View File

@ -580,7 +580,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
if (options.stage) { if (options.stage) {
throw new Error(errorMessage("it's using the 'stage' option")); throw new Error(errorMessage("it's using the 'stage' option"));
} }
return { ...options, stage: stage }; return { ...options, stage };
}; };
return createFakeHook( return createFakeHook(
{ {
@ -2066,7 +2066,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si
: originModule : originModule
? originModule.context ? originModule.context
: this.compiler.context, : this.compiler.context,
dependencies: dependencies dependencies
}, },
(err, result) => { (err, result) => {
if (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 there are still remaining references we have cycles and want to create a warning
if (remaining > 0) { if (remaining > 0) {
let circularRuntimeChunkInfo = []; const circularRuntimeChunkInfo = [];
for (const info of runtimeChunksMap.values()) { for (const info of runtimeChunksMap.values()) {
if (info.remaining !== 0) { if (info.remaining !== 0) {
circularRuntimeChunkInfo.push(info); circularRuntimeChunkInfo.push(info);

View File

@ -534,8 +534,8 @@ class ContextModule extends Module {
this.context this.context
? [this.context] ? [this.context]
: typeof this.options.resource === "string" : typeof this.options.resource === "string"
? [this.options.resource] ? [this.options.resource]
: /** @type {string[]} */ (this.options.resource), : /** @type {string[]} */ (this.options.resource),
null, null,
SNAPSHOT_OPTIONS, SNAPSHOT_OPTIONS,
(err, snapshot) => { (err, snapshot) => {
@ -950,9 +950,9 @@ module.exports = webpackAsyncContext;`;
/** @type {ContextElementDependency} */ /** @type {ContextElementDependency} */
(block.dependencies[0]); (block.dependencies[0]);
return { return {
dependency: dependency, dependency,
module: /** @type {Module} */ (moduleGraph.getModule(dependency)), module: /** @type {Module} */ (moduleGraph.getModule(dependency)),
block: block, block,
userRequest: dependency.userRequest, userRequest: dependency.userRequest,
chunks: undefined chunks: undefined
}; };
@ -994,8 +994,8 @@ module.exports = webpackAsyncContext;`;
const requestPrefix = hasNoChunk const requestPrefix = hasNoChunk
? "Promise.resolve()" ? "Promise.resolve()"
: hasMultipleOrNoChunks : hasMultipleOrNoChunks
? `Promise.all(ids.slice(${chunksStartPosition}).map(${RuntimeGlobals.ensureChunk}))` ? `Promise.all(ids.slice(${chunksStartPosition}).map(${RuntimeGlobals.ensureChunk}))`
: `${RuntimeGlobals.ensureChunk}(ids[${chunksStartPosition}])`; : `${RuntimeGlobals.ensureChunk}(ids[${chunksStartPosition}])`;
const returnModuleObject = this.getReturnModuleObjectSource( const returnModuleObject = this.getReturnModuleObjectSource(
fakeMap, fakeMap,
true, true,

View File

@ -93,8 +93,8 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
const contextDependencies = new LazySet(); const contextDependencies = new LazySet();
this.hooks.beforeResolve.callAsync( this.hooks.beforeResolve.callAsync(
{ {
context: context, context,
dependencies: dependencies, dependencies,
layer: data.contextInfo.issuerLayer, layer: data.contextInfo.issuerLayer,
resolveOptions, resolveOptions,
fileDependencies, fileDependencies,
@ -160,7 +160,7 @@ module.exports = class ContextModuleFactory extends ModuleFactory {
resolveOptions || EMPTY_RESOLVE_OPTIONS, resolveOptions || EMPTY_RESOLVE_OPTIONS,
"dependencyType", "dependencyType",
dependencies[0].category dependencies[0].category
) )
: resolveOptions : resolveOptions
); );
const loaderResolver = this.resolverFactory.get("loader"); const loaderResolver = this.resolverFactory.get("loader");

View File

@ -146,7 +146,7 @@ const stringifyObj = (
objKeys objKeys
) => { ) => {
let code; let code;
let arr = Array.isArray(obj); const arr = Array.isArray(obj);
if (arr) { if (arr) {
code = `[${ code = `[${
/** @type {any[]} */ (obj) /** @type {any[]} */ (obj)

View File

@ -101,7 +101,7 @@ class DllReferencePlugin {
let content = let content =
"content" in this.options ? this.options.content : undefined; "content" in this.options ? this.options.content : undefined;
if ("manifest" in this.options) { if ("manifest" in this.options) {
let manifestParameter = this.options.manifest; const manifestParameter = this.options.manifest;
let manifest; let manifest;
if (typeof manifestParameter === "string") { if (typeof manifestParameter === "string") {
const data = this._compilationData.get(params); const data = this._compilationData.get(params);
@ -130,7 +130,7 @@ class DllReferencePlugin {
normalModuleFactory normalModuleFactory
); );
new DelegatedModuleFactoryPlugin({ new DelegatedModuleFactoryPlugin({
source: source, source,
type: this.options.type, type: this.options.type,
scope: this.options.scope, scope: this.options.scope,
context: this.options.context || compiler.options.context, context: this.options.context || compiler.options.context,
@ -144,7 +144,7 @@ class DllReferencePlugin {
"DllReferencePlugin", "DllReferencePlugin",
(compilation, params) => { (compilation, params) => {
if ("manifest" in this.options) { if ("manifest" in this.options) {
let manifest = this.options.manifest; const manifest = this.options.manifest;
if (typeof manifest === "string") { if (typeof manifest === "string") {
const data = this._compilationData.get(params); const data = this._compilationData.get(params);
// If there was an error parsing the manifest file, add the // If there was an error parsing the manifest file, add the

View File

@ -662,13 +662,13 @@ class ExportsInfo {
getUsed(name, runtime) { getUsed(name, runtime) {
if (Array.isArray(name)) { if (Array.isArray(name)) {
if (name.length === 0) return this.otherExportsInfo.getUsed(runtime); 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) { if (info.exportsInfo && name.length > 1) {
return info.exportsInfo.getUsed(name.slice(1), runtime); return info.exportsInfo.getUsed(name.slice(1), runtime);
} }
return info.getUsed(runtime); return info.getUsed(runtime);
} }
let info = this.getReadOnlyExportInfo(name); const info = this.getReadOnlyExportInfo(name);
return info.getUsed(runtime); return info.getUsed(runtime);
} }
@ -684,7 +684,7 @@ class ExportsInfo {
if (!this.isUsed(runtime)) return false; if (!this.isUsed(runtime)) return false;
return name; return name;
} }
let info = this.getReadOnlyExportInfo(name[0]); const info = this.getReadOnlyExportInfo(name[0]);
const x = info.getUsedName(name[0], runtime); const x = info.getUsedName(name[0], runtime);
if (x === false) return false; if (x === false) return false;
const arr = x === name[0] && name.length === 1 ? name : [x]; const arr = x === name[0] && name.length === 1 ? name : [x];
@ -702,7 +702,7 @@ class ExportsInfo {
return arr.concat(name.slice(1)); return arr.concat(name.slice(1));
} }
} else { } else {
let info = this.getReadOnlyExportInfo(name); const info = this.getReadOnlyExportInfo(name);
const usedName = info.getUsedName(name, runtime); const usedName = info.getUsedName(name, runtime);
return usedName; return usedName;
} }
@ -1260,7 +1260,7 @@ class ExportInfo {
*/ */
_findTarget(moduleGraph, validTargetModuleFilter, alreadyVisited) { _findTarget(moduleGraph, validTargetModuleFilter, alreadyVisited) {
if (!this._target || this._target.size === 0) return undefined; 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; if (!rawTarget) return undefined;
/** @type {{ module: Module, export: string[] | undefined }} */ /** @type {{ module: Module, export: string[] | undefined }} */
let target = { let target = {

View File

@ -175,7 +175,7 @@ const getSourceForImportExternal = (
? `, { assert: ${JSON.stringify( ? `, { assert: ${JSON.stringify(
dependencyMeta.attributes, dependencyMeta.attributes,
importAssertionReplacer importAssertionReplacer
)} }` )} }`
: `, { with: ${JSON.stringify(dependencyMeta.attributes)} }` : `, { with: ${JSON.stringify(dependencyMeta.attributes)} }`
: ""; : "";
if (!Array.isArray(moduleAndSpecifiers)) { if (!Array.isArray(moduleAndSpecifiers)) {
@ -244,7 +244,7 @@ class ModuleExternalInitFragment extends InitFragment {
? ` assert ${JSON.stringify( ? ` assert ${JSON.stringify(
dependencyMeta.attributes, dependencyMeta.attributes,
importAssertionReplacer importAssertionReplacer
)}` )}`
: ` with ${JSON.stringify(dependencyMeta.attributes)}` : ` with ${JSON.stringify(dependencyMeta.attributes)}`
: "" : ""
};\n`, };\n`,
@ -353,17 +353,17 @@ const getSourceForModuleExternal = (
runtime, runtime,
runtimeTemplate runtimeTemplate
); );
let expression = moduleRemapping || baseAccess; const expression = moduleRemapping || baseAccess;
return { return {
expression, expression,
init: moduleRemapping init: moduleRemapping
? `var x = ${runtimeTemplate.basicFunction( ? `var x = ${runtimeTemplate.basicFunction(
"y", "y",
`var x = {}; ${RuntimeGlobals.definePropertyGetters}(x, y); return x` `var x = {}; ${RuntimeGlobals.definePropertyGetters}(x, y); return x`
)} \nvar y = ${runtimeTemplate.returningFunction( )} \nvar y = ${runtimeTemplate.returningFunction(
runtimeTemplate.returningFunction("x"), runtimeTemplate.returningFunction("x"),
"x" "x"
)}` )}`
: undefined, : undefined,
runtimeRequirements: moduleRemapping runtimeRequirements: moduleRemapping
? RUNTIME_REQUIREMENTS_FOR_MODULE ? RUNTIME_REQUIREMENTS_FOR_MODULE
@ -443,7 +443,7 @@ const getSourceForAmdOrUmdExternal = (
externalVariable, externalVariable,
Array.isArray(request) ? request.join(".") : request, Array.isArray(request) ? request.join(".") : request,
runtimeTemplate runtimeTemplate
) )
: undefined, : undefined,
expression: externalVariable expression: externalVariable
}; };
@ -703,7 +703,7 @@ class ExternalModule extends Module {
/** @type {string} */ /** @type {string} */
(runtimeTemplate.outputOptions.importMetaName), (runtimeTemplate.outputOptions.importMetaName),
runtimeTemplate.supportNodePrefixForCoreModules() runtimeTemplate.supportNodePrefixForCoreModules()
) )
: getSourceForCommonJsExternal(request); : getSourceForCommonJsExternal(request);
case "amd": case "amd":
case "amd-require": case "amd-require":

View File

@ -1670,7 +1670,7 @@ class FileSystemInfo {
const module = require.cache[path]; const module = require.cache[path];
if (module && Array.isArray(module.children)) { if (module && Array.isArray(module.children)) {
children: for (const child of module.children) { children: for (const child of module.children) {
let childPath = child.filename; const childPath = child.filename;
if (childPath) { if (childPath) {
push({ push({
type: RBDT_FILE, type: RBDT_FILE,
@ -1682,7 +1682,7 @@ class FileSystemInfo {
const context = dirname(this.fs, path); const context = dirname(this.fs, path);
for (const modulePath of module.paths) { for (const modulePath of module.paths) {
if (childPath.startsWith(modulePath)) { if (childPath.startsWith(modulePath)) {
let subPath = childPath.slice(modulePath.length + 1); const subPath = childPath.slice(modulePath.length + 1);
const packageMatch = /^(@[^\\/]+[\\/])[^\\/]+/.exec( const packageMatch = /^(@[^\\/]+[\\/])[^\\/]+/.exec(
subPath subPath
); );
@ -1755,7 +1755,7 @@ class FileSystemInfo {
); );
} else if (imp.d > -1) { } else if (imp.d > -1) {
// import() // import()
let expr = source.substring(imp.s, imp.e).trim(); const expr = source.substring(imp.s, imp.e).trim();
dependency = parseString(expr); dependency = parseString(expr);
} else { } else {
// e.g. import.meta // e.g. import.meta
@ -3388,7 +3388,7 @@ class FileSystemInfo {
: { : {
...timestamp, ...timestamp,
...hash ...hash
}; };
this._contextTshs.set(path, result); this._contextTshs.set(path, result);
callback(null, result); callback(null, result);
}; };

View File

@ -142,7 +142,7 @@ class HotModuleReplacementPlugin {
(arg.items).filter(param => param.isString()); (arg.items).filter(param => param.isString());
} }
/** @type {string[]} */ /** @type {string[]} */
let requests = []; const requests = [];
if (params.length > 0) { if (params.length > 0) {
params.forEach((param, idx) => { params.forEach((param, idx) => {
const request = /** @type {string} */ (param.string); const request = /** @type {string} */ (param.string);
@ -500,7 +500,7 @@ class HotModuleReplacementPlugin {
: compilation.codeGenerationResults.getHash( : compilation.codeGenerationResults.getHash(
module, module,
chunk.runtime chunk.runtime
); );
if (records.chunkModuleHashes[key] !== hash) { if (records.chunkModuleHashes[key] !== hash) {
updatedModules.add(module, chunk); updatedModules.add(module, chunk);
} }
@ -629,7 +629,7 @@ class HotModuleReplacementPlugin {
: compilation.codeGenerationResults.getHash( : compilation.codeGenerationResults.getHash(
module, module,
newRuntime newRuntime
); );
if (hash !== oldHash) { if (hash !== oldHash) {
if (module.type === WEBPACK_MODULE_TYPE_RUNTIME) { if (module.type === WEBPACK_MODULE_TYPE_RUNTIME) {
newRuntimeModules = newRuntimeModules || []; newRuntimeModules = newRuntimeModules || [];
@ -798,7 +798,7 @@ To fix this, make sure to include [runtime] in the output.hotUpdateMainFilename
Array.from(removedModules, m => Array.from(removedModules, m =>
chunkGraph.getModuleId(m) chunkGraph.getModuleId(m)
) )
) )
}; };
const source = new RawSource(JSON.stringify(hotUpdateMainJson)); const source = new RawSource(JSON.stringify(hotUpdateMainJson));

View File

@ -163,7 +163,7 @@ ModuleFilenameHelpers.createFilename = (
? options ? options
: { : {
moduleFilenameTemplate: options moduleFilenameTemplate: options
}) })
}; };
let absoluteResourcePath; let absoluteResourcePath;
@ -212,9 +212,9 @@ ModuleFilenameHelpers.createFilename = (
if (typeof opts.moduleFilenameTemplate === "function") { if (typeof opts.moduleFilenameTemplate === "function") {
return opts.moduleFilenameTemplate( return opts.moduleFilenameTemplate(
lazyObject({ lazyObject({
identifier: identifier, identifier,
shortIdentifier: shortIdentifier, shortIdentifier,
resource: resource, resource,
resourcePath: memoize(resourcePath), resourcePath: memoize(resourcePath),
absoluteResourcePath: memoize(absoluteResourcePath), absoluteResourcePath: memoize(absoluteResourcePath),
loaders: memoize(loaders), loaders: memoize(loaders),

View File

@ -17,7 +17,7 @@ class ModuleRestoreError extends WebpackError {
constructor(module, err) { constructor(module, err) {
let message = "Module restore failed: "; let message = "Module restore failed: ";
/** @type {string | undefined} */ /** @type {string | undefined} */
let details = undefined; const details = undefined;
if (err !== null && typeof err === "object") { if (err !== null && typeof err === "object") {
if (typeof err.stack === "string" && err.stack) { if (typeof err.stack === "string" && err.stack) {
const stack = err.stack; const stack = err.stack;

View File

@ -17,7 +17,7 @@ class ModuleStoreError extends WebpackError {
constructor(module, err) { constructor(module, err) {
let message = "Module storing failed: "; let message = "Module storing failed: ";
/** @type {string | undefined} */ /** @type {string | undefined} */
let details = undefined; const details = undefined;
if (err !== null && typeof err === "object") { if (err !== null && typeof err === "object") {
if (typeof err.stack === "string" && err.stack) { if (typeof err.stack === "string" && err.stack) {
const stack = err.stack; const stack = err.stack;

View File

@ -340,8 +340,8 @@ module.exports = class MultiCompiler {
* @returns {Compiler[]} compilers * @returns {Compiler[]} compilers
*/ */
const getReadyCompilers = () => { const getReadyCompilers = () => {
let readyCompilers = []; const readyCompilers = [];
let list = remainingCompilers; const list = remainingCompilers;
remainingCompilers = []; remainingCompilers = [];
for (const c of list) { for (const c of list) {
const dependencies = this.dependencies.get(c); const dependencies = this.dependencies.get(c);

View File

@ -142,14 +142,14 @@ const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => {
const mapper = !sourceRoot const mapper = !sourceRoot
? source => source ? source => source
: sourceRoot.endsWith("/") : sourceRoot.endsWith("/")
? source => ? source =>
source.startsWith("/") source.startsWith("/")
? `${sourceRoot.slice(0, -1)}${source}` ? `${sourceRoot.slice(0, -1)}${source}`
: `${sourceRoot}${source}` : `${sourceRoot}${source}`
: source => : source =>
source.startsWith("/") source.startsWith("/")
? `${sourceRoot}${source}` ? `${sourceRoot}${source}`
: `${sourceRoot}/${source}`; : `${sourceRoot}/${source}`;
const newSources = sourceMap.sources.map(source => const newSources = sourceMap.sources.map(source =>
contextifySourceUrl(context, mapper(source), associatedObjectForCache) contextifySourceUrl(context, mapper(source), associatedObjectForCache)
); );
@ -743,7 +743,7 @@ class NormalModule extends Module {
_module: this, _module: this,
_compilation: compilation, _compilation: compilation,
_compiler: compilation.compiler, _compiler: compilation.compiler,
fs: fs fs
}; };
Object.assign(loaderContext, options.loader); Object.assign(loaderContext, options.loader);
@ -859,7 +859,7 @@ class NormalModule extends Module {
currentLoader currentLoader
? compilation.runtimeTemplate.requestShortener.shorten( ? compilation.runtimeTemplate.requestShortener.shorten(
currentLoader.loader currentLoader.loader
) )
: "unknown" : "unknown"
}) didn't return a Buffer or String` }) didn't return a Buffer or String`
); );
@ -1161,10 +1161,10 @@ class NormalModule extends Module {
if (absolute !== dep && ABSOLUTE_PATH_REGEX.test(absolute)) { if (absolute !== dep && ABSOLUTE_PATH_REGEX.test(absolute)) {
(depWithoutGlob !== dep (depWithoutGlob !== dep
? /** @type {NonNullable<KnownBuildInfo["contextDependencies"]>} */ ? /** @type {NonNullable<KnownBuildInfo["contextDependencies"]>} */
( (
/** @type {BuildInfo} */ (this.buildInfo) /** @type {BuildInfo} */ (this.buildInfo)
.contextDependencies .contextDependencies
) )
: deps : deps
).add(absolute); ).add(absolute);
} }
@ -1241,8 +1241,8 @@ class NormalModule extends Module {
source, source,
current: this, current: this,
module: this, module: this,
compilation: compilation, compilation,
options: options options
}); });
} catch (e) { } catch (e) {
handleParseError(/** @type {Error} */ (e)); handleParseError(/** @type {Error} */ (e));
@ -1357,7 +1357,7 @@ class NormalModule extends Module {
const source = this.error const source = this.error
? new RawSource( ? new RawSource(
"throw new Error(" + JSON.stringify(this.error.message) + ");" "throw new Error(" + JSON.stringify(this.error.message) + ");"
) )
: /** @type {Generator} */ (this.generator).generate(this, { : /** @type {Generator} */ (this.generator).generate(this, {
dependencyTemplates, dependencyTemplates,
runtimeTemplate, runtimeTemplate,
@ -1369,7 +1369,7 @@ class NormalModule extends Module {
codeGenerationResults, codeGenerationResults,
getData, getData,
type type
}); });
if (source) { if (source) {
sources.set(type, new CachedSource(source)); sources.set(type, new CachedSource(source));

View File

@ -479,8 +479,8 @@ class NormalModuleFactory extends ModuleFactory {
noPreAutoLoaders || noPrePostAutoLoaders noPreAutoLoaders || noPrePostAutoLoaders
? 2 ? 2
: noAutoLoaders : noAutoLoaders
? 1 ? 1
: 0 : 0
) )
.split(/!+/); .split(/!+/);
unresolvedResource = /** @type {string} */ (rawElements.pop()); unresolvedResource = /** @type {string} */ (rawElements.pop());
@ -652,7 +652,7 @@ class NormalModuleFactory extends ModuleFactory {
} }
for (const loader of /** @type {LoaderItem[]} */ (preLoaders)) for (const loader of /** @type {LoaderItem[]} */ (preLoaders))
allLoaders.push(loader); allLoaders.push(loader);
let type = /** @type {string} */ (settings.type); const type = /** @type {string} */ (settings.type);
const resolveOptions = settings.resolve; const resolveOptions = settings.resolve;
const layer = settings.layer; const layer = settings.layer;
if (layer !== undefined && !layers) { if (layer !== undefined && !layers) {
@ -763,7 +763,7 @@ class NormalModuleFactory extends ModuleFactory {
resolveOptions || EMPTY_RESOLVE_OPTIONS, resolveOptions || EMPTY_RESOLVE_OPTIONS,
"dependencyType", "dependencyType",
dependencyType dependencyType
) )
: resolveOptions : resolveOptions
); );
this.resolveResource( 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) const type = /\.mjs$/i.test(parsedResult.path)
? "module" ? "module"
: /\.cjs$/i.test(parsedResult.path) : /\.cjs$/i.test(parsedResult.path)
? "commonjs" ? "commonjs"
: /** @type {ResolveRequest} */ : /** @type {ResolveRequest} */
(resolveRequest).descriptionFileData === undefined (resolveRequest).descriptionFileData === undefined
? undefined ? undefined
: /** @type {ResolveRequest} */ : /** @type {ResolveRequest} */
(resolveRequest).descriptionFileData.type; (resolveRequest).descriptionFileData.type;
const resolved = { const resolved = {
loader: parsedResult.path, loader: parsedResult.path,
type, type,

View File

@ -317,8 +317,8 @@ class SourceMapDevToolPlugin {
ModuleFilenameHelpers.createFilename( ModuleFilenameHelpers.createFilename(
module, module,
{ {
moduleFilenameTemplate: moduleFilenameTemplate, moduleFilenameTemplate,
namespace: namespace namespace
}, },
{ {
requestShortener, requestShortener,
@ -382,7 +382,7 @@ class SourceMapDevToolPlugin {
module, module,
{ {
moduleFilenameTemplate: fallbackModuleFilenameTemplate, moduleFilenameTemplate: fallbackModuleFilenameTemplate,
namespace: namespace namespace
}, },
{ {
requestShortener, requestShortener,
@ -457,7 +457,7 @@ class SourceMapDevToolPlugin {
/** @type {string | false | (function(PathData, AssetInfo=): string)} */ /** @type {string | false | (function(PathData, AssetInfo=): string)} */
let currentSourceMappingURLComment = sourceMappingURLComment; let currentSourceMappingURLComment = sourceMappingURLComment;
let cssExtensionDetected = const cssExtensionDetected =
CSS_EXTENSION_DETECT_REGEXP.test(file); CSS_EXTENSION_DETECT_REGEXP.test(file);
resetRegexpState(CSS_EXTENSION_DETECT_REGEXP); resetRegexpState(CSS_EXTENSION_DETECT_REGEXP);
if ( if (
@ -473,7 +473,7 @@ class SourceMapDevToolPlugin {
} }
const sourceMapString = JSON.stringify(sourceMap); const sourceMapString = JSON.stringify(sourceMap);
if (sourceMapFilename) { if (sourceMapFilename) {
let filename = file; const filename = file;
const sourceMapContentHash = const sourceMapContentHash =
usesContentHash && usesContentHash &&
/** @type {string} */ ( /** @type {string} */ (
@ -488,7 +488,7 @@ class SourceMapDevToolPlugin {
outputFs, outputFs,
`/${options.fileContext}`, `/${options.fileContext}`,
`/${filename}` `/${filename}`
) )
: filename, : filename,
contentHash: sourceMapContentHash contentHash: sourceMapContentHash
}; };
@ -503,7 +503,7 @@ class SourceMapDevToolPlugin {
outputFs, outputFs,
dirname(outputFs, `/${file}`), dirname(outputFs, `/${file}`),
`/${sourceMapFile}` `/${sourceMapFile}`
); );
/** @type {Source} */ /** @type {Source} */
let asset = new RawSource(source); let asset = new RawSource(source);
if (currentSourceMappingURLComment !== false) { if (currentSourceMappingURLComment !== false) {

View File

@ -155,7 +155,7 @@ const replacePathVariables = (path, data, assetInfo) => {
// [ext] - .js // [ext] - .js
if (typeof data.filename === "string") { if (typeof data.filename === "string") {
// check that filename is data uri // check that filename is data uri
let match = data.filename.match(/^data:([^;,]+)/); const match = data.filename.match(/^data:([^;,]+)/);
if (match) { if (match) {
const ext = mime.extension(match[1]); const ext = mime.extension(match[1]);
const emptyReplacer = replacer("", true); const emptyReplacer = replacer("", true);
@ -302,7 +302,7 @@ const replacePathVariables = (path, data, assetInfo) => {
? /** @type {ChunkGraph} */ (chunkGraph).getRenderedModuleHash( ? /** @type {ChunkGraph} */ (chunkGraph).getRenderedModuleHash(
module, module,
data.runtime data.runtime
) )
: module.hash : module.hash
), ),
"hashWithLength" in module ? module.hashWithLength : undefined, "hashWithLength" in module ? module.hashWithLength : undefined,

View File

@ -259,7 +259,7 @@ class WebpackOptionsApply extends OptionsApply {
append: hidden ? false : undefined, append: hidden ? false : undefined,
module: moduleMaps ? true : cheap ? false : true, module: moduleMaps ? true : cheap ? false : true,
columns: cheap ? false : true, columns: cheap ? false : true,
noSources: noSources, noSources,
namespace: options.output.devtoolNamespace namespace: options.output.devtoolNamespace
}).apply(compiler); }).apply(compiler);
} else if (options.devtool.includes("eval")) { } else if (options.devtool.includes("eval")) {
@ -336,7 +336,7 @@ class WebpackOptionsApply extends OptionsApply {
options.externalsPresets.node ? "node" : "web" options.externalsPresets.node ? "node" : "web"
}.js` }.js`
) )
}), }),
entries: !lazyOptions || lazyOptions.entries !== false, entries: !lazyOptions || lazyOptions.entries !== false,
imports: !lazyOptions || lazyOptions.imports !== false, imports: !lazyOptions || lazyOptions.imports !== false,
test: (lazyOptions && lazyOptions.test) || undefined test: (lazyOptions && lazyOptions.test) || undefined

View File

@ -330,12 +330,12 @@ const visitModules = (
let statConnectedChunkGroups = 0; let statConnectedChunkGroups = 0;
let statProcessedChunkGroupsForMerging = 0; let statProcessedChunkGroupsForMerging = 0;
let statMergedAvailableModuleSets = 0; let statMergedAvailableModuleSets = 0;
let statForkedAvailableModules = 0; const statForkedAvailableModules = 0;
let statForkedAvailableModulesCount = 0; const statForkedAvailableModulesCount = 0;
let statForkedAvailableModulesCountPlus = 0; const statForkedAvailableModulesCountPlus = 0;
let statForkedMergedModulesCount = 0; const statForkedMergedModulesCount = 0;
let statForkedMergedModulesCountPlus = 0; const statForkedMergedModulesCountPlus = 0;
let statForkedResultModulesCount = 0; const statForkedResultModulesCount = 0;
let statChunkGroupInfoUpdated = 0; let statChunkGroupInfoUpdated = 0;
let statChildChunkGroupsReconnected = 0; let statChildChunkGroupsReconnected = 0;

View File

@ -38,7 +38,7 @@ class IdleFileCachePlugin {
* @returns {void} * @returns {void}
*/ */
apply(compiler) { apply(compiler) {
let strategy = this.strategy; const strategy = this.strategy;
const idleTimeout = this.idleTimeout; const idleTimeout = this.idleTimeout;
const idleTimeoutForInitialStore = Math.min( const idleTimeoutForInitialStore = Math.min(
idleTimeout, idleTimeout,
@ -202,18 +202,11 @@ class IdleFileCachePlugin {
}s.` }s.`
); );
} }
idleTimer = setTimeout( idleTimer = setTimeout(() => {
() => { idleTimer = undefined;
idleTimer = undefined; isIdle = true;
isIdle = true; resolvedPromise.then(processIdleTasks);
resolvedPromise.then(processIdleTasks); }, Math.min(isInitialStore ? idleTimeoutForInitialStore : Infinity, isLargeChange ? idleTimeoutAfterLargeChanges : Infinity, idleTimeout));
},
Math.min(
isInitialStore ? idleTimeoutForInitialStore : Infinity,
isLargeChange ? idleTimeoutAfterLargeChanges : Infinity,
idleTimeout
)
);
idleTimer.unref(); idleTimer.unref();
} }
); );

View File

@ -298,7 +298,7 @@ const getArguments = (schema = webpackSchema) => {
return 0; return 0;
} }
if (Array.isArray(schemaPart.items)) { if (Array.isArray(schemaPart.items)) {
let i = 0; const i = 0;
for (const item of schemaPart.items) { for (const item of schemaPart.items) {
addedArguments += traverse( addedArguments += traverse(
item, item,
@ -390,7 +390,7 @@ const cliAddedItems = new WeakMap();
const getObjectAndProperty = (config, schemaPath, index = 0) => { const getObjectAndProperty = (config, schemaPath, index = 0) => {
if (!schemaPath) return { value: config }; if (!schemaPath) return { value: config };
const parts = schemaPath.split("."); const parts = schemaPath.split(".");
let property = parts.pop(); const property = parts.pop();
let current = config; let current = config;
let i = 0; let i = 0;
for (const part of parts) { for (const part of parts) {
@ -444,7 +444,7 @@ const getObjectAndProperty = (config, schemaPath, index = 0) => {
current = value; current = value;
i++; i++;
} }
let value = current[property]; const value = current[property];
if (property.endsWith("[]")) { if (property.endsWith("[]")) {
const name = property.slice(0, -2); const name = property.slice(0, -2);
const value = current[name]; const value = current[name];
@ -627,13 +627,13 @@ const processArguments = (args, config, values) => {
currentProblems.push({ currentProblems.push({
...problem, ...problem,
argument: key, argument: key,
value: value, value,
index: i index: i
}); });
} }
problems.push(...currentProblems); problems.push(...currentProblems);
}; };
let value = values[key]; const value = values[key];
if (Array.isArray(value)) { if (Array.isArray(value)) {
for (let i = 0; i < value.length; i++) { for (let i = 0; i < value.length; i++) {
processValue(value[i], i); processValue(value[i], i);

View File

@ -167,15 +167,15 @@ const applyWebpackOptionsDefaults = (options, compilerIndex) => {
const { mode, name, target } = options; const { mode, name, target } = options;
let targetProperties = const targetProperties =
target === false target === false
? /** @type {false} */ (false) ? /** @type {false} */ (false)
: typeof target === "string" : typeof target === "string"
? getTargetProperties(target, /** @type {Context} */ (options.context)) ? getTargetProperties(target, /** @type {Context} */ (options.context))
: getTargetsProperties( : getTargetsProperties(
/** @type {string[]} */ (target), /** @type {string[]} */ (target),
/** @type {Context} */ (options.context) /** @type {Context} */ (options.context)
); );
const development = mode === "development"; const development = mode === "development";
const production = mode === "production" || !mode; const production = mode === "production" || !mode;
@ -275,8 +275,8 @@ const applyWebpackOptionsDefaults = (options, compilerIndex) => {
validExternalTypes.includes(options.output.library.type) validExternalTypes.includes(options.output.library.type)
? /** @type {ExternalsType} */ (options.output.library.type) ? /** @type {ExternalsType} */ (options.output.library.type)
: options.output.module : options.output.module
? "module" ? "module"
: "var"; : "var";
}); });
applyNodeDefaults(options.node, { applyNodeDefaults(options.node, {
@ -340,7 +340,7 @@ const applyWebpackOptionsDefaults = (options, compilerIndex) => {
node: targetProperties.node, node: targetProperties.node,
nwjs: targetProperties.nwjs, nwjs: targetProperties.nwjs,
electron: targetProperties.electron electron: targetProperties.electron
} }
}; };
}; };
@ -475,7 +475,7 @@ const applySnapshotDefaults = (snapshot, { production, futureDefaults }) => {
process.versions.pnp === "3" process.versions.pnp === "3"
? [ ? [
/^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/ /^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/
] ]
: [/^(.+?[\\/]node_modules[\\/])/] : [/^(.+?[\\/]node_modules[\\/])/]
); );
F(snapshot, "immutablePaths", () => F(snapshot, "immutablePaths", () =>
@ -912,8 +912,9 @@ const applyOutputDefaults = (
} catch (e) { } catch (e) {
if (/** @type {Error & { code: string }} */ (e).code !== "ENOENT") { if (/** @type {Error & { code: string }} */ (e).code !== "ENOENT") {
/** @type {Error & { code: string }} */ /** @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; throw e;
} }
return ""; return "";

View File

@ -93,7 +93,7 @@ class CssExportsGenerator extends Generator {
chunkGraph: generateContext.chunkGraph, chunkGraph: generateContext.chunkGraph,
module, module,
runtime: generateContext.runtime, runtime: generateContext.runtime,
runtimeRequirements: runtimeRequirements, runtimeRequirements,
concatenationScope: generateContext.concatenationScope, concatenationScope: generateContext.concatenationScope,
codeGenerationResults: generateContext.codeGenerationResults, codeGenerationResults: generateContext.codeGenerationResults,
initFragments, initFragments,
@ -135,7 +135,7 @@ class CssExportsGenerator extends Generator {
const usedIdentifiers = new Set(); const usedIdentifiers = new Set();
for (const [name, v] of cssExportsData.exports) { for (const [name, v] of cssExportsData.exports) {
let identifier = Template.toIdentifier(name); let identifier = Template.toIdentifier(name);
let i = 0; const i = 0;
while (usedIdentifiers.has(identifier)) { while (usedIdentifiers.has(identifier)) {
identifier = Template.toIdentifier(name + i); identifier = Template.toIdentifier(name + i);
} }
@ -161,7 +161,7 @@ class CssExportsGenerator extends Generator {
); );
} }
const exports = []; 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)}`); exports.push(`\t${JSON.stringify(name)}: ${JSON.stringify(v)}`);
} }
return new RawSource( return new RawSource(

View File

@ -146,7 +146,7 @@ const LZWEncode = str => {
let encoded = ""; let encoded = "";
let phrase = str[0]; let phrase = str[0];
let code = 256; let code = 256;
let maxCode = "\uffff".charCodeAt(0); const maxCode = "\uffff".charCodeAt(0);
for (let i = 1; i < str.length; i++) { for (let i = 1; i < str.length; i++) {
const c = str[i]; const c = str[i];
if (map.has(phrase + c)) { if (map.has(phrase + c)) {
@ -259,12 +259,12 @@ class CssModulesPlugin {
generatorOptions.exportsConvention, generatorOptions.exportsConvention,
generatorOptions.localIdentName, generatorOptions.localIdentName,
generatorOptions.esModule generatorOptions.esModule
) )
: new CssGenerator( : new CssGenerator(
generatorOptions.exportsConvention, generatorOptions.exportsConvention,
generatorOptions.localIdentName, generatorOptions.localIdentName,
generatorOptions.esModule generatorOptions.esModule
); );
}); });
normalModuleFactory.hooks.createModuleClass normalModuleFactory.hooks.createModuleClass
.for(type) .for(type)
@ -623,7 +623,7 @@ class CssModulesPlugin {
const cacheEntry = this._moduleCache.get(moduleSourceContent); const cacheEntry = this._moduleCache.get(moduleSourceContent);
/** @type {Inheritance} */ /** @type {Inheritance} */
let inheritance = [[module.cssLayer, module.supports, module.media]]; const inheritance = [[module.cssLayer, module.supports, module.media]];
if (module.inheritance) { if (module.inheritance) {
inheritance.push(...module.inheritance); inheritance.push(...module.inheritance);
} }
@ -720,7 +720,7 @@ class CssModulesPlugin {
? Array.from( ? Array.from(
exports, exports,
([n, v]) => `${escapeCss(n)}:${escapeCss(v)}/` ([n, v]) => `${escapeCss(n)}:${escapeCss(v)}/`
).join("") ).join("")
: "" : ""
}${esModule ? "&" : ""}${escapeCss(moduleId)}` }${esModule ? "&" : ""}${escapeCss(moduleId)}`
); );

View File

@ -206,7 +206,7 @@ class CssParser extends Parser {
/** @type {[number, number] | undefined} */ /** @type {[number, number] | undefined} */
let lastIdentifier = undefined; let lastIdentifier = undefined;
/** @type [string, number, number][] */ /** @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 }} */ /** @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; let importData = undefined;
/** @type {boolean} */ /** @type {boolean} */
@ -320,7 +320,7 @@ class CssParser extends Parser {
if (input.charCodeAt(pos) === CC_RIGHT_CURLY) break; if (input.charCodeAt(pos) === CC_RIGHT_CURLY) break;
pos = walkCssTokens.eatWhitespaceAndComments(input, pos); pos = walkCssTokens.eatWhitespaceAndComments(input, pos);
if (pos === input.length) return pos; if (pos === input.length) return pos;
let start = pos; const start = pos;
let name; let name;
[pos, name] = eatText(input, pos, eatExportName); [pos, name] = eatText(input, pos, eatExportName);
if (pos === input.length) return pos; if (pos === input.length) return pos;
@ -428,7 +428,10 @@ class CssParser extends Parser {
return isNextRulePrelude; return isNextRulePrelude;
}, },
url: (input, start, end, contentStart, contentEnd) => { url: (input, start, end, contentStart, contentEnd) => {
let value = normalizeUrl(input.slice(contentStart, contentEnd), false); const value = normalizeUrl(
input.slice(contentStart, contentEnd),
false
);
switch (scope) { switch (scope) {
case CSS_MODE_IN_AT_IMPORT: { case CSS_MODE_IN_AT_IMPORT: {
@ -530,7 +533,7 @@ class CssParser extends Parser {
(last[0].replace(/\\/g, "").toLowerCase() === "url" || (last[0].replace(/\\/g, "").toLowerCase() === "url" ||
IMAGE_SET_FUNCTION.test(last[0].replace(/\\/g, ""))) 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 // Ignore `url()`, `url('')` and `url("")`, they are valid by spec
if (value.length === 0) { if (value.length === 0) {
@ -884,7 +887,7 @@ class CssParser extends Parser {
} }
if (name === "var") { if (name === "var") {
let pos = walkCssTokens.eatWhitespaceAndComments(input, end); const pos = walkCssTokens.eatWhitespaceAndComments(input, end);
if (pos === input.length) return pos; if (pos === input.length) return pos;
const [newPos, name] = eatText(input, pos, eatNameInVar); const [newPos, name] = eatText(input, pos, eatNameInVar);
if (!name.startsWith("--")) return end; if (!name.startsWith("--")) return end;
@ -920,7 +923,7 @@ class CssParser extends Parser {
) { ) {
modeData = balanced[balanced.length - 1] modeData = balanced[balanced.length - 1]
? /** @type {"local" | "global"} */ ? /** @type {"local" | "global"} */
(balanced[balanced.length - 1][0]) (balanced[balanced.length - 1][0])
: undefined; : undefined;
const dep = new ConstDependency("", [start, end]); const dep = new ConstDependency("", [start, end]);
module.addPresentationalDependency(dep); module.addPresentationalDependency(dep);

View File

@ -431,7 +431,7 @@ const consumePotentialPseudo = (input, pos, callbacks) => {
if (!callbacks.isSelector(input, pos) || !_startsIdentifier(input, pos)) if (!callbacks.isSelector(input, pos) || !_startsIdentifier(input, pos))
return pos; return pos;
pos = _consumeIdentifier(input, pos, callbacks); pos = _consumeIdentifier(input, pos, callbacks);
let cc = input.charCodeAt(pos); const cc = input.charCodeAt(pos);
if (cc === CC_LEFT_PARENTHESIS) { if (cc === CC_LEFT_PARENTHESIS) {
pos++; pos++;
if (callbacks.pseudoFunction !== undefined) { if (callbacks.pseudoFunction !== undefined) {
@ -723,7 +723,7 @@ module.exports.isIdentStartCodePoint = isIdentStartCodePoint;
*/ */
module.exports.eatComments = (input, pos) => { module.exports.eatComments = (input, pos) => {
for (;;) { for (;;) {
let originalPos = pos; const originalPos = pos;
pos = consumeComments(input, pos, {}); pos = consumeComments(input, pos, {});
if (originalPos === pos) { if (originalPos === pos) {
break; break;
@ -753,7 +753,7 @@ module.exports.eatWhitespace = (input, pos) => {
*/ */
module.exports.eatWhitespaceAndComments = (input, pos) => { module.exports.eatWhitespaceAndComments = (input, pos) => {
for (;;) { for (;;) {
let originalPos = pos; const originalPos = pos;
pos = consumeComments(input, pos, {}); pos = consumeComments(input, pos, {});
while (_isWhiteSpace(input.charCodeAt(pos))) { while (_isWhiteSpace(input.charCodeAt(pos))) {
pos++; pos++;

View File

@ -317,7 +317,7 @@ class AMDDefineDependencyParserPlugin {
} }
} }
} }
let fnRenames = new Map(); const fnRenames = new Map();
if (array) { if (array) {
/** @type {Record<number, string>} */ /** @type {Record<number, string>} */
const identifiers = {}; const identifiers = {};

View File

@ -69,8 +69,8 @@ exports.create = (
) => { ) => {
if (param.isTemplateString()) { if (param.isTemplateString()) {
const quasis = /** @type {BasicEvaluatedExpression[]} */ (param.quasis); const quasis = /** @type {BasicEvaluatedExpression[]} */ (param.quasis);
let prefixRaw = /** @type {string} */ (quasis[0].string); const prefixRaw = /** @type {string} */ (quasis[0].string);
let postfixRaw = const postfixRaw =
/** @type {string} */ /** @type {string} */
(quasis.length > 1 ? quasis[quasis.length - 1].string : ""); (quasis.length > 1 ? quasis[quasis.length - 1].string : "");
@ -180,10 +180,10 @@ exports.create = (
((param.prefix && param.prefix.isString()) || ((param.prefix && param.prefix.isString()) ||
(param.postfix && param.postfix.isString())) (param.postfix && param.postfix.isString()))
) { ) {
let prefixRaw = const prefixRaw =
/** @type {string} */ /** @type {string} */
(param.prefix && param.prefix.isString() ? param.prefix.string : ""); (param.prefix && param.prefix.isString() ? param.prefix.string : "");
let postfixRaw = const postfixRaw =
/** @type {string} */ /** @type {string} */
(param.postfix && param.postfix.isString() ? param.postfix.string : ""); (param.postfix && param.postfix.isString() ? param.postfix.string : "");
const prefixRange = const prefixRange =

View File

@ -345,7 +345,7 @@ HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependen
if (dep.referencedPropertiesInDestructuring) { if (dep.referencedPropertiesInDestructuring) {
const prefixedIds = ids[0] === "default" ? ids.slice(1) : ids; const prefixedIds = ids[0] === "default" ? ids.slice(1) : ids;
for (let { for (const {
id, id,
shorthand, shorthand,
range range

View File

@ -124,7 +124,7 @@ ImportDependency.Template = class ImportDependencyTemplate extends (
); );
const content = runtimeTemplate.moduleNamespacePromise({ const content = runtimeTemplate.moduleNamespacePromise({
chunkGraph, chunkGraph,
block: block, block,
module: /** @type {Module} */ (moduleGraph.getModule(dep)), module: /** @type {Module} */ (moduleGraph.getModule(dep)),
request: dep.request, request: dep.request,
strict: /** @type {BuildMeta} */ (module.buildMeta).strictHarmonyModule, strict: /** @type {BuildMeta} */ (module.buildMeta).strictHarmonyModule,

View File

@ -64,7 +64,7 @@ class ProvidedDependency extends ModuleDependency {
* @returns {(string[] | ReferencedExport)[]} referenced exports * @returns {(string[] | ReferencedExport)[]} referenced exports
*/ */
getReferencedExports(moduleGraph, runtime) { getReferencedExports(moduleGraph, runtime) {
let ids = this.ids; const ids = this.ids;
if (ids.length === 0) return Dependency.EXPORTS_OBJECT_REFERENCED; if (ids.length === 0) return Dependency.EXPORTS_OBJECT_REFERENCED;
return [ids]; return [ids];
} }

View File

@ -241,7 +241,7 @@ class WorkerPlugin {
insertLocation: arg2 insertLocation: arg2
? /** @type {Range} */ (arg2.range) ? /** @type {Range} */ (arg2.range)
: /** @type {Range} */ (arg1.range)[1] : /** @type {Range} */ (arg1.range)[1]
}; };
const { options: importOptions, errors: commentErrors } = const { options: importOptions, errors: commentErrors } =
parser.parseCommentOptions(/** @type {Range} */ (expr.range)); parser.parseCommentOptions(/** @type {Range} */ (expr.range));
@ -258,7 +258,7 @@ class WorkerPlugin {
} }
/** @type {EntryOptions} */ /** @type {EntryOptions} */
let entryOptions = {}; const entryOptions = {};
if (importOptions) { if (importOptions) {
if (importOptions.webpackIgnore !== undefined) { if (importOptions.webpackIgnore !== undefined) {
@ -316,9 +316,9 @@ class WorkerPlugin {
} }
if (entryOptions.runtime === undefined) { if (entryOptions.runtime === undefined) {
let i = workerIndexMap.get(parser.state) || 0; const i = workerIndexMap.get(parser.state) || 0;
workerIndexMap.set(parser.state, i + 1); workerIndexMap.set(parser.state, i + 1);
let name = `${cachedContextify( const name = `${cachedContextify(
parser.state.module.identifier() parser.state.module.identifier()
)}|${i}`; )}|${i}`;
const hash = createHash(compilation.outputOptions.hashFunction); const hash = createHash(compilation.outputOptions.hashFunction);

View File

@ -103,7 +103,7 @@ class ModuleChunkFormatPlugin {
compilation.outputOptions compilation.outputOptions
), ),
{ {
chunk: chunk, chunk,
contentHashType: "javascript" contentHashType: "javascript"
} }
) )

View File

@ -292,7 +292,7 @@ class BasicEvaluatedExpression {
if (this.isBigInt()) return `${this.bigint}`; if (this.isBigInt()) return `${this.bigint}`;
if (this.isRegExp()) return `${this.regExp}`; if (this.isRegExp()) return `${this.regExp}`;
if (this.isArray()) { if (this.isArray()) {
let array = []; const array = [];
for (const item of /** @type {BasicEvaluatedExpression[]} */ ( for (const item of /** @type {BasicEvaluatedExpression[]} */ (
this.items this.items
)) { )) {

View File

@ -684,8 +684,8 @@ class JavascriptModulesPlugin {
return strictHeader return strictHeader
? new ConcatSource(strictHeader, source, ";") ? new ConcatSource(strictHeader, source, ";")
: renderContext.runtimeTemplate.isModule() : renderContext.runtimeTemplate.isModule()
? source ? source
: new ConcatSource(source, ";"); : new ConcatSource(source, ";");
} }
/** /**
@ -718,7 +718,7 @@ class JavascriptModulesPlugin {
inlinedModules = new Set(chunkGraph.getChunkEntryModulesIterable(chunk)); inlinedModules = new Set(chunkGraph.getChunkEntryModulesIterable(chunk));
} }
let source = new ConcatSource(); const source = new ConcatSource();
let prefix; let prefix;
if (iife) { if (iife) {
if (runtimeTemplate.supportsArrowFunction()) { if (runtimeTemplate.supportsArrowFunction()) {
@ -756,7 +756,7 @@ class JavascriptModulesPlugin {
inlinedModules inlinedModules
? allModules.filter( ? allModules.filter(
m => !(/** @type {Set<Module>} */ (inlinedModules).has(m)) m => !(/** @type {Set<Module>} */ (inlinedModules).has(m))
) )
: allModules, : allModules,
module => this.renderModule(module, chunkRenderContext, hooks, true), module => this.renderModule(module, chunkRenderContext, hooks, true),
prefix prefix
@ -849,15 +849,15 @@ class JavascriptModulesPlugin {
const exports = runtimeRequirements.has(RuntimeGlobals.exports); const exports = runtimeRequirements.has(RuntimeGlobals.exports);
const webpackExports = const webpackExports =
exports && m.exportsArgument === RuntimeGlobals.exports; exports && m.exportsArgument === RuntimeGlobals.exports;
let iife = innerStrict const iife = innerStrict
? "it need to be in strict mode." ? "it need to be in strict mode."
: inlinedModules.size > 1 : inlinedModules.size > 1
? // TODO check globals and top-level declarations of other entries and chunk modules ? // TODO check globals and top-level declarations of other entries and chunk modules
// to make a better decision // to make a better decision
"it need to be isolated against other entry modules." "it need to be isolated against other entry modules."
: exports && !webpackExports : exports && !webpackExports
? `it uses a non-standard name for the exports (${m.exportsArgument}).` ? `it uses a non-standard name for the exports (${m.exportsArgument}).`
: hooks.embedInRuntimeBailout.call(m, renderContext); : hooks.embedInRuntimeBailout.call(m, renderContext);
let footer; let footer;
if (iife !== undefined) { if (iife !== undefined) {
startupSource.add( startupSource.add(
@ -1047,7 +1047,7 @@ class JavascriptModulesPlugin {
allowInlineStartup: true allowInlineStartup: true
}; };
let { header: buf, startup, beforeStartup, afterStartup } = result; const { header: buf, startup, beforeStartup, afterStartup } = result;
if (result.allowInlineStartup && moduleFactories) { if (result.allowInlineStartup && moduleFactories) {
startup.push( startup.push(
@ -1323,14 +1323,14 @@ class JavascriptModulesPlugin {
`${RuntimeGlobals.interceptModuleExecution}.forEach(function(handler) { handler(execOptions); });`, `${RuntimeGlobals.interceptModuleExecution}.forEach(function(handler) { handler(execOptions); });`,
"module = execOptions.module;", "module = execOptions.module;",
"execOptions.factory.call(module.exports, module, module.exports, execOptions.require);" "execOptions.factory.call(module.exports, module, module.exports, execOptions.require);"
]) ])
: runtimeRequirements.has(RuntimeGlobals.thisAsExports) : runtimeRequirements.has(RuntimeGlobals.thisAsExports)
? Template.asString([ ? Template.asString([
`__webpack_modules__[moduleId].call(module.exports, module, module.exports, ${RuntimeGlobals.require});` `__webpack_modules__[moduleId].call(module.exports, module, module.exports, ${RuntimeGlobals.require});`
]) ])
: Template.asString([ : Template.asString([
`__webpack_modules__[moduleId](module, module.exports, ${RuntimeGlobals.require});` `__webpack_modules__[moduleId](module, module.exports, ${RuntimeGlobals.require});`
]); ]);
const needModuleId = runtimeRequirements.has(RuntimeGlobals.moduleId); const needModuleId = runtimeRequirements.has(RuntimeGlobals.moduleId);
const needModuleLoaded = runtimeRequirements.has( const needModuleLoaded = runtimeRequirements.has(
RuntimeGlobals.moduleLoaded RuntimeGlobals.moduleLoaded
@ -1343,7 +1343,7 @@ class JavascriptModulesPlugin {
? Template.indent([ ? Template.indent([
"if (cachedModule.error !== undefined) throw cachedModule.error;", "if (cachedModule.error !== undefined) throw cachedModule.error;",
"return cachedModule.exports;" "return cachedModule.exports;"
]) ])
: Template.indent("return cachedModule.exports;"), : Template.indent("return cachedModule.exports;"),
"}", "}",
"// Create a new module (and put it into the cache)", "// Create a new module (and put it into the cache)",
@ -1366,27 +1366,27 @@ class JavascriptModulesPlugin {
"if(threw) delete __webpack_module_cache__[moduleId];" "if(threw) delete __webpack_module_cache__[moduleId];"
]), ]),
"}" "}"
]) ])
: outputOptions.strictModuleErrorHandling : outputOptions.strictModuleErrorHandling
? Template.asString([ ? Template.asString([
"// Execute the module function", "// Execute the module function",
"try {", "try {",
Template.indent(moduleExecution), Template.indent(moduleExecution),
"} catch(e) {", "} catch(e) {",
Template.indent(["module.error = e;", "throw e;"]), Template.indent(["module.error = e;", "throw e;"]),
"}" "}"
]) ])
: Template.asString([ : Template.asString([
"// Execute the module function", "// Execute the module function",
moduleExecution moduleExecution
]), ]),
needModuleLoaded needModuleLoaded
? Template.asString([ ? Template.asString([
"", "",
"// Flag the module as loaded", "// Flag the module as loaded",
`${RuntimeGlobals.moduleLoaded} = true;`, `${RuntimeGlobals.moduleLoaded} = true;`,
"" ""
]) ])
: "", : "",
"// Return the exports of the module", "// Return the exports of the module",
"return module.exports;" "return module.exports;"

View File

@ -1366,8 +1366,8 @@ class JavascriptParser extends Parser {
if (expr.arguments.length !== 2) return; if (expr.arguments.length !== 2) return;
if (expr.arguments[0].type === "SpreadElement") return; if (expr.arguments[0].type === "SpreadElement") return;
if (expr.arguments[1].type === "SpreadElement") return; if (expr.arguments[1].type === "SpreadElement") return;
let arg1 = this.evaluateExpression(expr.arguments[0]); const arg1 = this.evaluateExpression(expr.arguments[0]);
let arg2 = this.evaluateExpression(expr.arguments[1]); const arg2 = this.evaluateExpression(expr.arguments[1]);
if (!arg1.isString() && !arg1.isRegExp()) return; if (!arg1.isString() && !arg1.isRegExp()) return;
const arg1Value = /** @type {string | RegExp} */ ( const arg1Value = /** @type {string | RegExp} */ (
arg1.regExp || arg1.string arg1.regExp || arg1.string
@ -1387,8 +1387,8 @@ class JavascriptParser extends Parser {
.tap("JavascriptParser", (expr, param) => { .tap("JavascriptParser", (expr, param) => {
if (!param.isString()) return; if (!param.isString()) return;
let arg1; let arg1;
let result, let result;
str = /** @type {string} */ (param.string); const str = /** @type {string} */ (param.string);
switch (expr.arguments.length) { switch (expr.arguments.length) {
case 1: case 1:
if (expr.arguments[0].type === "SpreadElement") return; if (expr.arguments[0].type === "SpreadElement") return;
@ -3415,7 +3415,7 @@ class JavascriptParser extends Parser {
* @param {ImportExpression} expression import expression * @param {ImportExpression} expression import expression
*/ */
walkImportExpression(expression) { walkImportExpression(expression) {
let result = this.hooks.importCall.call(expression); const result = this.hooks.importCall.call(expression);
if (result === true) return; if (result === true) return;
this.walkExpression(expression.source); this.walkExpression(expression.source);
@ -4395,7 +4395,7 @@ class JavascriptParser extends Parser {
const comments = /** @type {Comment[]} */ (this.comments); const comments = /** @type {Comment[]} */ (this.comments);
let idx = binarySearchBounds.ge(comments, rangeStart, compare); let idx = binarySearchBounds.ge(comments, rangeStart, compare);
/** @type {Comment[]} */ /** @type {Comment[]} */
let commentsInRange = []; const commentsInRange = [];
while ( while (
comments[idx] && comments[idx] &&
/** @type {Range} */ (comments[idx].range)[1] <= rangeEnd /** @type {Range} */ (comments[idx].range)[1] <= rangeEnd
@ -4579,9 +4579,9 @@ class JavascriptParser extends Parser {
if (comments.length === 0) { if (comments.length === 0) {
return EMPTY_COMMENT_OPTIONS; return EMPTY_COMMENT_OPTIONS;
} }
let options = {}; const options = {};
/** @type {unknown[]} */ /** @type {unknown[]} */
let errors = []; const errors = [];
for (const comment of comments) { for (const comment of comments) {
const { value } = comment; const { value } = comment;
if (value && webpackCommentRegExp.test(value)) { if (value && webpackCommentRegExp.test(value)) {

View File

@ -79,7 +79,7 @@ exports.evaluateToBoolean = value => {
*/ */
exports.evaluateToIdentifier = (identifier, rootInfo, getMembers, truthy) => { exports.evaluateToIdentifier = (identifier, rootInfo, getMembers, truthy) => {
return function identifierExpression(expr) { return function identifierExpression(expr) {
let evaluatedExpression = new BasicEvaluatedExpression() const evaluatedExpression = new BasicEvaluatedExpression()
.setIdentifier(identifier, rootInfo, getMembers) .setIdentifier(identifier, rootInfo, getMembers)
.setSideEffects(false) .setSideEffects(false)
.setRange(/** @type {Range} */ (expr.range)); .setRange(/** @type {Range} */ (expr.range));

View File

@ -68,7 +68,7 @@ const createObjectForExportsInfo = (data, exportsInfo, runtime) => {
/** @type {Record<string, RawJsonData>} */ (reducedData)[name] = value; /** @type {Record<string, RawJsonData>} */ (reducedData)[name] = value;
} }
if (isArray) { if (isArray) {
let arrayLengthWhenUsed = const arrayLengthWhenUsed =
exportsInfo.getReadOnlyExportInfo("length").getUsed(runtime) !== exportsInfo.getReadOnlyExportInfo("length").getUsed(runtime) !==
UsageState.Unused UsageState.Unused
? data.length ? data.length
@ -173,7 +173,7 @@ class JsonGenerator extends Generator {
} }
const exportsInfo = moduleGraph.getExportsInfo(module); const exportsInfo = moduleGraph.getExportsInfo(module);
/** @type {RawJsonData} */ /** @type {RawJsonData} */
let finalJson = const finalJson =
typeof data === "object" && typeof data === "object" &&
data && data &&
exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused

View File

@ -67,10 +67,9 @@ class AmdLibraryPlugin extends AbstractLibraryPlugin {
); );
} }
} }
return { const _name = /** @type {string} */ (name);
name: /** @type {string} */ (name), const _amdContainer = /** @type {string} */ (amdContainer);
amdContainer: /** @type {string} */ (amdContainer) return { name: _name, amdContainer: _amdContainer };
};
} }
/** /**

View File

@ -143,8 +143,9 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin {
); );
} }
} }
const _name = /** @type {string | string[]} */ (name);
return { return {
name: /** @type {string | string[]} */ (name), name: _name,
export: library.export export: library.export
}; };
} }
@ -295,7 +296,7 @@ class AssignLibraryPlugin extends AbstractLibraryPlugin {
const exportAccess = options.export const exportAccess = options.export
? propertyAccess( ? propertyAccess(
Array.isArray(options.export) ? options.export : [options.export] Array.isArray(options.export) ? options.export : [options.export]
) )
: ""; : "";
const result = new ConcatSource(source); const result = new ConcatSource(source);
if (staticExports) { if (staticExports) {

View File

@ -54,8 +54,9 @@ class JsonpLibraryPlugin extends AbstractLibraryPlugin {
`Jsonp library name must be a simple string. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` `Jsonp library name must be a simple string. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}`
); );
} }
const _name = /** @type {string} */ (name);
return { return {
name: /** @type {string} */ (name) name: _name
}; };
} }

View File

@ -73,8 +73,9 @@ class ModernModuleLibraryPlugin extends AbstractLibraryPlugin {
`Library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` `Library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}`
); );
} }
const _name = /** @type {string} */ (name);
return { return {
name: /** @type {string} */ (name) name: _name
}; };
} }

View File

@ -58,8 +58,9 @@ class ModuleLibraryPlugin extends AbstractLibraryPlugin {
`Library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` `Library name must be unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}`
); );
} }
const _name = /** @type {string} */ (name);
return { return {
name: /** @type {string} */ (name) name: _name
}; };
} }

View File

@ -58,8 +58,9 @@ class SystemLibraryPlugin extends AbstractLibraryPlugin {
`System.js library name must be a simple string or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}` `System.js library name must be a simple string or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}`
); );
} }
const _name = /** @type {string} */ (name);
return { return {
name: /** @type {string} */ (name) name: _name
}; };
} }
@ -187,7 +188,7 @@ class SystemLibraryPlugin extends AbstractLibraryPlugin {
.join(",\n") .join(",\n")
), ),
"]," "],"
]); ]);
return new ConcatSource( return new ConcatSource(
Template.asString([ Template.asString([

View File

@ -10,7 +10,7 @@ const { Logger } = require("./Logger");
const createConsoleLogger = require("./createConsoleLogger"); const createConsoleLogger = require("./createConsoleLogger");
/** @type {createConsoleLogger.LoggerOptions} */ /** @type {createConsoleLogger.LoggerOptions} */
let currentDefaultLoggerOptions = { const currentDefaultLoggerOptions = {
level: "info", level: "info",
debug: false, debug: false,
console console

View File

@ -51,7 +51,7 @@ class AggressiveMergingPlugin {
chunks => { chunks => {
const chunkGraph = compilation.chunkGraph; const chunkGraph = compilation.chunkGraph;
/** @type {{a: Chunk, b: Chunk, improvement: number}[]} */ /** @type {{a: Chunk, b: Chunk, improvement: number}[]} */
let combinations = []; const combinations = [];
for (const a of chunks) { for (const a of chunks) {
if (a.canBeInitial()) continue; if (a.canBeInitial()) continue;
for (const b of chunks) { for (const b of chunks) {

View File

@ -367,10 +367,10 @@ const getFinalBinding = (
const defaultExport = asCall const defaultExport = asCall
? `${info.interopDefaultAccessName}()` ? `${info.interopDefaultAccessName}()`
: asiSafe : asiSafe
? `(${info.interopDefaultAccessName}())` ? `(${info.interopDefaultAccessName}())`
: asiSafe === false : asiSafe === false
? `;(${info.interopDefaultAccessName}())` ? `;(${info.interopDefaultAccessName}())`
: `${info.interopDefaultAccessName}.a`; : `${info.interopDefaultAccessName}.a`;
return { return {
info, info,
rawName: defaultExport, rawName: defaultExport,
@ -601,8 +601,8 @@ const getFinalName = (
return asiSafe return asiSafe
? `(0,${reference})` ? `(0,${reference})`
: asiSafe === false : asiSafe === false
? `;(0,${reference})` ? `;(0,${reference})`
: `/*#__PURE__*/Object(${reference})`; : `/*#__PURE__*/Object(${reference})`;
} }
return reference; return reference;
} }
@ -903,7 +903,9 @@ class ConcatenatedModule extends Module {
* @returns {Iterable<{ connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true }>} imported modules in order * @returns {Iterable<{ connection: ModuleGraphConnection, runtimeCondition: RuntimeSpec | true }>} imported modules in order
*/ */
const getConcatenatedImports = module => { const getConcatenatedImports = module => {
let connections = Array.from(moduleGraph.getOutgoingConnections(module)); const connections = Array.from(
moduleGraph.getOutgoingConnections(module)
);
if (module === rootModule) { if (module === rootModule) {
for (const c of moduleGraph.getOutgoingConnections(this)) for (const c of moduleGraph.getOutgoingConnections(this))
connections.push(c); connections.push(c);
@ -1077,7 +1079,7 @@ class ConcatenatedModule extends Module {
/** @type {string} */ (rootModule.context), /** @type {string} */ (rootModule.context),
associatedObjectForCache associatedObjectForCache
); );
let identifiers = []; const identifiers = [];
for (const module of modules) { for (const module of modules) {
identifiers.push(cachedMakePathsRelative(module.identifier())); identifiers.push(cachedMakePathsRelative(module.identifier()));
} }
@ -1489,8 +1491,9 @@ class ConcatenatedModule extends Module {
} */ ${finalName}`; } */ ${finalName}`;
} catch (e) { } catch (e) {
/** @type {Error} */ /** @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; throw e;
} }
}); });
@ -1593,7 +1596,7 @@ class ConcatenatedModule extends Module {
nsObj.length > 0 nsObj.length > 0
? `${RuntimeGlobals.definePropertyGetters}(${name}, {${nsObj.join( ? `${RuntimeGlobals.definePropertyGetters}(${name}, {${nsObj.join(
"," ","
)}\n});\n` )}\n});\n`
: ""; : "";
if (nsObj.length > 0) if (nsObj.length > 0)
runtimeRequirements.add(RuntimeGlobals.definePropertyGetters); runtimeRequirements.add(RuntimeGlobals.definePropertyGetters);
@ -1795,8 +1798,9 @@ ${defineGetters}`
info.moduleScope = moduleScope; info.moduleScope = moduleScope;
} catch (err) { } catch (err) {
/** @type {Error} */ /** @type {Error} */
(err).message += (
`\nwhile analyzing module ${m.identifier()} for concatenation`; err
).message += `\nwhile analyzing module ${m.identifier()} for concatenation`;
throw err; throw err;
} }
} }

View File

@ -291,8 +291,8 @@ class ModuleConcatenationPlugin {
filteredRuntime === true filteredRuntime === true
? chunkRuntime ? chunkRuntime
: filteredRuntime === false : filteredRuntime === false
? undefined ? undefined
: filteredRuntime; : filteredRuntime;
// create a configuration with the root // create a configuration with the root
const currentConfiguration = new ConcatConfiguration( const currentConfiguration = new ConcatConfiguration(
@ -399,7 +399,7 @@ class ModuleConcatenationPlugin {
// Create a new ConcatenatedModule // Create a new ConcatenatedModule
ConcatenatedModule.getCompilationHooks(compilation); ConcatenatedModule.getCompilationHooks(compilation);
let newModule = ConcatenatedModule.create( const newModule = ConcatenatedModule.create(
rootModule, rootModule,
modules, modules,
concatConfiguration.runtime, concatConfiguration.runtime,

View File

@ -215,7 +215,7 @@ class RealContentHashPlugin {
[asset.referencedHashes, asset.ownHashes] = [asset.referencedHashes, asset.ownHashes] =
await cacheAnalyse.providePromise(name, etag, () => { await cacheAnalyse.providePromise(name, etag, () => {
const referencedHashes = new Set(); const referencedHashes = new Set();
let ownHashes = new Set(); const ownHashes = new Set();
const inContent = content.match(hashRegExp); const inContent = content.match(hashRegExp);
if (inContent) { if (inContent) {
for (const hash of inContent) { for (const hash of inContent) {

View File

@ -41,7 +41,7 @@ function* getModulesFromMask(mask, ordinalModules) {
// Consider the last 32 bits, since that's what Math.clz32 can handle // Consider the last 32 bits, since that's what Math.clz32 can handle
let last32 = Number(BigInt.asUintN(32, mask)); let last32 = Number(BigInt.asUintN(32, mask));
while (last32 > 0) { 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 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 // The 32 is baked into the initial value of offset
const moduleIndex = offset - last; const moduleIndex = offset - last;
@ -148,7 +148,7 @@ class RemoveParentModulesPlugin {
availableModulesMask = parentMask; availableModulesMask = parentMask;
changed = true; changed = true;
} else { } else {
let newMask = availableModulesMask & parentMask; const newMask = availableModulesMask & parentMask;
if (newMask !== availableModulesMask) { if (newMask !== availableModulesMask) {
changed = true; changed = true;
availableModulesMask = newMask; availableModulesMask = newMask;

View File

@ -500,7 +500,7 @@ const normalizeCacheGroups = (cacheGroups, defaultSizeTypes) => {
*/ */
const fn = (module, context) => { const fn = (module, context) => {
/** @type {CacheGroupSource[]} */ /** @type {CacheGroupSource[]} */
let results = []; const results = [];
for (const fn of handlers) { for (const fn of handlers) {
fn(module, context, results); fn(module, context, results);
} }
@ -749,20 +749,20 @@ module.exports = class SplitChunksPlugin {
cacheGroupSource.minChunks !== undefined cacheGroupSource.minChunks !== undefined
? cacheGroupSource.minChunks ? cacheGroupSource.minChunks
: cacheGroupSource.enforce : cacheGroupSource.enforce
? 1 ? 1
: this.options.minChunks, : this.options.minChunks,
maxAsyncRequests: maxAsyncRequests:
cacheGroupSource.maxAsyncRequests !== undefined cacheGroupSource.maxAsyncRequests !== undefined
? cacheGroupSource.maxAsyncRequests ? cacheGroupSource.maxAsyncRequests
: cacheGroupSource.enforce : cacheGroupSource.enforce
? Infinity ? Infinity
: this.options.maxAsyncRequests, : this.options.maxAsyncRequests,
maxInitialRequests: maxInitialRequests:
cacheGroupSource.maxInitialRequests !== undefined cacheGroupSource.maxInitialRequests !== undefined
? cacheGroupSource.maxInitialRequests ? cacheGroupSource.maxInitialRequests
: cacheGroupSource.enforce : cacheGroupSource.enforce
? Infinity ? Infinity
: this.options.maxInitialRequests, : this.options.maxInitialRequests,
getName: getName:
cacheGroupSource.getName !== undefined cacheGroupSource.getName !== undefined
? cacheGroupSource.getName ? cacheGroupSource.getName
@ -1210,7 +1210,7 @@ module.exports = class SplitChunksPlugin {
// Walk through all modules // Walk through all modules
for (const module of compilation.modules) { for (const module of compilation.modules) {
// Get cache group // Get cache group
let cacheGroups = this.options.getCacheGroups(module, context); const cacheGroups = this.options.getCacheGroups(module, context);
if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) { if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) {
continue; continue;
} }
@ -1428,13 +1428,13 @@ module.exports = class SplitChunksPlugin {
chunk.isOnlyInitial() chunk.isOnlyInitial()
? item.cacheGroup.maxInitialRequests ? item.cacheGroup.maxInitialRequests
: chunk.canBeInitial() : chunk.canBeInitial()
? Math.min( ? Math.min(
/** @type {number} */ /** @type {number} */
(item.cacheGroup.maxInitialRequests), (item.cacheGroup.maxInitialRequests),
/** @type {number} */ /** @type {number} */
(item.cacheGroup.maxAsyncRequests) (item.cacheGroup.maxAsyncRequests)
) )
: item.cacheGroup.maxAsyncRequests : item.cacheGroup.maxAsyncRequests
); );
if ( if (
isFinite(maxRequests) && isFinite(maxRequests) &&
@ -1482,7 +1482,7 @@ module.exports = class SplitChunksPlugin {
usedChunks.size === 1 usedChunks.size === 1
) { ) {
const [chunk] = usedChunks; const [chunk] = usedChunks;
let chunkSizes = Object.create(null); const chunkSizes = Object.create(null);
for (const module of chunkGraph.getChunkModulesIterable(chunk)) { for (const module of chunkGraph.getChunkModulesIterable(chunk)) {
if (!item.modules.has(module)) { if (!item.modules.has(module)) {
for (const type of module.getSourceTypes()) { for (const type of module.getSourceTypes()) {
@ -1569,21 +1569,21 @@ module.exports = class SplitChunksPlugin {
oldMaxSizeSettings.minSize, oldMaxSizeSettings.minSize,
item.cacheGroup._minSizeForMaxSize, item.cacheGroup._minSizeForMaxSize,
Math.max Math.max
) )
: item.cacheGroup.minSize, : item.cacheGroup.minSize,
maxAsyncSize: oldMaxSizeSettings maxAsyncSize: oldMaxSizeSettings
? combineSizes( ? combineSizes(
oldMaxSizeSettings.maxAsyncSize, oldMaxSizeSettings.maxAsyncSize,
item.cacheGroup.maxAsyncSize, item.cacheGroup.maxAsyncSize,
Math.min Math.min
) )
: item.cacheGroup.maxAsyncSize, : item.cacheGroup.maxAsyncSize,
maxInitialSize: oldMaxSizeSettings maxInitialSize: oldMaxSizeSettings
? combineSizes( ? combineSizes(
oldMaxSizeSettings.maxInitialSize, oldMaxSizeSettings.maxInitialSize,
item.cacheGroup.maxInitialSize, item.cacheGroup.maxInitialSize,
Math.min Math.min
) )
: item.cacheGroup.maxInitialSize, : item.cacheGroup.maxInitialSize,
automaticNameDelimiter: item.cacheGroup.automaticNameDelimiter, automaticNameDelimiter: item.cacheGroup.automaticNameDelimiter,
keys: oldMaxSizeSettings keys: oldMaxSizeSettings

View File

@ -127,8 +127,8 @@ module.exports = class SizeLimitsPlugin {
if (size > /** @type {number} */ (entrypointSizeLimit)) { if (size > /** @type {number} */ (entrypointSizeLimit)) {
entrypointsOverLimit.push({ entrypointsOverLimit.push({
name: name, name,
size: size, size,
files: entry.getFiles().filter(fileFilter) files: entry.getFiles().filter(fileFilter)
}); });
isOverSizeLimitSet.add(entry); isOverSizeLimitSet.add(entry);

View File

@ -1101,6 +1101,7 @@ class BinaryMiddleware extends SerializerMiddleware {
} }
// avoid leaking memory in context // avoid leaking memory in context
// eslint-disable-next-line prefer-const
let _result = result; let _result = result;
result = undefined; result = undefined;
return _result; return _result;

View File

@ -29,7 +29,7 @@ class MapObjectSerializer {
*/ */
deserialize(context) { deserialize(context) {
/** @type {number} */ /** @type {number} */
let size = context.read(); const size = context.read();
/** @type {Map<K, V>} */ /** @type {Map<K, V>} */
const map = new Map(); const map = new Map();
/** @type {K[]} */ /** @type {K[]} */

View File

@ -26,7 +26,7 @@ class SetObjectSerializer {
*/ */
deserialize(context) { deserialize(context) {
/** @type {number} */ /** @type {number} */
let size = context.read(); const size = context.read();
/** @type {Set<T>} */ /** @type {Set<T>} */
const set = new Set(); const set = new Set();
for (let i = 0; i < size; i++) { for (let i = 0; i < size; i++) {

View File

@ -57,10 +57,10 @@ class ConsumeSharedPlugin {
(item, key) => { (item, key) => {
if (Array.isArray(item)) throw new Error("Unexpected array in options"); if (Array.isArray(item)) throw new Error("Unexpected array in options");
/** @type {ConsumeOptions} */ /** @type {ConsumeOptions} */
let result = const result =
item === key || !isRequiredVersion(item) item === key || !isRequiredVersion(item)
? // item is a request/key ? // item is a request/key
{ {
import: key, import: key,
shareScope: options.shareScope || "default", shareScope: options.shareScope || "default",
shareKey: key, shareKey: key,
@ -69,10 +69,10 @@ class ConsumeSharedPlugin {
strictVersion: false, strictVersion: false,
singleton: false, singleton: false,
eager: false eager: false
} }
: // key is a request/key : // key is a request/key
// item is a version // item is a version
{ {
import: key, import: key,
shareScope: options.shareScope || "default", shareScope: options.shareScope || "default",
shareKey: key, shareKey: key,
@ -81,7 +81,7 @@ class ConsumeSharedPlugin {
packageName: undefined, packageName: undefined,
singleton: false, singleton: false,
eager: false eager: false
}; };
return result; return result;
}, },
(item, key) => ({ (item, key) => ({

View File

@ -250,7 +250,7 @@ function canBeDecoded(str) {
* @returns {string} dep version * @returns {string} dep version
*/ */
function getGitUrlVersion(gitUrl) { function getGitUrlVersion(gitUrl) {
let oriGitUrl = gitUrl; const oriGitUrl = gitUrl;
// github extreme shorthand // github extreme shorthand
if (RE_URL_GITHUB_EXTREME_SHORT.test(gitUrl)) { if (RE_URL_GITHUB_EXTREME_SHORT.test(gitUrl)) {
gitUrl = "github:" + gitUrl; gitUrl = "github:" + gitUrl;

View File

@ -62,7 +62,7 @@ class TupleSet {
} }
const beforeLast = args[args.length - 2]; const beforeLast = args[args.length - 2];
let set = map.get(beforeLast); const set = map.get(beforeLast);
if (set === undefined) { if (set === undefined) {
return false; return false;
} }
@ -86,7 +86,7 @@ class TupleSet {
} }
const beforeLast = args[args.length - 2]; const beforeLast = args[args.length - 2];
let set = map.get(beforeLast); const set = map.get(beforeLast);
if (set === undefined) { if (set === undefined) {
return; return;
} }

View File

@ -480,8 +480,8 @@ exports.compareChunksNatural = chunkGraph => {
* @returns {-1|0|1} sorting comparator value * @returns {-1|0|1} sorting comparator value
*/ */
exports.compareLocations = (a, b) => { exports.compareLocations = (a, b) => {
let isObjectA = typeof a === "object" && a !== null; const isObjectA = typeof a === "object" && a !== null;
let isObjectB = typeof b === "object" && b !== null; const isObjectB = typeof b === "object" && b !== null;
if (!isObjectA || !isObjectB) { if (!isObjectA || !isObjectB) {
if (isObjectA) return 1; if (isObjectA) return 1;
if (isObjectB) return -1; if (isObjectB) return -1;

View File

@ -397,14 +397,14 @@ module.exports = ({ maxSize, minSize, items, getSize, getKey }) => {
// going minSize from left and right // going minSize from left and right
// at least one node need to be included otherwise we get stuck // at least one node need to be included otherwise we get stuck
let left = 1; let left = 1;
let leftSize = Object.create(null); const leftSize = Object.create(null);
addSizeTo(leftSize, group.nodes[0].size); addSizeTo(leftSize, group.nodes[0].size);
while (left < group.nodes.length && isTooSmall(leftSize, minSize)) { while (left < group.nodes.length && isTooSmall(leftSize, minSize)) {
addSizeTo(leftSize, group.nodes[left].size); addSizeTo(leftSize, group.nodes[left].size);
left++; left++;
} }
let right = group.nodes.length - 2; 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); addSizeTo(rightSize, group.nodes[group.nodes.length - 1].size);
while (right >= 0 && isTooSmall(rightSize, minSize)) { while (right >= 0 && isTooSmall(rightSize, minSize)) {
addSizeTo(rightSize, group.nodes[right].size); addSizeTo(rightSize, group.nodes[right].size);
@ -452,7 +452,7 @@ module.exports = ({ maxSize, minSize, items, getSize, getKey }) => {
let best = -1; let best = -1;
let bestSimilarity = Infinity; let bestSimilarity = Infinity;
let pos = left; let pos = left;
let rightSize = sumSize(group.nodes.slice(pos)); const rightSize = sumSize(group.nodes.slice(pos));
// pos v v right // pos v v right
// [ O O O ] O O O [ O O O ] // [ O O O ] O O O [ O O O ]

View File

@ -138,14 +138,14 @@ const smartGrouping = (items, groupConfigs) => {
} }
} }
const targetGroupCount = (options && options.targetGroupCount) || 4; const targetGroupCount = (options && options.targetGroupCount) || 4;
let sizeValue = force const sizeValue = force
? items.size ? items.size
: Math.min( : Math.min(
items.size, items.size,
(totalSize * 2) / targetGroupCount + (totalSize * 2) / targetGroupCount +
itemsWithGroups.size - itemsWithGroups.size -
items.size items.size
); );
if ( if (
sizeValue > bestGroupSize || sizeValue > bestGroupSize ||
(force && (!bestGroupOptions || !bestGroupOptions.force)) (force && (!bestGroupOptions || !bestGroupOptions.force))

View File

@ -67,7 +67,7 @@ function installYarnAsync() {
function exec(command, args, description) { function exec(command, args, description) {
console.log(`Setup: ${description}`); console.log(`Setup: ${description}`);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let cp = require("child_process").spawn(command, args, { const cp = require("child_process").spawn(command, args, {
cwd: root, cwd: root,
stdio: "inherit", stdio: "inherit",
shell: true shell: true
@ -88,7 +88,7 @@ function exec(command, args, description) {
function execGetOutput(command, args, description) { function execGetOutput(command, args, description) {
console.log(`Setup: ${description}`); console.log(`Setup: ${description}`);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let cp = require("child_process").spawn(command, args, { const cp = require("child_process").spawn(command, args, {
cwd: root, cwd: root,
stdio: [process.stdin, "pipe", process.stderr], stdio: [process.stdin, "pipe", process.stderr],
shell: true shell: true

View File

@ -108,7 +108,7 @@ describe("BinaryMiddleware", () => {
for (const prepend of items) { for (const prepend of items) {
for (const append of items) { for (const append of items) {
if (c > 1 && append !== undefined) continue; if (c > 1 && append !== undefined) continue;
let data = [prepend, ...caseData, append].filter( const data = [prepend, ...caseData, append].filter(
x => x !== undefined x => x !== undefined
); );
if (data.length * c > 200000) continue; if (data.length * c > 200000) continue;

View File

@ -88,7 +88,6 @@ describe("ChangesAndRemovals", () => {
it("should not track modified/removed files during initial watchRun", done => { it("should not track modified/removed files during initial watchRun", done => {
const compiler = createSingleCompiler(); const compiler = createSingleCompiler();
let watcher;
const watchRunFinished = new Promise(resolve => { const watchRunFinished = new Promise(resolve => {
compiler.hooks.watchRun.tap("ChangesAndRemovalsTest", compiler => { compiler.hooks.watchRun.tap("ChangesAndRemovalsTest", compiler => {
expect(getChanges(compiler)).toEqual({ expect(getChanges(compiler)).toEqual({
@ -98,7 +97,7 @@ describe("ChangesAndRemovals", () => {
resolve(); resolve();
}); });
}); });
watcher = compiler.watch({ aggregateTimeout: 200 }, err => { const watcher = compiler.watch({ aggregateTimeout: 200 }, err => {
if (err) done(err); if (err) done(err);
}); });

View File

@ -266,7 +266,7 @@ const describeCases = config => {
? children.reduce( ? children.reduce(
(all, { modules }) => all.concat(modules), (all, { modules }) => all.concat(modules),
modules || [] modules || []
) )
: modules; : modules;
if ( if (
allModules.some( allModules.some(
@ -565,7 +565,7 @@ const describeCases = config => {
referencingModule.identifier referencingModule.identifier
? referencingModule.identifier.slice( ? referencingModule.identifier.slice(
esmIdentifier.length + 1 esmIdentifier.length + 1
) )
: fileURLToPath(referencingModule.url) : fileURLToPath(referencingModule.url)
), ),
options, options,
@ -637,7 +637,7 @@ const describeCases = config => {
", " ", "
)}) {${content}\n})`; )}) {${content}\n})`;
let oldCurrentScript = document.currentScript; const oldCurrentScript = document.currentScript;
document.currentScript = new CurrentScript(subPath); document.currentScript = new CurrentScript(subPath);
const fn = runInNewContext const fn = runInNewContext
? vm.runInNewContext(code, globalContext, p) ? vm.runInNewContext(code, globalContext, p)
@ -657,9 +657,9 @@ const describeCases = config => {
) { ) {
return testConfig.modules[module]; return testConfig.modules[module];
} else { } else {
return require( return require(module.startsWith("node:")
module.startsWith("node:") ? module.slice(5) : module ? module.slice(5)
); : module);
} }
}; };

View File

@ -15,7 +15,7 @@ describe("ContextModuleFactory", () => {
setTimeout(() => callback(null, ["/file"])); setTimeout(() => callback(null, ["/file"]));
}; };
memfs.stat = (file, callback) => { memfs.stat = (file, callback) => {
let err = new Error("fake ENOENT error"); const err = new Error("fake ENOENT error");
err.code = "ENOENT"; err.code = "ENOENT";
setTimeout(() => callback(err, null)); setTimeout(() => callback(err, null));
}; };
@ -39,7 +39,7 @@ describe("ContextModuleFactory", () => {
setTimeout(() => callback(null, ["/file"])); setTimeout(() => callback(null, ["/file"]));
}; };
memfs.stat = (file, callback) => { memfs.stat = (file, callback) => {
let err = new Error("fake EACCES error"); const err = new Error("fake EACCES error");
err.code = "EACCES"; err.code = "EACCES";
setTimeout(() => callback(err, null)); setTimeout(() => callback(err, null));
}; };

View File

@ -194,7 +194,7 @@ describe("NormalModule", () => {
}); });
describe("#originalSource", () => { describe("#originalSource", () => {
let expectedSource = "some source"; const expectedSource = "some source";
beforeEach(() => { beforeEach(() => {
normalModule._source = new RawSource(expectedSource); normalModule._source = new RawSource(expectedSource);
}); });

View File

@ -70,7 +70,7 @@ const describeCases = config => {
return true; return true;
}) })
.forEach(testName => { .forEach(testName => {
let infraStructureLog = []; const infraStructureLog = [];
describe(testName, () => { describe(testName, () => {
const testDirectory = path.join( const testDirectory = path.join(
@ -112,7 +112,7 @@ const describeCases = config => {
emitOnErrors: true, emitOnErrors: true,
minimizer: [terserForTesting], minimizer: [terserForTesting],
...config.optimization ...config.optimization
} }
: { : {
removeAvailableModules: true, removeAvailableModules: true,
removeEmptyChunks: true, removeEmptyChunks: true,
@ -128,7 +128,7 @@ const describeCases = config => {
chunkIds: "size", chunkIds: "size",
minimizer: [terserForTesting], minimizer: [terserForTesting],
...config.optimization ...config.optimization
}, },
performance: { performance: {
hints: false hints: false
}, },

View File

@ -33,7 +33,7 @@ module.exports = class FakeDocument {
_onElementRemoved(element) { _onElementRemoved(element) {
const type = element._type; const type = element._type;
let list = this._elementsByTagName.get(type); const list = this._elementsByTagName.get(type);
const idx = list.indexOf(element); const idx = list.indexOf(element);
list.splice(idx, 1); list.splice(idx, 1);
} }
@ -205,7 +205,7 @@ class FakeSheet {
.replace(/^https:\/\/test\.cases\/path\//, "") .replace(/^https:\/\/test\.cases\/path\//, "")
.replace(/^https:\/\/example\.com\/public\/path\//, "") .replace(/^https:\/\/example\.com\/public\/path\//, "")
.replace(/^https:\/\/example\.com\//, "") .replace(/^https:\/\/example\.com\//, "")
); );
let css = fs.readFileSync(filepath, "utf-8"); let css = fs.readFileSync(filepath, "utf-8");
css = css.replace(/@import url\("([^"]+)"\);/g, (match, url) => { css = css.replace(/@import url\("([^"]+)"\);/g, (match, url) => {
if (!/^https:\/\/test\.cases\/path\//.test(url)) { if (!/^https:\/\/test\.cases\/path\//.test(url)) {

View File

@ -1,5 +1,5 @@
module.exports = () => { module.exports = () => {
let warnings = []; const warnings = [];
let oldWarn; let oldWarn;
beforeEach(done => { beforeEach(done => {

View File

@ -1,7 +1,7 @@
describe("warmup", () => { describe("warmup", () => {
it("should warmup webpack", done => { it("should warmup webpack", done => {
let webpack = require("../../"); let webpack = require("../../");
let END = new Error("end warmup"); const END = new Error("end warmup");
webpack( webpack(
{ {
entry: "data:text/javascript,import 'data:text/javascript,'", entry: "data:text/javascript,import 'data:text/javascript,'",