diff --git a/lib/AmdMainTemplatePlugin.js b/lib/AmdMainTemplatePlugin.js index b950ed5e08f..ff715ec6c17 100644 --- a/lib/AmdMainTemplatePlugin.js +++ b/lib/AmdMainTemplatePlugin.js @@ -71,7 +71,9 @@ class AmdMainTemplatePlugin { } mainTemplate.hooks.globalHashPaths.tap("AmdMainTemplatePlugin", paths => { - if (this.name) paths.push(this.name); + if (this.name) { + paths.push(this.name); + } return paths; }); diff --git a/lib/BannerPlugin.js b/lib/BannerPlugin.js index 930990ad8d3..1e9aa343c0e 100644 --- a/lib/BannerPlugin.js +++ b/lib/BannerPlugin.js @@ -13,7 +13,9 @@ const validateOptions = require("schema-utils"); const schema = require("../schemas/plugins/BannerPlugin.json"); const wrapComment = str => { - if (!str.includes("\n")) return Template.toComment(str); + if (!str.includes("\n")) { + return Template.toComment(str); + } return `/*!\n * ${str .replace(/\*\//g, "* /") .split("\n") diff --git a/lib/BasicEvaluatedExpression.js b/lib/BasicEvaluatedExpression.js index 48134eae0fd..65db864f9b0 100644 --- a/lib/BasicEvaluatedExpression.js +++ b/lib/BasicEvaluatedExpression.js @@ -90,20 +90,21 @@ class BasicEvaluatedExpression { asBool() { if (this.truthy) return true; - else if (this.falsy) return false; - else if (this.isBoolean()) return this.bool; - else if (this.isNull()) return false; - else if (this.isString()) return this.string !== ""; - else if (this.isNumber()) return this.number !== 0; - else if (this.isRegExp()) return true; - else if (this.isArray()) return true; - else if (this.isConstArray()) return true; - else if (this.isWrapped()) + if (this.falsy) return false; + if (this.isBoolean()) return this.bool; + if (this.isNull()) return false; + if (this.isString()) return this.string !== ""; + if (this.isNumber()) return this.number !== 0; + if (this.isRegExp()) return true; + if (this.isArray()) return true; + if (this.isConstArray()) return true; + if (this.isWrapped()) { return (this.prefix && this.prefix.asBool()) || (this.postfix && this.postfix.asBool()) ? true : undefined; - else if (this.isTemplateString()) { + } + if (this.isTemplateString()) { for (const quasi of this.quasis) { if (quasi.asBool()) return true; } @@ -165,7 +166,9 @@ class BasicEvaluatedExpression { this.type = TypeConditional; this.options = []; } - for (const item of options) this.options.push(item); + for (const item of options) { + this.options.push(item); + } return this; } diff --git a/lib/CachePlugin.js b/lib/CachePlugin.js index 7a16df101e2..0d1650be963 100644 --- a/lib/CachePlugin.js +++ b/lib/CachePlugin.js @@ -26,12 +26,17 @@ class CachePlugin { (childCompiler, compilerName, compilerIndex) => { if (cache) { let childCache; - if (!cache.children) cache.children = {}; - if (!cache.children[compilerName]) + if (!cache.children) { + cache.children = {}; + } + if (!cache.children[compilerName]) { cache.children[compilerName] = []; - if (cache.children[compilerName][compilerIndex]) + } + if (cache.children[compilerName][compilerIndex]) { childCache = cache.children[compilerName][compilerIndex]; - else cache.children[compilerName].push((childCache = {})); + } else { + cache.children[compilerName].push((childCache = {})); + } registerCacheToCompiler(childCompiler, childCache); } } @@ -43,7 +48,9 @@ class CachePlugin { this.watching = true; }); compiler.hooks.run.tapAsync("CachePlugin", (compiler, callback) => { - if (!compiler._lastCompilationFileDependencies) return callback(); + if (!compiler._lastCompilationFileDependencies) { + return callback(); + } const fs = compiler.inputFileSystem; const fileTs = (compiler.fileTimestamps = new Map()); asyncLib.forEach( diff --git a/lib/Chunk.js b/lib/Chunk.js index f0c6f3902dd..31193bd9f7c 100644 --- a/lib/Chunk.js +++ b/lib/Chunk.js @@ -378,13 +378,14 @@ class Chunk { otherChunk._groups.clear(); if (this.name && otherChunk.name) { - if (this.name.length !== otherChunk.name.length) + if (this.name.length !== otherChunk.name.length) { this.name = this.name.length < otherChunk.name.length ? this.name : otherChunk.name; - else + } else { this.name = this.name < otherChunk.name ? this.name : otherChunk.name; + } } return true; @@ -420,12 +421,16 @@ class Chunk { for (const chunkGroup of queue) { if (a.isInGroup(chunkGroup)) continue; if (chunkGroup.isInitial()) return false; - for (const parent of chunkGroup.parentsIterable) queue.add(parent); + for (const parent of chunkGroup.parentsIterable) { + queue.add(parent); + } } return true; }; - if (this.preventIntegration || otherChunk.preventIntegration) return false; + if (this.preventIntegration || otherChunk.preventIntegration) { + return false; + } if (this.hasRuntime() !== otherChunk.hasRuntime()) { if (this.hasRuntime()) { @@ -436,7 +441,11 @@ class Chunk { return false; } } - if (this.hasEntryModule() || otherChunk.hasEntryModule()) return false; + + if (this.hasEntryModule() || otherChunk.hasEntryModule()) { + return false; + } + return true; } @@ -509,14 +518,20 @@ class Chunk { ); for (const chunkGroup of this.groupsIterable) { - for (const child of chunkGroup.childrenIterable) queue.add(child); + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } } for (const chunkGroup of queue) { for (const chunk of chunkGroup.chunks) { - if (!initialChunks.has(chunk)) chunks.add(chunk); + if (!initialChunks.has(chunk)) { + chunks.add(chunk); + } + } + for (const child of chunkGroup.childrenIterable) { + queue.add(child); } - for (const child of chunkGroup.childrenIterable) queue.add(child); } return chunks; @@ -530,11 +545,14 @@ class Chunk { for (const chunk of this.getAllAsyncChunks()) { chunkHashMap[chunk.id] = realHash ? chunk.hash : chunk.renderedHash; for (const key of Object.keys(chunk.contentHash)) { - if (!chunkContentHashMap[key]) + if (!chunkContentHashMap[key]) { chunkContentHashMap[key] = Object.create(null); + } chunkContentHashMap[key][chunk.id] = chunk.contentHash[key]; } - if (chunk.name) chunkNameMap[chunk.id] = chunk.name; + if (chunk.name) { + chunkNameMap[chunk.id] = chunk.name; + } } return { @@ -572,12 +590,16 @@ class Chunk { const cmp = b.order - a.order; if (cmp !== 0) return cmp; // TOOD webpack 5 remove this check of compareTo - if (a.group.compareTo) return a.group.compareTo(b.group); + if (a.group.compareTo) { + return a.group.compareTo(b.group); + } return 0; }); result[name] = Array.from( list.reduce((set, item) => { - for (const chunk of item.group.chunks) set.add(chunk.id); + for (const chunk of item.group.chunks) { + set.add(chunk.id); + } return set; }, new Set()) ); @@ -592,8 +614,9 @@ class Chunk { const data = chunk.getChildIdsByOrders(); for (const key of Object.keys(data)) { let chunkMap = chunkMaps[key]; - if (chunkMap === undefined) + if (chunkMap === undefined) { chunkMaps[key] = chunkMap = Object.create(null); + } chunkMap[chunk.id] = data[key]; } } @@ -642,12 +665,17 @@ class Chunk { if (!chunksProcessed.has(chunk)) { chunksProcessed.add(chunk); if (!filterChunkFn || filterChunkFn(chunk)) { - for (const module of chunk.modulesIterable) - if (filterFn(module)) return true; + for (const module of chunk.modulesIterable) { + if (filterFn(module)) { + return true; + } + } } } } - for (const child of chunkGroup.childrenIterable) queue.add(child); + for (const child of chunkGroup.childrenIterable) { + queue.add(child); + } } return false; } diff --git a/lib/ChunkGroup.js b/lib/ChunkGroup.js index b48d9407e15..7e69cfab452 100644 --- a/lib/ChunkGroup.js +++ b/lib/ChunkGroup.js @@ -259,7 +259,9 @@ class ChunkGroup { setParents(newParents) { this._parents.clear(); - for (const p of newParents) this._parents.add(p); + for (const p of newParents) { + this._parents.add(p); + } } getNumberOfParents() { @@ -418,7 +420,9 @@ class ChunkGroup { if (key.endsWith("Order")) { const name = key.substr(0, key.length - "Order".length); let list = lists.get(name); - if (list === undefined) lists.set(name, (list = [])); + if (list === undefined) { + lists.set(name, (list = [])); + } list.push({ order: childGroup.options[key], group: childGroup @@ -433,7 +437,9 @@ class ChunkGroup { const cmp = b.order - a.order; if (cmp !== 0) return cmp; // TOOD webpack 5 remove this check of compareTo - if (a.group.compareTo) return a.group.compareTo(b.group); + if (a.group.compareTo) { + return a.group.compareTo(b.group); + } return 0; }); result[name] = list.map(i => i.group); @@ -444,20 +450,22 @@ class ChunkGroup { checkConstraints() { const chunk = this; for (const child of chunk._children) { - if (!child._parents.has(chunk)) + if (!child._parents.has(chunk)) { throw new Error( `checkConstraints: child missing parent ${chunk.debugId} -> ${ child.debugId }` ); + } } for (const parentChunk of chunk._parents) { - if (!parentChunk._children.has(chunk)) + if (!parentChunk._children.has(chunk)) { throw new Error( `checkConstraints: parent missing child ${parentChunk.debugId} <- ${ chunk.debugId }` ); + } } } } diff --git a/lib/Compilation.js b/lib/Compilation.js index 64e262559f6..71e35e747ca 100644 --- a/lib/Compilation.js +++ b/lib/Compilation.js @@ -287,8 +287,9 @@ class Compilation extends Tapable { if (this.cache && this.cache[cacheName]) { const cacheModule = this.cache[cacheName]; - if (typeof cacheModule.updateCacheModule === "function") + if (typeof cacheModule.updateCacheModule === "function") { cacheModule.updateCacheModule(module); + } let rebuild = true; if (this.fileTimestamps && this.contextTimestamps) { @@ -302,8 +303,12 @@ class Compilation extends Tapable { cacheModule.disconnect(); this._modules.set(identifier, cacheModule); this.modules.push(cacheModule); - for (const err of cacheModule.errors) this.errors.push(err); - for (const err of cacheModule.warnings) this.warnings.push(err); + for (const err of cacheModule.errors) { + this.errors.push(err); + } + for (const err of cacheModule.warnings) { + this.warnings.push(err); + } return { module: cacheModule, issuer: true, @@ -355,7 +360,9 @@ class Compilation extends Tapable { const callback = err => { this._buildingModules.delete(module); - for (const cb of callbackList) cb(err); + for (const cb of callbackList) { + cb(err); + } }; this.hooks.buildModule.call(module); @@ -370,8 +377,11 @@ class Compilation extends Tapable { const err = errors[indexError]; err.origin = origin; err.dependencies = dependencies; - if (optional) this.warnings.push(err); - else this.errors.push(err); + if (optional) { + this.warnings.push(err); + } else { + this.errors.push(err); + } } const warnings = module.warnings; @@ -403,15 +413,17 @@ class Compilation extends Tapable { const resourceIdent = dep.getResourceIdentifier(); if (resourceIdent) { const factory = this.dependencyFactories.get(dep.constructor); - if (factory === undefined) + if (factory === undefined) { throw new Error( `No module factory available for dependency type: ${ dep.constructor.name }` ); + } let innerMap = dependencies.get(factory); - if (innerMap === undefined) + if (innerMap === undefined) { dependencies.set(factory, (innerMap = new Map())); + } let list = innerMap.get(resourceIdent); if (list === undefined) innerMap.set(resourceIdent, (list = [])); list.push(dep); @@ -781,7 +793,9 @@ class Compilation extends Tapable { const callback = err => { this._rebuildingModules.delete(module); - for (const cb of callbackList) cb(err); + for (const cb of callbackList) { + cb(err); + } }; this.hooks.rebuildModule.call(module); @@ -925,15 +939,18 @@ class Compilation extends Tapable { this.sortItemsWithChunkIds(); - if (shouldRecord) + if (shouldRecord) { this.hooks.recordModules.call(this.modules, this.records); - if (shouldRecord) this.hooks.recordChunks.call(this.chunks, this.records); + this.hooks.recordChunks.call(this.chunks, this.records); + } this.hooks.beforeHash.call(); this.createHash(); this.hooks.afterHash.call(); - if (shouldRecord) this.hooks.recordHash.call(this.records); + if (shouldRecord) { + this.hooks.recordHash.call(this.records); + } this.hooks.beforeModuleAssets.call(); this.createModuleAssets(); @@ -943,7 +960,9 @@ class Compilation extends Tapable { } this.hooks.additionalChunkAssets.call(this.chunks); this.summarizeDependencies(); - if (shouldRecord) this.hooks.record.call(this, this.records); + if (shouldRecord) { + this.hooks.record.call(this, this.records); + } this.hooks.additionalAssets.callAsync(err => { if (err) { @@ -1378,8 +1397,11 @@ class Compilation extends Tapable { // 3. Create a new Set of available modules at this points newAvailableModules = new Set(availableModules); - for (const chunk of chunkGroup.chunks) - for (const m of chunk.modulesIterable) newAvailableModules.add(m); + for (const chunk of chunkGroup.chunks) { + for (const m of chunk.modulesIterable) { + newAvailableModules.add(m); + } + } // 4. Filter edges with available modules const filteredDeps = deps.filter(filterFn); @@ -1532,8 +1554,11 @@ class Compilation extends Tapable { for (let indexModule2 = 0; indexModule2 < modules2.length; indexModule2++) { const module2 = modules2[indexModule2]; if (module2.id === null) { - if (unusedIds.length > 0) module2.id = unusedIds.pop(); - else module2.id = nextFreeModuleId++; + if (unusedIds.length > 0) { + module2.id = unusedIds.pop(); + } else { + module2.id = nextFreeModuleId++; + } } } } @@ -1587,8 +1612,11 @@ class Compilation extends Tapable { for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { const chunk = chunks[indexChunk]; if (chunk.id === null) { - if (unusedIds.length > 0) chunk.id = unusedIds.pop(); - else chunk.id = nextFreeChunkId++; + if (unusedIds.length > 0) { + chunk.id = unusedIds.pop(); + } else { + chunk.id = nextFreeChunkId++; + } } if (!chunk.ids) { chunk.ids = [chunk.id]; @@ -1697,14 +1725,23 @@ class Compilation extends Tapable { const hashDigest = outputOptions.hashDigest; const hashDigestLength = outputOptions.hashDigestLength; const hash = createHash(hashFunction); - if (outputOptions.hashSalt) hash.update(outputOptions.hashSalt); + if (outputOptions.hashSalt) { + hash.update(outputOptions.hashSalt); + } this.mainTemplate.updateHash(hash); this.chunkTemplate.updateHash(hash); - for (const key of Object.keys(this.moduleTemplates).sort()) + for (const key of Object.keys(this.moduleTemplates).sort()) { this.moduleTemplates[key].updateHash(hash); - for (const child of this.children) hash.update(child.hash); - for (const warning of this.warnings) hash.update(`${warning.message}`); - for (const error of this.errors) hash.update(`${error.message}`); + } + for (const child of this.children) { + hash.update(child.hash); + } + for (const warning of this.warnings) { + hash.update(`${warning.message}`); + } + for (const error of this.errors) { + hash.update(`${error.message}`); + } const modules = this.modules; for (let i = 0; i < modules.length; i++) { const module = modules[i]; @@ -1730,7 +1767,9 @@ class Compilation extends Tapable { for (let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; const chunkHash = createHash(hashFunction); - if (outputOptions.hashSalt) chunkHash.update(outputOptions.hashSalt); + if (outputOptions.hashSalt) { + chunkHash.update(outputOptions.hashSalt); + } chunk.updateHash(chunkHash); const template = chunk.hasRuntime() ? this.mainTemplate @@ -1823,10 +1862,11 @@ class Compilation extends Tapable { } } file = this.getPath(filenameTemplate, fileManifest.pathOptions); - if (this.assets[file] && this.assets[file] !== source) + if (this.assets[file] && this.assets[file] !== source) { throw new Error( `Conflict: Multiple assets emit to the same filename ${file}` ); + } this.assets[file] = source; chunk.files.push(file); this.hooks.chunkAsset.call(chunk, file); @@ -1864,18 +1904,20 @@ class Compilation extends Tapable { for (let indexModule = 0; indexModule < modules.length; indexModule++) { const moduleId = modules[indexModule].id; if (moduleId === null) continue; - if (usedIds.has(moduleId)) + if (usedIds.has(moduleId)) { throw new Error(`checkConstraints: duplicate module id ${moduleId}`); + } usedIds.add(moduleId); } const chunks = this.chunks; for (let indexChunk = 0; indexChunk < chunks.length; indexChunk++) { const chunk = chunks[indexChunk]; - if (chunks.indexOf(chunk) !== indexChunk) + if (chunks.indexOf(chunk) !== indexChunk) { throw new Error( `checkConstraints: duplicate chunk in compilation ${chunk.debugId}` ); + } } for (const chunkGroup of this.chunkGroups) { diff --git a/lib/Compiler.js b/lib/Compiler.js index 23b5d8cca6d..11d51471bc7 100644 --- a/lib/Compiler.js +++ b/lib/Compiler.js @@ -245,8 +245,9 @@ class Compiler extends Tapable { } purgeInputFileSystem() { - if (this.inputFileSystem && this.inputFileSystem.purge) + if (this.inputFileSystem && this.inputFileSystem.purge) { this.inputFileSystem.purge(); + } } emitAssets(compilation, callback) { @@ -291,7 +292,9 @@ class Compiler extends Tapable { this.outputFileSystem.join(outputPath, dir), writeOut ); - } else writeOut(); + } else { + writeOut(); + } }, err => { if (err) return callback(err); @@ -317,10 +320,11 @@ class Compiler extends Tapable { const idx1 = this.recordsOutputPath.lastIndexOf("/"); const idx2 = this.recordsOutputPath.lastIndexOf("\\"); let recordsOutputPathDirectory = null; - if (idx1 > idx2) + if (idx1 > idx2) { recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx1); - if (idx1 < idx2) + } else if (idx1 < idx2) { recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx2); + } const writeFile = () => { this.outputFileSystem.writeFile( @@ -330,7 +334,9 @@ class Compiler extends Tapable { ); }; - if (!recordsOutputPathDirectory) return writeFile(); + if (!recordsOutputPathDirectory) { + return writeFile(); + } this.outputFileSystem.mkdirp(recordsOutputPathDirectory, err => { if (err) return callback(err); writeFile(); @@ -371,7 +377,9 @@ class Compiler extends Tapable { ) { const childCompiler = new Compiler(this.context); if (Array.isArray(plugins)) { - for (const plugin of plugins) plugin.apply(childCompiler); + for (const plugin of plugins) { + plugin.apply(childCompiler); + } } for (const name in this.hooks) { if ( @@ -385,8 +393,9 @@ class Compiler extends Tapable { "thisCompilation" ].includes(name) ) { - if (childCompiler.hooks[name]) + if (childCompiler.hooks[name]) { childCompiler.hooks[name].taps = this.hooks[name].taps.slice(); + } } } childCompiler.name = compilerName; @@ -398,11 +407,14 @@ class Compiler extends Tapable { childCompiler.contextTimestamps = this.contextTimestamps; const relativeCompilerName = makePathsRelative(this.context, compilerName); - if (!this.records[relativeCompilerName]) + if (!this.records[relativeCompilerName]) { this.records[relativeCompilerName] = []; - if (this.records[relativeCompilerName][compilerIndex]) + } + if (this.records[relativeCompilerName][compilerIndex]) { childCompiler.records = this.records[relativeCompilerName][compilerIndex]; - else this.records[relativeCompilerName].push((childCompiler.records = {})); + } else { + this.records[relativeCompilerName].push((childCompiler.records = {})); + } childCompiler.options = Object.create(this.options); childCompiler.options.output = Object.create(childCompiler.options.output); diff --git a/lib/ConstPlugin.js b/lib/ConstPlugin.js index 736838353b2..03b279b6490 100644 --- a/lib/ConstPlugin.js +++ b/lib/ConstPlugin.js @@ -21,13 +21,19 @@ const collectDeclaration = (declarations, pattern) => { declarations.add(node.name); break; case "ArrayPattern": - for (const element of node.elements) if (element) stack.push(element); + for (const element of node.elements) { + if (element) { + stack.push(element); + } + } break; case "AssignmentPattern": stack.push(node.left); break; case "ObjectPattern": - for (const property of node.properties) stack.push(property.value); + for (const property of node.properties) { + stack.push(property.value); + } break; case "RestElement": stack.push(node.argument); @@ -47,7 +53,9 @@ const getHoistedDeclarations = (branch, includeFunctionDeclarations) => { // Walk through control statements to look for hoisted declarations. // Some branches are skipped since they do not allow declarations. case "BlockStatement": - for (const stmt of node.body) stack.push(stmt); + for (const stmt of node.body) { + stack.push(stmt); + } break; case "IfStatement": stack.push(node.consequent); @@ -68,22 +76,30 @@ const getHoistedDeclarations = (branch, includeFunctionDeclarations) => { stack.push(node.body); break; case "SwitchStatement": - for (const cs of node.cases) - for (const consequent of cs.consequent) stack.push(consequent); + for (const cs of node.cases) { + for (const consequent of cs.consequent) { + stack.push(consequent); + } + } break; case "TryStatement": stack.push(node.block); - if (node.handler) stack.push(node.handler.body); + if (node.handler) { + stack.push(node.handler.body); + } stack.push(node.finalizer); break; case "FunctionDeclaration": - if (includeFunctionDeclarations) + if (includeFunctionDeclarations) { collectDeclaration(declarations, node.id); + } break; case "VariableDeclaration": - if (node.kind === "var") - for (const decl of node.declarations) + if (node.kind === "var") { + for (const decl of node.declarations) { collectDeclaration(declarations, decl.id); + } + } break; } } diff --git a/lib/ContextModule.js b/lib/ContextModule.js index e0009450b36..042d5938cab 100644 --- a/lib/ContextModule.js +++ b/lib/ContextModule.js @@ -35,14 +35,16 @@ class ContextModule extends Module { resource: resource, resourceQuery: resourceQuery }); - if (options.resolveOptions !== undefined) + if (options.resolveOptions !== undefined) { this.resolveOptions = options.resolveOptions; + } // Info from Build this._contextDependencies = new Set([this.context]); - if (typeof options.mode !== "string") + if (typeof options.mode !== "string") { throw new Error("options.mode is a required option"); + } this._identifier = this._createIdentifier(); } @@ -73,22 +75,37 @@ class ContextModule extends Module { _createIdentifier() { let identifier = this.context; - if (this.options.resourceQuery) + if (this.options.resourceQuery) { identifier += ` ${this.options.resourceQuery}`; - if (this.options.mode) identifier += ` ${this.options.mode}`; - if (!this.options.recursive) identifier += " nonrecursive"; - if (this.options.addon) identifier += ` ${this.options.addon}`; - if (this.options.regExp) identifier += ` ${this.options.regExp}`; - if (this.options.include) identifier += ` include: ${this.options.include}`; - if (this.options.exclude) identifier += ` exclude: ${this.options.exclude}`; + } + if (this.options.mode) { + identifier += ` ${this.options.mode}`; + } + if (!this.options.recursive) { + identifier += " nonrecursive"; + } + if (this.options.addon) { + identifier += ` ${this.options.addon}`; + } + if (this.options.regExp) { + identifier += ` ${this.options.regExp}`; + } + if (this.options.include) { + identifier += ` include: ${this.options.include}`; + } + if (this.options.exclude) { + identifier += ` exclude: ${this.options.exclude}`; + } if (this.options.groupOptions) { identifier += ` groupOptions: ${JSON.stringify( this.options.groupOptions )}`; } - if (this.options.namespaceObject === "strict") + if (this.options.namespaceObject === "strict") { identifier += " strict namespace object"; - else if (this.options.namespaceObject) identifier += " namespace object"; + } else if (this.options.namespaceObject) { + identifier += " namespace object"; + } return identifier; } @@ -99,42 +116,62 @@ class ContextModule extends Module { readableIdentifier(requestShortener) { let identifier = requestShortener.shorten(this.context); - if (this.options.resourceQuery) + if (this.options.resourceQuery) { identifier += ` ${this.options.resourceQuery}`; - if (this.options.mode) identifier += ` ${this.options.mode}`; - if (!this.options.recursive) identifier += " nonrecursive"; - if (this.options.addon) + } + if (this.options.mode) { + identifier += ` ${this.options.mode}`; + } + if (!this.options.recursive) { + identifier += " nonrecursive"; + } + if (this.options.addon) { identifier += ` ${requestShortener.shorten(this.options.addon)}`; - if (this.options.regExp) + } + if (this.options.regExp) { identifier += ` ${this.prettyRegExp(this.options.regExp + "")}`; - if (this.options.include) + } + if (this.options.include) { identifier += ` include: ${this.prettyRegExp(this.options.include + "")}`; - if (this.options.exclude) + } + if (this.options.exclude) { identifier += ` exclude: ${this.prettyRegExp(this.options.exclude + "")}`; + } if (this.options.groupOptions) { const groupOptions = this.options.groupOptions; - for (const key of Object.keys(groupOptions)) + for (const key of Object.keys(groupOptions)) { identifier += ` ${key}: ${groupOptions[key]}`; + } } - if (this.options.namespaceObject === "strict") + if (this.options.namespaceObject === "strict") { identifier += " strict namespace object"; - else if (this.options.namespaceObject) identifier += " namespace object"; + } else if (this.options.namespaceObject) { + identifier += " namespace object"; + } return identifier; } libIdent(options) { let identifier = this.contextify(options.context, this.context); - if (this.options.mode) identifier += ` ${this.options.mode}`; - if (this.options.recursive) identifier += " recursive"; - if (this.options.addon) + if (this.options.mode) { + identifier += ` ${this.options.mode}`; + } + if (this.options.recursive) { + identifier += " recursive"; + } + if (this.options.addon) { identifier += ` ${this.contextify(options.context, this.options.addon)}`; - if (this.options.regExp) + } + if (this.options.regExp) { identifier += ` ${this.prettyRegExp(this.options.regExp + "")}`; - if (this.options.include) + } + if (this.options.include) { identifier += ` include: ${this.prettyRegExp(this.options.include + "")}`; - if (this.options.exclude) + } + if (this.options.exclude) { identifier += ` exclude: ${this.prettyRegExp(this.options.exclude + "")}`; + } return identifier; } @@ -206,7 +243,9 @@ class ContextModule extends Module { for (const dep of dependencies) { let chunkName = this.options.chunkName; if (chunkName) { - if (!/\[(index|request)\]/.test(chunkName)) chunkName += "[index]"; + if (!/\[(index|request)\]/.test(chunkName)) { + chunkName += "[index]"; + } chunkName = chunkName.replace(/\[index\]/g, index++); chunkName = chunkName.replace( /\[request\]/g, @@ -253,7 +292,9 @@ class ContextModule extends Module { } getFakeMap(dependencies) { - if (!this.options.namespaceObject) return 9; + if (!this.options.namespaceObject) { + return 9; + } // if we filter first we get a new array // therefor we dont need to create a clone of dependencies explicitly // therefore the order of this is !important! @@ -281,11 +322,18 @@ class ContextModule extends Module { } return map; }, Object.create(null)); - if (!hasNamespace && hasNonHarmony && !hasNamed) + if (!hasNamespace && hasNonHarmony && !hasNamed) { return this.options.namespaceObject === "strict" ? 1 : 7; - if (hasNamespace && !hasNonHarmony && !hasNamed) return 9; - if (!hasNamespace && !hasNonHarmony && hasNamed) return 3; - if (!hasNamespace && !hasNonHarmony && !hasNamed) return 9; + } + if (hasNamespace && !hasNonHarmony && !hasNamed) { + return 9; + } + if (!hasNamespace && !hasNonHarmony && hasNamed) { + return 3; + } + if (!hasNamespace && !hasNonHarmony && !hasNamed) { + return 9; + } return fakeMap; } @@ -296,13 +344,16 @@ class ContextModule extends Module { } getReturn(type) { - if (type === 9) return "__webpack_require__(id)"; + if (type === 9) { + return "__webpack_require__(id)"; + } return `__webpack_require__.t(id, ${type})`; } getReturnModuleObjectSource(fakeMap, fakeMapDataExpression = "fakeMap[id]") { - if (typeof fakeMap === "number") + if (typeof fakeMap === "number") { return `return ${this.getReturn(fakeMap)};`; + } return `return __webpack_require__.t(id, ${fakeMapDataExpression})`; } @@ -504,8 +555,9 @@ module.exports = webpackAsyncContext;`; hasMultipleOrNoChunks = true; } const arrayStart = [item.dependency.module.id]; - if (typeof fakeMap === "object") + if (typeof fakeMap === "object") { arrayStart.push(fakeMap[item.dependency.module.id]); + } map[item.userRequest] = arrayStart.concat( chunks.map(chunk => chunk.id) ); diff --git a/lib/ContextModuleFactory.js b/lib/ContextModuleFactory.js index 80f13eac154..2a52a58f058 100644 --- a/lib/ContextModuleFactory.js +++ b/lib/ContextModuleFactory.js @@ -67,17 +67,24 @@ module.exports = class ContextModuleFactory extends Tapable { loadersPrefix = ""; const idx = request.lastIndexOf("!"); if (idx >= 0) { - loaders = request.substr(0, idx + 1); + let loadersRequest = request.substr(0, idx + 1); let i; - for (i = 0; i < loaders.length && loaders[i] === "!"; i++) { + for ( + i = 0; + i < loadersRequest.length && loadersRequest[i] === "!"; + i++ + ) { loadersPrefix += "!"; } - loaders = loaders + loadersRequest = loadersRequest .substr(i) .replace(/!+$/, "") .replace(/!!+/g, "!"); - if (loaders === "") loaders = []; - else loaders = loaders.split("!"); + if (loadersRequest === "") { + loaders = []; + } else { + loaders = loadersRequest.split("!"); + } resource = request.substr(idx + 1); } else { loaders = []; @@ -222,9 +229,13 @@ module.exports = class ContextModuleFactory extends Tapable { callback(null, alternatives); } ); - } else callback(); + } else { + callback(); + } }); - } else callback(); + } else { + callback(); + } }, (err, result) => { if (err) return callback(err); diff --git a/lib/ContextReplacementPlugin.js b/lib/ContextReplacementPlugin.js index 84d1f0e744f..39c29de83bf 100644 --- a/lib/ContextReplacementPlugin.js +++ b/lib/ContextReplacementPlugin.js @@ -60,12 +60,15 @@ class ContextReplacementPlugin { cmf.hooks.beforeResolve.tap("ContextReplacementPlugin", result => { if (!result) return; if (resourceRegExp.test(result.request)) { - if (typeof newContentResource !== "undefined") + if (typeof newContentResource !== "undefined") { result.request = newContentResource; - if (typeof newContentRecursive !== "undefined") + } + if (typeof newContentRecursive !== "undefined") { result.recursive = newContentRecursive; - if (typeof newContentRegExp !== "undefined") + } + if (typeof newContentRegExp !== "undefined") { result.regExp = newContentRegExp; + } if (typeof newContentCallback === "function") { newContentCallback(result); } else { @@ -79,16 +82,20 @@ class ContextReplacementPlugin { cmf.hooks.afterResolve.tap("ContextReplacementPlugin", result => { if (!result) return; if (resourceRegExp.test(result.resource)) { - if (typeof newContentResource !== "undefined") + if (typeof newContentResource !== "undefined") { result.resource = path.resolve(result.resource, newContentResource); - if (typeof newContentRecursive !== "undefined") + } + if (typeof newContentRecursive !== "undefined") { result.recursive = newContentRecursive; - if (typeof newContentRegExp !== "undefined") + } + if (typeof newContentRegExp !== "undefined") { result.regExp = newContentRegExp; - if (typeof newContentCreateContextMap === "function") + } + if (typeof newContentCreateContextMap === "function") { result.resolveDependencies = createResolveDependenciesFromContextMap( newContentCreateContextMap ); + } if (typeof newContentCallback === "function") { const origResource = result.resource; newContentCallback(result); diff --git a/lib/DefinePlugin.js b/lib/DefinePlugin.js index bf168d7f3a2..4d485a9eb95 100644 --- a/lib/DefinePlugin.js +++ b/lib/DefinePlugin.js @@ -23,13 +23,22 @@ const stringifyObj = obj => { }; const toCode = code => { - if (code === null) return "null"; - else if (code === undefined) return "undefined"; - else if (code instanceof RegExp && code.toString) return code.toString(); - else if (typeof code === "function" && code.toString) + if (code === null) { + return "null"; + } + if (code === undefined) { + return "undefined"; + } + if (code instanceof RegExp && code.toString) { + return code.toString(); + } + if (typeof code === "function" && code.toString) { return "(" + code.toString() + ")"; - else if (typeof code === "object") return stringifyObj(code); - else return code + ""; + } + if (typeof code === "object") { + return stringifyObj(code); + } + return code + ""; }; class DefinePlugin { diff --git a/lib/DependenciesBlock.js b/lib/DependenciesBlock.js index 037118f5734..360cc5437ca 100644 --- a/lib/DependenciesBlock.js +++ b/lib/DependenciesBlock.js @@ -40,7 +40,9 @@ class DependenciesBlock { removeDependency(dependency) { const idx = this.dependencies.indexOf(dependency); - if (idx >= 0) this.dependencies.splice(idx, 1); + if (idx >= 0) { + this.dependencies.splice(idx, 1); + } } updateHash(hash) { diff --git a/lib/DependenciesBlockVariable.js b/lib/DependenciesBlockVariable.js index abb990b44fc..7f7416271aa 100644 --- a/lib/DependenciesBlockVariable.js +++ b/lib/DependenciesBlockVariable.js @@ -25,8 +25,9 @@ class DependenciesBlockVariable { const source = new ReplaceSource(new RawSource(this.expression)); for (const dep of this.dependencies) { const template = dependencyTemplates.get(dep.constructor); - if (!template) + if (!template) { throw new Error(`No template for dependency: ${dep.constructor.name}`); + } template.apply(dep, source, runtimeTemplate, dependencyTemplates); } return source; diff --git a/lib/DllPlugin.js b/lib/DllPlugin.js index 36fa4f84ce2..5542833719b 100644 --- a/lib/DllPlugin.js +++ b/lib/DllPlugin.js @@ -20,8 +20,10 @@ class DllPlugin { apply(compiler) { compiler.hooks.entryOption.tap("DllPlugin", (context, entry) => { const itemToPlugin = (item, name) => { - if (Array.isArray(item)) return new DllEntryPlugin(context, item, name); - else throw new Error("DllPlugin: supply an Array as entry"); + if (Array.isArray(item)) { + return new DllEntryPlugin(context, item, name); + } + throw new Error("DllPlugin: supply an Array as entry"); }; if (typeof entry === "object" && !Array.isArray(entry)) { Object.keys(entry).forEach(name => { diff --git a/lib/DynamicEntryPlugin.js b/lib/DynamicEntryPlugin.js index 38a5dbb3fc5..0f1fabf0e8b 100644 --- a/lib/DynamicEntryPlugin.js +++ b/lib/DynamicEntryPlugin.js @@ -65,7 +65,9 @@ class DynamicEntryPlugin { module.exports = DynamicEntryPlugin; DynamicEntryPlugin.createDependency = (entry, name) => { - if (Array.isArray(entry)) + if (Array.isArray(entry)) { return MultiEntryPlugin.createDependency(entry, name); - else return SingleEntryPlugin.createDependency(entry, name); + } else { + return SingleEntryPlugin.createDependency(entry, name); + } }; diff --git a/lib/ErrorHelpers.js b/lib/ErrorHelpers.js index 51d8017f3ae..900ae4d59e8 100644 --- a/lib/ErrorHelpers.js +++ b/lib/ErrorHelpers.js @@ -10,8 +10,11 @@ const webpackOptionsFlag = "WEBPACK_OPTIONS"; exports.cutOffByFlag = (stack, flag) => { stack = stack.split("\n"); - for (let i = 0; i < stack.length; i++) - if (stack[i].includes(flag)) stack.length = i; + for (let i = 0; i < stack.length; i++) { + if (stack[i].includes(flag)) { + stack.length = i; + } + } return stack.join("\n"); }; diff --git a/lib/EvalSourceMapDevToolPlugin.js b/lib/EvalSourceMapDevToolPlugin.js index a4641209b74..daf9aaddfc6 100644 --- a/lib/EvalSourceMapDevToolPlugin.js +++ b/lib/EvalSourceMapDevToolPlugin.js @@ -9,10 +9,11 @@ const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOpt class EvalSourceMapDevToolPlugin { constructor(options) { - if (arguments.length > 1) + if (arguments.length > 1) { throw new Error( "EvalSourceMapDevToolPlugin only takes one argument (pass an options object)" ); + } if (typeof options === "string") { options = { append: options diff --git a/lib/FlagDependencyUsagePlugin.js b/lib/FlagDependencyUsagePlugin.js index 9531b4b9008..51b70b6ae8f 100644 --- a/lib/FlagDependencyUsagePlugin.js +++ b/lib/FlagDependencyUsagePlugin.js @@ -26,16 +26,22 @@ class FlagDependencyUsagePlugin { const processModule = (module, usedExports) => { module.used = true; if (module.usedExports === true) return; - else if (usedExports === true) module.usedExports = true; - else if (Array.isArray(usedExports)) { + if (usedExports === true) { + module.usedExports = true; + } else if (Array.isArray(usedExports)) { const old = module.usedExports ? module.usedExports.length : -1; module.usedExports = addToSet( module.usedExports || [], usedExports ); - if (module.usedExports.length === old) return; - } else if (Array.isArray(module.usedExports)) return; - else module.usedExports = false; + if (module.usedExports.length === old) { + return; + } + } else if (Array.isArray(module.usedExports)) { + return; + } else { + module.usedExports = false; + } // for a module without side effects we stop tracking usage here when no export is used // This module won't be evaluated in this case diff --git a/lib/FunctionModuleTemplatePlugin.js b/lib/FunctionModuleTemplatePlugin.js index 4b4d8e1f68d..cf2e1b0eae4 100644 --- a/lib/FunctionModuleTemplatePlugin.js +++ b/lib/FunctionModuleTemplatePlugin.js @@ -47,30 +47,32 @@ class FunctionModuleTemplatePlugin { if ( Array.isArray(module.buildMeta.providedExports) && module.buildMeta.providedExports.length === 0 - ) + ) { source.add(Template.toComment("no exports provided") + "\n"); - else if (Array.isArray(module.buildMeta.providedExports)) + } else if (Array.isArray(module.buildMeta.providedExports)) { source.add( Template.toComment( "exports provided: " + module.buildMeta.providedExports.join(", ") ) + "\n" ); - else if (module.buildMeta.providedExports) + } else if (module.buildMeta.providedExports) { source.add(Template.toComment("no static exports found") + "\n"); + } if ( Array.isArray(module.usedExports) && module.usedExports.length === 0 - ) + ) { source.add(Template.toComment("no exports used") + "\n"); - else if (Array.isArray(module.usedExports)) + } else if (Array.isArray(module.usedExports)) { source.add( Template.toComment( "exports used: " + module.usedExports.join(", ") ) + "\n" ); - else if (module.usedExports) + } else if (module.usedExports) { source.add(Template.toComment("all exports used") + "\n"); + } if (module.optimizationBailout) { for (const text of module.optimizationBailout) { let code; diff --git a/lib/HotModuleReplacement.runtime.js b/lib/HotModuleReplacement.runtime.js index 044e04bb99e..855ca302e9b 100644 --- a/lib/HotModuleReplacement.runtime.js +++ b/lib/HotModuleReplacement.runtime.js @@ -19,13 +19,16 @@ module.exports = function() { var fn = function(request) { if (me.hot.active) { if (installedModules[request]) { - if (installedModules[request].parents.indexOf(moduleId) === -1) + if (installedModules[request].parents.indexOf(moduleId) === -1) { installedModules[request].parents.push(moduleId); + } } else { hotCurrentParents = [moduleId]; hotCurrentChildModule = request; } - if (me.children.indexOf(request) === -1) me.children.push(request); + if (me.children.indexOf(request) === -1) { + me.children.push(request); + } } else { console.warn( "[HMR] unexpected require(" + @@ -167,8 +170,9 @@ module.exports = function() { } function hotCheck(apply) { - if (hotStatus !== "idle") + if (hotStatus !== "idle") { throw new Error("check() is only allowed in idle status"); + } hotApplyOnUpdate = apply; hotSetStatus("check"); return hotDownloadManifest(hotRequestTimeout).then(function(update) { diff --git a/lib/HotModuleReplacementPlugin.js b/lib/HotModuleReplacementPlugin.js index 92221d6646a..4b0edac7241 100644 --- a/lib/HotModuleReplacementPlugin.js +++ b/lib/HotModuleReplacementPlugin.js @@ -255,8 +255,11 @@ module.exports = class HotModuleReplacementPlugin { mainTemplate.hooks.currentHash.tap( "HotModuleReplacementPlugin", (_, length) => { - if (isFinite(length)) return `hotCurrentHash.substr(0, ${length})`; - else return "hotCurrentHash"; + if (isFinite(length)) { + return `hotCurrentHash.substr(0, ${length})`; + } else { + return "hotCurrentHash"; + } } ); @@ -301,21 +304,24 @@ module.exports = class HotModuleReplacementPlugin { } ); // TODO webpack 5: refactor this, no custom hooks - if (!parser.hooks.hotAcceptCallback) + if (!parser.hooks.hotAcceptCallback) { parser.hooks.hotAcceptCallback = new SyncBailHook([ "expression", "requests" ]); - if (!parser.hooks.hotAcceptWithoutCallback) + } + if (!parser.hooks.hotAcceptWithoutCallback) { parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([ "expression", "requests" ]); + } parser.hooks.call .for("module.hot.accept") .tap("HotModuleReplacementPlugin", expr => { - if (!parser.state.compilation.hotUpdateChunkTemplate) + if (!parser.state.compilation.hotUpdateChunkTemplate) { return false; + } if (expr.arguments.length >= 1) { const arg = parser.evaluateExpression(expr.arguments[0]); let params = []; @@ -355,8 +361,9 @@ module.exports = class HotModuleReplacementPlugin { parser.hooks.call .for("module.hot.decline") .tap("HotModuleReplacementPlugin", expr => { - if (!parser.state.compilation.hotUpdateChunkTemplate) + if (!parser.state.compilation.hotUpdateChunkTemplate) { return false; + } if (expr.arguments.length === 1) { const arg = parser.evaluateExpression(expr.arguments[0]); let params = []; diff --git a/lib/JavascriptGenerator.js b/lib/JavascriptGenerator.js index 167a628c76b..882f7d4d4a6 100644 --- a/lib/JavascriptGenerator.js +++ b/lib/JavascriptGenerator.js @@ -143,10 +143,11 @@ class JavascriptGenerator { sourceDependency(dependency, dependencyTemplates, source, runtimeTemplate) { const template = dependencyTemplates.get(dependency.constructor); - if (!template) + if (!template) { throw new Error( "No template for dependency: " + dependency.constructor.name ); + } template.apply(dependency, source, runtimeTemplate, dependencyTemplates); } diff --git a/lib/JavascriptModulesPlugin.js b/lib/JavascriptModulesPlugin.js index 5570b8c4511..5e0aaf8c4c7 100644 --- a/lib/JavascriptModulesPlugin.js +++ b/lib/JavascriptModulesPlugin.js @@ -55,10 +55,8 @@ class JavascriptModulesPlugin { const moduleTemplates = options.moduleTemplates; const dependencyTemplates = options.dependencyTemplates; - let filenameTemplate; - if (chunk.filenameTemplate) - filenameTemplate = chunk.filenameTemplate; - else filenameTemplate = outputOptions.filename; + const filenameTemplate = + chunk.filenameTemplate || outputOptions.filename; const useChunkHash = compilation.mainTemplate.useChunkHash(chunk); @@ -101,11 +99,8 @@ class JavascriptModulesPlugin { const outputOptions = options.outputOptions; const moduleTemplates = options.moduleTemplates; const dependencyTemplates = options.dependencyTemplates; - - let filenameTemplate; - if (chunk.filenameTemplate) - filenameTemplate = chunk.filenameTemplate; - else filenameTemplate = outputOptions.chunkFilename; + const filenameTemplate = + chunk.filenameTemplate || outputOptions.chunkFilename; result.push({ render: () => diff --git a/lib/JsonParser.js b/lib/JsonParser.js index 6642fbbf109..f0c59777bb3 100644 --- a/lib/JsonParser.js +++ b/lib/JsonParser.js @@ -16,8 +16,9 @@ class JsonParser { const data = parseJson(source[0] === "\ufeff" ? source.slice(1) : source); state.module.buildInfo.jsonData = data; state.module.buildMeta.exportsType = "named"; - if (typeof data === "object" && data) + if (typeof data === "object" && data) { state.module.addDependency(new JsonExportsDependency(Object.keys(data))); + } state.module.addDependency(new JsonExportsDependency(["default"])); return state; } diff --git a/lib/LibraryTemplatePlugin.js b/lib/LibraryTemplatePlugin.js index cc7c828e180..484442efcbc 100644 --- a/lib/LibraryTemplatePlugin.js +++ b/lib/LibraryTemplatePlugin.js @@ -30,8 +30,9 @@ const accessorAccess = (base, accessor, joinWith = "; ") => { ? base + accessorToObjectAccess(accessors.slice(0, idx + 1)) : accessors[0] + accessorToObjectAccess(accessors.slice(1, idx + 1)); if (idx === accessors.length - 1) return a; - if (idx === 0 && typeof base === "undefined") + if (idx === 0 && typeof base === "undefined") { return `${a} = typeof ${a} === "object" ? ${a} : {}`; + } return `${a} = ${a} || {}`; }) .join(joinWith); diff --git a/lib/LoaderOptionsPlugin.js b/lib/LoaderOptionsPlugin.js index 1493df37b02..5d13e2c0643 100644 --- a/lib/LoaderOptionsPlugin.js +++ b/lib/LoaderOptionsPlugin.js @@ -14,10 +14,11 @@ class LoaderOptionsPlugin { validateOptions(schema, options || {}, "Loader Options Plugin"); if (typeof options !== "object") options = {}; - if (!options.test) + if (!options.test) { options.test = { test: () => true }; + } this.options = options; } diff --git a/lib/MainTemplate.js b/lib/MainTemplate.js index 1b0dba4d06b..3463546fea6 100644 --- a/lib/MainTemplate.js +++ b/lib/MainTemplate.js @@ -401,10 +401,11 @@ module.exports = class MainTemplate extends Tapable { if (chunk.hasEntryModule()) { source = this.hooks.renderWithEntry.call(source, chunk, hash); } - if (!source) + if (!source) { throw new Error( "Compiler error: MainTemplate plugin 'render' should return something" ); + } chunk.rendered = true; return new ConcatSource(source, ";"); } diff --git a/lib/Module.js b/lib/Module.js index 72f25857225..258dd2fcecb 100644 --- a/lib/Module.js +++ b/lib/Module.js @@ -225,8 +225,9 @@ class Module extends DependenciesBlock { hasReasonForChunk(chunk) { if (this._rewriteChunkInReasons) { - for (const operation of this._rewriteChunkInReasons) + for (const operation of this._rewriteChunkInReasons) { this._doRewriteChunkInReasons(operation.oldChunk, operation.newChunks); + } this._rewriteChunkInReasons = undefined; } for (let i = 0; i < this.reasons.length; i++) { @@ -241,8 +242,9 @@ class Module extends DependenciesBlock { rewriteChunkInReasons(oldChunk, newChunks) { // This is expensive. Delay operation until we really need the data - if (this._rewriteChunkInReasons === undefined) + if (this._rewriteChunkInReasons === undefined) { this._rewriteChunkInReasons = []; + } this._rewriteChunkInReasons.push({ oldChunk, newChunks @@ -266,13 +268,15 @@ class Module extends DependenciesBlock { // Mangle export name if possible if (this.isProvided(exportName)) { - if (this.buildMeta.exportsType === "namespace") + if (this.buildMeta.exportsType === "namespace") { return Template.numberToIdentifer(idx); - else if ( + } + if ( this.buildMeta.exportsType === "named" && !this.usedExports.includes("default") - ) + ) { return Template.numberToIdentifer(idx); + } } return exportName; } diff --git a/lib/ModuleFilenameHelpers.js b/lib/ModuleFilenameHelpers.js index 2847305b10e..105e89e3fa8 100644 --- a/lib/ModuleFilenameHelpers.js +++ b/lib/ModuleFilenameHelpers.js @@ -48,8 +48,9 @@ const getHash = str => { }; const asRegExp = test => { - if (typeof test === "string") + if (typeof test === "string") { test = new RegExp("^" + test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); + } return test; }; @@ -141,7 +142,9 @@ ModuleFilenameHelpers.replaceDuplicates = (array, fn, comparator) => { if (countMap[item].length > 1) { if (comparator && countMap[item][0] === i) return item; return fn(item, i, posMap[item]++); - } else return item; + } else { + return item; + } }); }; @@ -156,11 +159,20 @@ ModuleFilenameHelpers.matchPart = (str, test) => { }; ModuleFilenameHelpers.matchObject = (obj, str) => { - if (obj.test) - if (!ModuleFilenameHelpers.matchPart(str, obj.test)) return false; - if (obj.include) - if (!ModuleFilenameHelpers.matchPart(str, obj.include)) return false; - if (obj.exclude) - if (ModuleFilenameHelpers.matchPart(str, obj.exclude)) return false; + if (obj.test) { + if (!ModuleFilenameHelpers.matchPart(str, obj.test)) { + return false; + } + } + if (obj.include) { + if (!ModuleFilenameHelpers.matchPart(str, obj.include)) { + return false; + } + } + if (obj.exclude) { + if (ModuleFilenameHelpers.matchPart(str, obj.exclude)) { + return false; + } + } return true; }; diff --git a/lib/MultiCompiler.js b/lib/MultiCompiler.js index a21e971c2bf..cdc7fb5089e 100644 --- a/lib/MultiCompiler.js +++ b/lib/MultiCompiler.js @@ -162,8 +162,11 @@ module.exports = class MultiCompiler extends Tapable { for (const c of list) { const ready = !c.dependencies || c.dependencies.every(isDependencyFulfilled); - if (ready) readyCompilers.push(c); - else remainingCompilers.push(c); + if (ready) { + readyCompilers.push(c); + } else { + remainingCompilers.push(c); + } } return readyCompilers; }; @@ -233,12 +236,16 @@ module.exports = class MultiCompiler extends Tapable { } run(callback) { - if (this.running) return callback(new ConcurrentCompilationError()); + if (this.running) { + return callback(new ConcurrentCompilationError()); + } const finalCallback = (err, stats) => { this.running = false; - if (callback !== undefined) return callback(err, stats); + if (callback !== undefined) { + return callback(err, stats); + } }; const allStats = this.compilers.map(() => null); @@ -249,13 +256,17 @@ module.exports = class MultiCompiler extends Tapable { (compiler, callback) => { const compilerIdx = this.compilers.indexOf(compiler); compiler.run((err, stats) => { - if (err) return callback(err); + if (err) { + return callback(err); + } allStats[compilerIdx] = stats; callback(); }); }, err => { - if (err) return finalCallback(err); + if (err) { + return finalCallback(err); + } finalCallback(null, new MultiStats(allStats)); } ); @@ -264,8 +275,9 @@ module.exports = class MultiCompiler extends Tapable { purgeInputFileSystem() { for (const compiler of this.compilers) { - if (compiler.inputFileSystem && compiler.inputFileSystem.purge) + if (compiler.inputFileSystem && compiler.inputFileSystem.purge) { compiler.inputFileSystem.purge(); + } } } }; diff --git a/lib/MultiModule.js b/lib/MultiModule.js index 2150d01e73d..6aee82f6694 100644 --- a/lib/MultiModule.js +++ b/lib/MultiModule.js @@ -56,10 +56,13 @@ class MultiModule extends Module { let idx = 0; for (const dep of this.dependencies) { if (dep.module) { - if (idx === this.dependencies.length - 1) str.push("module.exports = "); + if (idx === this.dependencies.length - 1) { + str.push("module.exports = "); + } str.push("__webpack_require__("); - if (runtimeTemplate.outputOptions.pathinfo) + if (runtimeTemplate.outputOptions.pathinfo) { str.push(Template.toComment(dep.request)); + } str.push(`${JSON.stringify(dep.module.id)}`); str.push(")"); } else { diff --git a/lib/NodeStuffPlugin.js b/lib/NodeStuffPlugin.js index 515d4b17398..9ee407cd6df 100644 --- a/lib/NodeStuffPlugin.js +++ b/lib/NodeStuffPlugin.js @@ -30,8 +30,9 @@ class NodeStuffPlugin { if (parserOptions.node === false) return; let localOptions = options; - if (parserOptions.node) + if (parserOptions.node) { localOptions = Object.assign({}, localOptions, parserOptions.node); + } const setConstant = (expressionName, value) => { parser.hooks.expression diff --git a/lib/NormalModule.js b/lib/NormalModule.js index 125c21c2b8d..26ed491f944 100644 --- a/lib/NormalModule.js +++ b/lib/NormalModule.js @@ -153,12 +153,15 @@ class NormalModule extends Module { const loaderContext = { version: 2, emitWarning: warning => { - if (!(warning instanceof Error)) + if (!(warning instanceof Error)) { warning = new NonErrorEmittedError(warning); + } this.warnings.push(new ModuleWarning(this, warning)); }, emitError: error => { - if (!(error instanceof Error)) error = new NonErrorEmittedError(error); + if (!(error instanceof Error)) { + error = new NonErrorEmittedError(error); + } this.errors.push(new ModuleError(this, error)); }, exec: (code, filename) => { @@ -174,7 +177,9 @@ class NormalModule extends Module { resolver.resolve({}, context, request, {}, callback); }, emitFile: (name, content, sourceMap) => { - if (!this.buildInfo.assets) this.buildInfo.assets = Object.create(null); + if (!this.buildInfo.assets) { + this.buildInfo.assets = Object.create(null); + } this.buildInfo.assets[name] = this.createSourceForAsset( name, content, @@ -191,7 +196,9 @@ class NormalModule extends Module { }; compilation.hooks.normalModuleLoader.call(loaderContext, this); - if (options.loader) Object.assign(loaderContext, options.loader); + if (options.loader) { + Object.assign(loaderContext, options.loader); + } return loaderContext; } diff --git a/lib/NormalModuleFactory.js b/lib/NormalModuleFactory.js index 91ef80baf29..11dc42c75c1 100644 --- a/lib/NormalModuleFactory.js +++ b/lib/NormalModuleFactory.js @@ -21,11 +21,18 @@ const cachedMerge = require("./util/cachedMerge"); const EMPTY_RESOLVE_OPTIONS = {}; const loaderToIdent = data => { - if (!data.options) return data.loader; - if (typeof data.options === "string") return data.loader + "?" + data.options; - if (typeof data.options !== "object") + if (!data.options) { + return data.loader; + } + if (typeof data.options === "string") { + return data.loader + "?" + data.options; + } + if (typeof data.options !== "object") { throw new Error("loader options must be string or object"); - if (data.ident) return data.loader + "??" + data.ident; + } + if (data.ident) { + return data.loader + "??" + data.ident; + } return data.loader + "?" + JSON.stringify(data.options); }; @@ -252,16 +259,21 @@ class NormalModuleFactory extends Tapable { const useLoadersPre = []; for (const r of result) { if (r.type === "use") { - if (r.enforce === "post" && !noPrePostAutoLoaders) + if (r.enforce === "post" && !noPrePostAutoLoaders) { useLoadersPost.push(r.value); - else if ( + } else if ( r.enforce === "pre" && !noPreAutoLoaders && !noPrePostAutoLoaders - ) + ) { useLoadersPre.push(r.value); - else if (!r.enforce && !noAutoLoaders && !noPrePostAutoLoaders) + } else if ( + !r.enforce && + !noAutoLoaders && + !noPrePostAutoLoaders + ) { useLoaders.push(r.value); + } } else if ( typeof r.value === "object" && r.value !== null && @@ -428,8 +440,11 @@ class NormalModuleFactory extends Tapable { getParser(type, parserOptions) { let ident = type; if (parserOptions) { - if (parserOptions.ident) ident = `${type}|${parserOptions.ident}`; - else ident = JSON.stringify([type, parserOptions]); + if (parserOptions.ident) { + ident = `${type}|${parserOptions.ident}`; + } else { + ident = JSON.stringify([type, parserOptions]); + } } if (ident in this.parserCache) { return this.parserCache[ident]; @@ -449,8 +464,11 @@ class NormalModuleFactory extends Tapable { getGenerator(type, generatorOptions) { let ident = type; if (generatorOptions) { - if (generatorOptions.ident) ident = `${type}|${generatorOptions.ident}`; - else ident = JSON.stringify([type, generatorOptions]); + if (generatorOptions.ident) { + ident = `${type}|${generatorOptions.ident}`; + } else { + ident = JSON.stringify([type, generatorOptions]); + } } if (ident in this.generatorCache) { return this.generatorCache[ident]; diff --git a/lib/OptionsDefaulter.js b/lib/OptionsDefaulter.js index a2495b3746e..c5ff612d8d7 100644 --- a/lib/OptionsDefaulter.js +++ b/lib/OptionsDefaulter.js @@ -36,8 +36,9 @@ class OptionsDefaulter { for (let name in this.defaults) { switch (this.config[name]) { case undefined: - if (getProperty(options, name) === undefined) + if (getProperty(options, name) === undefined) { setProperty(options, name, this.defaults[name]); + } break; case "call": setProperty( @@ -47,12 +48,15 @@ class OptionsDefaulter { ); break; case "make": - if (getProperty(options, name) === undefined) + if (getProperty(options, name) === undefined) { setProperty(options, name, this.defaults[name].call(this, options)); + } break; case "append": { let oldValue = getProperty(options, name); - if (!Array.isArray(oldValue)) oldValue = []; + if (!Array.isArray(oldValue)) { + oldValue = []; + } oldValue.push(...this.defaults[name]); setProperty(options, name, oldValue); break; diff --git a/lib/Parser.js b/lib/Parser.js index cb91cc2ea83..eec89bfe3bf 100644 --- a/lib/Parser.js +++ b/lib/Parser.js @@ -117,17 +117,18 @@ class Parser extends Tapable { const regexp = HOOK_MAP_COMPAT_CONFIG[name]; const match = regexp.exec(options.name); if (match) { - if (match[1]) + if (match[1]) { this.hooks[name].tap( match[1], options.fn.name || "unnamed compat plugin", options.fn.bind(this) ); - else + } else { this.hooks[name].tap( options.fn.name || "unnamed compat plugin", options.fn.bind(this) ); + } return true; } } @@ -156,12 +157,14 @@ class Parser extends Tapable { .setBoolean(expr.value) .setRange(expr.range); } - if (expr.value === null) + if (expr.value === null) { return new BasicEvaluatedExpression().setNull().setRange(expr.range); - if (expr.value instanceof RegExp) + } + if (expr.value instanceof RegExp) { return new BasicEvaluatedExpression() .setRegExp(expr.value) .setRange(expr.range); + } }); this.hooks.evaluate.for("LogicalExpression").tap("Parser", expr => { let left; @@ -411,22 +414,26 @@ class Parser extends Tapable { .setRange(expr.range); } const arg = this.evaluateExpression(expr.argument); - if (arg.isString() || arg.isWrapped()) + if (arg.isString() || arg.isWrapped()) { return new BasicEvaluatedExpression() .setString("string") .setRange(expr.range); - else if (arg.isNumber()) + } + if (arg.isNumber()) { return new BasicEvaluatedExpression() .setString("number") .setRange(expr.range); - else if (arg.isBoolean()) + } + if (arg.isBoolean()) { return new BasicEvaluatedExpression() .setString("boolean") .setRange(expr.range); - else if (arg.isArray() || arg.isConstArray() || arg.isRegExp()) + } + if (arg.isArray() || arg.isConstArray() || arg.isRegExp()) { return new BasicEvaluatedExpression() .setString("object") .setRange(expr.range); + } } else if (expr.operator === "!") { const argument = this.evaluateExpression(expr.argument); if (!argument) return; @@ -434,19 +441,23 @@ class Parser extends Tapable { return new BasicEvaluatedExpression() .setBoolean(!argument.bool) .setRange(expr.range); - } else if (argument.isTruthy()) { + } + if (argument.isTruthy()) { return new BasicEvaluatedExpression() .setBoolean(false) .setRange(expr.range); - } else if (argument.isFalsy()) { + } + if (argument.isFalsy()) { return new BasicEvaluatedExpression() .setBoolean(true) .setRange(expr.range); - } else if (argument.isString()) { + } + if (argument.isString()) { return new BasicEvaluatedExpression() .setBoolean(!argument.string) .setRange(expr.range); - } else if (argument.isNumber()) { + } + if (argument.isNumber()) { return new BasicEvaluatedExpression() .setBoolean(!argument.number) .setRange(expr.range); @@ -696,7 +707,9 @@ class Parser extends Tapable { result = param.string.split(arg.string); } else if (arg.isRegExp()) { result = param.string.split(arg.regExp); - } else return; + } else { + return; + } return new BasicEvaluatedExpression() .setArray(result) .setRange(expr.range); @@ -710,10 +723,16 @@ class Parser extends Tapable { const alternate = this.evaluateExpression(expr.alternate); if (!consequent || !alternate) return; res = new BasicEvaluatedExpression(); - if (consequent.isConditional()) res.setOptions(consequent.options); - else res.setOptions([consequent]); - if (alternate.isConditional()) res.addOptions(alternate.options); - else res.addOptions([alternate]); + if (consequent.isConditional()) { + res.setOptions(consequent.options); + } else { + res.setOptions([consequent]); + } + if (alternate.isConditional()) { + res.addOptions(alternate.options); + } else { + res.addOptions([alternate]); + } } else { res = this.evaluateExpression( conditionValue ? expr.consequent : expr.alternate @@ -735,9 +754,9 @@ class Parser extends Tapable { getRenameIdentifier(expr) { const result = this.evaluateExpression(expr); - if (!result) return; - if (result.isIdentifier()) return result.identifier; - return; + if (result && result.isIdentifier()) { + return result.identifier; + } } walkClass(classy) { @@ -746,17 +765,21 @@ class Parser extends Tapable { const wasTopLevel = this.scope.topLevelScope; this.scope.topLevelScope = false; for (const methodDefinition of classy.body.body) { - if (methodDefinition.type === "MethodDefinition") + if (methodDefinition.type === "MethodDefinition") { this.walkMethodDefinition(methodDefinition); + } } this.scope.topLevelScope = wasTopLevel; } } walkMethodDefinition(methodDefinition) { - if (methodDefinition.computed && methodDefinition.key) + if (methodDefinition.computed && methodDefinition.key) { this.walkExpression(methodDefinition.key); - if (methodDefinition.value) this.walkExpression(methodDefinition.value); + } + if (methodDefinition.value) { + this.walkExpression(methodDefinition.value); + } } // Prewalking iterates the scope for variable declarations @@ -912,7 +935,9 @@ class Parser extends Tapable { prewalkIfStatement(statement) { this.prewalkStatement(statement.consequent); - if (statement.alternate) this.prewalkStatement(statement.alternate); + if (statement.alternate) { + this.prewalkStatement(statement.alternate); + } } walkIfStatement(statement) { @@ -920,10 +945,15 @@ class Parser extends Tapable { if (result === undefined) { this.walkExpression(statement.test); this.walkStatement(statement.consequent); - if (statement.alternate) this.walkStatement(statement.alternate); + if (statement.alternate) { + this.walkStatement(statement.alternate); + } } else { - if (result) this.walkStatement(statement.consequent); - else if (statement.alternate) this.walkStatement(statement.alternate); + if (result) { + this.walkStatement(statement.consequent); + } else if (statement.alternate) { + this.walkStatement(statement.alternate); + } } } @@ -1006,26 +1036,34 @@ class Parser extends Tapable { prewalkForStatement(statement) { if (statement.init) { - if (statement.init.type === "VariableDeclaration") + if (statement.init.type === "VariableDeclaration") { this.prewalkStatement(statement.init); + } } this.prewalkStatement(statement.body); } walkForStatement(statement) { if (statement.init) { - if (statement.init.type === "VariableDeclaration") + if (statement.init.type === "VariableDeclaration") { this.walkStatement(statement.init); - else this.walkExpression(statement.init); + } else { + this.walkExpression(statement.init); + } + } + if (statement.test) { + this.walkExpression(statement.test); + } + if (statement.update) { + this.walkExpression(statement.update); } - if (statement.test) this.walkExpression(statement.test); - if (statement.update) this.walkExpression(statement.update); this.walkStatement(statement.body); } prewalkForInStatement(statement) { - if (statement.left.type === "VariableDeclaration") + if (statement.left.type === "VariableDeclaration") { this.prewalkVariableDeclaration(statement.left); + } this.prewalkStatement(statement.body); } @@ -1142,7 +1180,7 @@ class Parser extends Tapable { switch (specifier.type) { case "ExportSpecifier": { const name = specifier.exported.name; - if (source) + if (source) { this.hooks.exportImportSpecifier.call( statement, source, @@ -1150,13 +1188,14 @@ class Parser extends Tapable { name, specifierIndex ); - else + } else { this.hooks.exportSpecifier.call( statement, specifier.local.name, name, specifierIndex ); + } break; } } @@ -1445,11 +1484,15 @@ class Parser extends Tapable { } walkArrayExpression(expression) { - if (expression.elements) this.walkExpressions(expression.elements); + if (expression.elements) { + this.walkExpressions(expression.elements); + } } walkSpreadElement(expression) { - if (expression.argument) this.walkExpression(expression.argument); + if (expression.argument) { + this.walkExpression(expression.argument); + } } walkObjectExpression(expression) { @@ -1463,10 +1506,16 @@ class Parser extends Tapable { this.walkExpression(prop.argument); continue; } - if (prop.computed) this.walkExpression(prop.key); - if (prop.shorthand) this.scope.inShorthand = true; + if (prop.computed) { + this.walkExpression(prop.key); + } + if (prop.shorthand) { + this.scope.inShorthand = true; + } this.walkExpression(prop.value); - if (prop.shorthand) this.scope.inShorthand = false; + if (prop.shorthand) { + this.scope.inShorthand = false; + } } } @@ -1576,10 +1625,15 @@ class Parser extends Tapable { if (result === undefined) { this.walkExpression(expression.test); this.walkExpression(expression.consequent); - if (expression.alternate) this.walkExpression(expression.alternate); + if (expression.alternate) { + this.walkExpression(expression.alternate); + } } else { - if (result) this.walkExpression(expression.consequent); - else if (expression.alternate) this.walkExpression(expression.alternate); + if (result) { + this.walkExpression(expression.consequent); + } else if (expression.alternate) { + this.walkExpression(expression.alternate); + } } } @@ -1596,21 +1650,30 @@ class Parser extends Tapable { } this.walkExpression(expression.callee); - if (expression.arguments) this.walkExpressions(expression.arguments); + if (expression.arguments) { + this.walkExpressions(expression.arguments); + } } walkYieldExpression(expression) { - if (expression.argument) this.walkExpression(expression.argument); + if (expression.argument) { + this.walkExpression(expression.argument); + } } walkTemplateLiteral(expression) { - if (expression.expressions) this.walkExpressions(expression.expressions); + if (expression.expressions) { + this.walkExpressions(expression.expressions); + } } walkTaggedTemplateExpression(expression) { - if (expression.tag) this.walkExpression(expression.tag); - if (expression.quasi && expression.quasi.expressions) + if (expression.tag) { + this.walkExpression(expression.tag); + } + if (expression.quasi && expression.quasi.expressions) { this.walkExpressions(expression.quasi.expressions); + } } walkClassExpression(expression) { @@ -1624,8 +1687,9 @@ class Parser extends Tapable { const hook = this.hooks.canRename.get(renameIdentifier); if (hook !== undefined && hook.call(argOrThis)) { const hook = this.hooks.rename.get(renameIdentifier); - if (hook === undefined || !hook.call(argOrThis)) + if (hook === undefined || !hook.call(argOrThis)) { return renameIdentifier; + } } } this.walkExpression(argOrThis); @@ -1852,11 +1916,12 @@ class Parser extends Tapable { parseString(expression) { switch (expression.type) { case "BinaryExpression": - if (expression.operator === "+") + if (expression.operator === "+") { return ( this.parseString(expression.left) + this.parseString(expression.right) ); + } break; case "Literal": return expression.value + ""; @@ -1903,12 +1968,20 @@ class Parser extends Tapable { const consequent = this.parseCalculatedString(expression.consequent); const alternate = this.parseCalculatedString(expression.alternate); const items = []; - if (consequent.conditional) items.push(...consequent.conditional); - else if (!consequent.code) items.push(consequent); - else break; - if (alternate.conditional) items.push(...alternate.conditional); - else if (!alternate.code) items.push(alternate); - else break; + if (consequent.conditional) { + items.push(...consequent.conditional); + } else if (!consequent.code) { + items.push(consequent); + } else { + break; + } + if (alternate.conditional) { + items.push(...alternate.conditional); + } else if (!alternate.code) { + items.push(alternate); + } else { + break; + } return { range: undefined, value: "", @@ -1975,8 +2048,9 @@ class Parser extends Tapable { sourceType: this.sourceType, locations: false }); - if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") + if (ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") { throw new Error("evaluate: Source is not a expression"); + } return this.evaluateExpression(ast.body[0].expression); } @@ -2029,8 +2103,12 @@ class Parser extends Tapable { return null; } let prefix = ""; - for (let i = exprName.length - 1; i >= 2; i--) prefix += exprName[i] + "."; - if (exprName.length > 1) prefix += exprName[1]; + for (let i = exprName.length - 1; i >= 2; i--) { + prefix += exprName[i] + "."; + } + if (exprName.length > 1) { + prefix += exprName[1]; + } const name = prefix ? prefix + "." + exprName[0] : exprName[0]; const nameGeneral = prefix; return { diff --git a/lib/ParserHelpers.js b/lib/ParserHelpers.js index 1098cb99c16..9552182dace 100644 --- a/lib/ParserHelpers.js +++ b/lib/ParserHelpers.js @@ -72,8 +72,11 @@ ParserHelpers.evaluateToIdentifier = (identifier, truthy) => { let evex = new BasicEvaluatedExpression() .setIdentifier(identifier) .setRange(expr.range); - if (truthy === true) evex = evex.setTruthy(); - else if (truthy === false) evex = evex.setFalsy(); + if (truthy === true) { + evex = evex.setTruthy(); + } else if (truthy === false) { + evex = evex.setFalsy(); + } return evex; }; }; diff --git a/lib/RawModule.js b/lib/RawModule.js index 94fc8c43d73..ab3fd3ab5bd 100644 --- a/lib/RawModule.js +++ b/lib/RawModule.js @@ -42,9 +42,11 @@ module.exports = class RawModule extends Module { } source() { - if (this.useSourceMap) + if (this.useSourceMap) { return new OriginalSource(this.sourceStr, this.identifier()); - else return new RawSource(this.sourceStr); + } else { + return new RawSource(this.sourceStr); + } } updateHash(hash) { diff --git a/lib/RecordIdsPlugin.js b/lib/RecordIdsPlugin.js index 2fa78da9e3b..32c16e48041 100644 --- a/lib/RecordIdsPlugin.js +++ b/lib/RecordIdsPlugin.js @@ -56,18 +56,20 @@ class RecordIdsPlugin { module.id = id; } } - if (Array.isArray(records.modules.usedIds)) + if (Array.isArray(records.modules.usedIds)) { compilation.usedModuleIds = new Set(records.modules.usedIds); + } } ); const getModuleIdentifier = module => { - if (portableIds) + if (portableIds) { return identifierUtils.makePathsRelative( compiler.context, module.identifier(), compilation.cache ); + } return module.identifier(); }; @@ -77,26 +79,27 @@ class RecordIdsPlugin { const index = chunkGroup.chunks.indexOf(chunk); for (const origin of chunkGroup.origins) { if (origin.module) { - if (origin.request) + if (origin.request) { sources.push( `${index} ${getModuleIdentifier(origin.module)} ${ origin.request }` ); - else if (typeof origin.loc === "string") + } else if (typeof origin.loc === "string") { sources.push( `${index} ${getModuleIdentifier(origin.module)} ${origin.loc}` ); - else if ( + } else if ( origin.loc && typeof origin.loc === "object" && origin.loc.start - ) + ) { sources.push( `${index} ${getModuleIdentifier( origin.module )} ${JSON.stringify(origin.loc.start)}` ); + } } } } @@ -152,8 +155,9 @@ class RecordIdsPlugin { } } } - if (Array.isArray(records.chunks.usedIds)) + if (Array.isArray(records.chunks.usedIds)) { compilation.usedChunkIds = new Set(records.chunks.usedIds); + } } ); }); diff --git a/lib/RequestShortener.js b/lib/RequestShortener.js index 3648dde96c7..e3e080b9ff3 100644 --- a/lib/RequestShortener.js +++ b/lib/RequestShortener.js @@ -23,8 +23,9 @@ const createRegExpForPath = path => { class RequestShortener { constructor(directory) { directory = normalizeBackSlashDirection(directory); - if (SEPARATOR_REGEXP.test(directory)) + if (SEPARATOR_REGEXP.test(directory)) { directory = directory.substr(0, directory.length - 1); + } if (directory) { this.currentDirectoryRegExp = createRegExpForPath(directory); @@ -54,16 +55,22 @@ class RequestShortener { shorten(request) { if (!request) return request; const cacheEntry = this.cache.get(request); - if (cacheEntry !== undefined) return cacheEntry; + if (cacheEntry !== undefined) { + return cacheEntry; + } let result = normalizeBackSlashDirection(request); - if (this.buildinsAsModule && this.buildinsRegExp) + if (this.buildinsAsModule && this.buildinsRegExp) { result = result.replace(this.buildinsRegExp, "!(webpack)"); - if (this.currentDirectoryRegExp) + } + if (this.currentDirectoryRegExp) { result = result.replace(this.currentDirectoryRegExp, "!."); - if (this.parentDirectoryRegExp) + } + if (this.parentDirectoryRegExp) { result = result.replace(this.parentDirectoryRegExp, "!.."); - if (!this.buildinsAsModule && this.buildinsRegExp) + } + if (!this.buildinsAsModule && this.buildinsRegExp) { result = result.replace(this.buildinsRegExp, "!(webpack)"); + } result = result.replace(INDEX_JS_REGEXP, "$1"); result = result.replace(FRONT_OR_BACK_BANG_REGEXP, ""); this.cache.set(request, result); diff --git a/lib/RuleSet.js b/lib/RuleSet.js index 093311cb4d5..2013a26d7e0 100644 --- a/lib/RuleSet.js +++ b/lib/RuleSet.js @@ -117,7 +117,7 @@ module.exports = class RuleSet { } static normalizeRule(rule, refs, ident) { - if (typeof rule === "string") + if (typeof rule === "string") { return { use: [ { @@ -125,9 +125,11 @@ module.exports = class RuleSet { } ] }; - if (!rule) + } + if (!rule) { throw new Error("Unexcepted null when object was expected as rule"); - if (typeof rule !== "object") + } + if (typeof rule !== "object") { throw new Error( "Unexcepted " + typeof rule + @@ -135,6 +137,7 @@ module.exports = class RuleSet { rule + ")" ); + } const newRule = {}; let useSource; @@ -142,7 +145,7 @@ module.exports = class RuleSet { let condition; const checkUseSource = newSource => { - if (useSource && useSource !== newSource) + if (useSource && useSource !== newSource) { throw new Error( RuleSet.buildErrorMessage( rule, @@ -155,11 +158,12 @@ module.exports = class RuleSet { ) ) ); + } useSource = newSource; }; const checkResourceSource = newSource => { - if (resourceSource && resourceSource !== newSource) + if (resourceSource && resourceSource !== newSource) { throw new Error( RuleSet.buildErrorMessage( rule, @@ -172,6 +176,7 @@ module.exports = class RuleSet { ) ) ); + } resourceSource = newSource; }; @@ -222,7 +227,7 @@ module.exports = class RuleSet { } } - if (rule.loader && rule.loaders) + if (rule.loader && rule.loaders) { throw new Error( RuleSet.buildErrorMessage( rule, @@ -231,6 +236,7 @@ module.exports = class RuleSet { ) ) ); + } const loader = rule.loaders || rule.loader; if (typeof loader === "string" && !rule.options && !rule.query) { @@ -274,19 +280,21 @@ module.exports = class RuleSet { newRule.use = RuleSet.normalizeUse(rule.use, ident); } - if (rule.rules) + if (rule.rules) { newRule.rules = RuleSet.normalizeRules( rule.rules, refs, `${ident}-rules` ); + } - if (rule.oneOf) + if (rule.oneOf) { newRule.oneOf = RuleSet.normalizeRules( rule.oneOf, refs, `${ident}-oneOf` ); + } const keys = Object.keys(rule).filter(key => { return ![ @@ -365,16 +373,22 @@ module.exports = class RuleSet { const newItem = {}; - if (item.options && item.query) + if (item.options && item.query) { throw new Error("Provided options and query in use"); + } - if (!item.loader) throw new Error("No loader specified"); + if (!item.loader) { + throw new Error("No loader specified"); + } newItem.options = item.options || item.query; if (typeof newItem.options === "object" && newItem.options) { - if (newItem.options.ident) newItem.ident = newItem.options.ident; - else newItem.ident = ident; + if (newItem.options.ident) { + newItem.ident = newItem.options.ident; + } else { + newItem.ident = ident; + } } const keys = Object.keys(item).filter(function(key) { @@ -403,7 +417,7 @@ module.exports = class RuleSet { const items = condition.map(c => RuleSet.normalizeCondition(c)); return orMatcher(items); } - if (typeof condition !== "object") + if (typeof condition !== "object") { throw Error( "Unexcepted " + typeof condition + @@ -411,6 +425,7 @@ module.exports = class RuleSet { condition + ")" ); + } const matchers = []; Object.keys(condition).forEach(key => { @@ -438,9 +453,12 @@ module.exports = class RuleSet { throw new Error("Unexcepted property " + key + " in condition"); } }); - if (matchers.length === 0) + if (matchers.length === 0) { throw new Error("Excepted condition but got " + condition); - if (matchers.length === 1) return matchers[0]; + } + if (matchers.length === 1) { + return matchers[0]; + } return andMatcher(matchers); } @@ -468,10 +486,12 @@ module.exports = class RuleSet { data.resourceQuery && rule.resourceQuery && !rule.resourceQuery(data.resourceQuery) - ) + ) { return false; - if (data.compiler && rule.compiler && !rule.compiler(data.compiler)) + } + if (data.compiler && rule.compiler && !rule.compiler(data.compiler)) { return false; + } // apply const keys = Object.keys(rule).filter(key => { @@ -527,8 +547,9 @@ module.exports = class RuleSet { findOptionsByIdent(ident) { const options = this.references[ident]; - if (!options) + if (!options) { throw new Error("Can't find options with ident '" + ident + "'"); + } return options; } }; diff --git a/lib/RuntimeTemplate.js b/lib/RuntimeTemplate.js index 7e975437f7e..92292d389c1 100644 --- a/lib/RuntimeTemplate.js +++ b/lib/RuntimeTemplate.js @@ -79,10 +79,11 @@ module.exports = class RuntimeTemplate { } moduleRaw({ module, request }) { - if (!module) + if (!module) { return this.missingModule({ request }); + } return `__webpack_require__(${this.moduleId({ module, request })})`; } @@ -94,10 +95,11 @@ module.exports = class RuntimeTemplate { } moduleNamespace({ module, request, strict }) { - if (!module) + if (!module) { return this.missingModule({ request }); + } const moduleId = this.moduleId({ module, request @@ -205,10 +207,11 @@ module.exports = class RuntimeTemplate { content += `/* harmony import */ ${optDeclaration}${importVar}_default = /*#__PURE__*/__webpack_require__.n(${importVar});\n`; } if (exportsType === "named") { - if (Array.isArray(module.buildMeta.providedExports)) + if (Array.isArray(module.buildMeta.providedExports)) { content += `${optDeclaration}${importVar}_namespace = /*#__PURE__*/__webpack_require__.t(${moduleId}, 1);\n`; - else + } else { content += `${optDeclaration}${importVar}_namespace = /*#__PURE__*/__webpack_require__.t(${moduleId});\n`; + } } return content; } @@ -223,18 +226,23 @@ module.exports = class RuntimeTemplate { callContext, importVar }) { - if (!module) + if (!module) { return this.missingModule({ request }); + } const exportsType = module.buildMeta && module.buildMeta.exportsType; if (!exportsType) { if (exportName === "default") { if (!originModule.buildMeta.strictHarmonyModule) { - if (isCall) return `${importVar}_default()`; - else if (asiSafe) return `(${importVar}_default())`; - else return `${importVar}_default.a`; + if (isCall) { + return `${importVar}_default()`; + } else if (asiSafe) { + return `(${importVar}_default())`; + } else { + return `${importVar}_default.a`; + } } else { return importVar; } @@ -261,8 +269,11 @@ module.exports = class RuntimeTemplate { used !== exportName ? Template.toNormalComment(exportName) + " " : ""; const access = `${importVar}[${comment}${JSON.stringify(used)}]`; if (isCall) { - if (callContext === false && asiSafe) return `(0,${access})`; - else if (callContext === false) return `Object(${access})`; + if (callContext === false && asiSafe) { + return `(0,${access})`; + } else if (callContext === false) { + return `Object(${access})`; + } } return access; } else { diff --git a/lib/SourceMapDevToolPlugin.js b/lib/SourceMapDevToolPlugin.js index cb6e8b27131..2c733428f60 100644 --- a/lib/SourceMapDevToolPlugin.js +++ b/lib/SourceMapDevToolPlugin.js @@ -53,10 +53,11 @@ const getTaskForFile = (file, chunk, options, compilation) => { class SourceMapDevToolPlugin { constructor(options) { - if (arguments.length > 1) + if (arguments.length > 1) { throw new Error( "SourceMapDevToolPlugin only takes one argument (pass an options object)" ); + } validateOptions(schema, options || {}, "SourceMap DevTool Plugin"); diff --git a/lib/Stats.js b/lib/Stats.js index ccb5594e5aa..9ece0f3bc48 100644 --- a/lib/Stats.js +++ b/lib/Stats.js @@ -114,10 +114,15 @@ class Stats { ); // eslint-disable-line no-useless-escape return ident => regExp.test(ident); } - if (item && typeof item === "object" && typeof item.test === "function") + if (item && typeof item === "object" && typeof item.test === "function") { return ident => item.test(ident); - if (typeof item === "function") return item; - if (typeof item === "boolean") return () => item; + } + if (typeof item === "function") { + return item; + } + if (typeof item === "boolean") { + return () => item; + } }; const compilation = this.compilation; @@ -260,10 +265,9 @@ class Stats { const formatError = e => { let text = ""; - if (typeof e === "string") - e = { - message: e - }; + if (typeof e === "string") { + e = { message: e }; + } if (e.chunk) { text += `chunk ${e.chunk.name || e.chunk.id}${ e.chunk.hasRuntime() @@ -286,9 +290,12 @@ class Stats { ); } text += e.message; - if (showErrorDetails && e.details) text += `\n${e.details}`; - if (showErrorDetails && e.missing) + if (showErrorDetails && e.details) { + text += `\n${e.details}`; + } + if (showErrorDetails && e.missing) { text += e.missing.map(item => `\n[${item}]`).join(""); + } if (showModuleTrace && e.origin) { text += `\n @ ${e.origin.readableIdentifier(requestShortener)}`; if (typeof e.originLoc === "object") { @@ -392,11 +399,13 @@ class Stats { } if (chunk.name) { assetsByFile[asset].chunkNames.push(chunk.name); - if (obj.assetsByChunkName[chunk.name]) + if (obj.assetsByChunkName[chunk.name]) { obj.assetsByChunkName[chunk.name] = [] .concat(obj.assetsByChunkName[chunk.name]) .concat([asset]); - else obj.assetsByChunkName[chunk.name] = asset; + } else { + obj.assetsByChunkName[chunk.name] = asset; + } } } } @@ -520,15 +529,20 @@ class Stats { }; if (reason.dependency) { const locInfo = formatLocation(reason.dependency.loc); - if (locInfo) obj.loc = locInfo; + if (locInfo) { + obj.loc = locInfo; + } } return obj; }) .sort((a, b) => a.moduleId - b.moduleId); } if (showUsedExports) { - if (module.used === true) obj.usedExports = module.usedExports; - else if (module.used === false) obj.usedExports = false; + if (module.used === true) { + obj.usedExports = module.usedExports; + } else if (module.used === false) { + obj.usedExports = false; + } } if (showProvidedExports) { obj.providedExports = Array.isArray(module.buildMeta.providedExports) @@ -662,12 +676,13 @@ class Stats { const obj = new Stats(child).toJson(childOptions, forToString); delete obj.hash; delete obj.version; - if (child.name) + if (child.name) { obj.name = identifierUtils.makePathsRelative( context, child.name, compilation.cache ); + } return obj; }); } @@ -745,7 +760,9 @@ class Stats { const rows = array.length; const cols = array[0].length; const colSizes = new Array(cols); - for (let col = 0; col < cols; col++) colSizes[col] = 0; + for (let col = 0; col < cols; col++) { + colSizes[col] = 0; + } for (let row = 0; row < rows; row++) { for (let col = 0; col < cols; col++) { const value = `${getText(array, row, col)}`; @@ -759,11 +776,18 @@ class Stats { const format = array[row][col].color; const value = `${getText(array, row, col)}`; let l = value.length; - if (align[col] === "l") format(value); - for (; l < colSizes[col] && col !== cols - 1; l++) colors.normal(" "); - if (align[col] === "r") format(value); - if (col + 1 < cols && colSizes[col] !== 0) + if (align[col] === "l") { + format(value); + } + for (; l < colSizes[col] && col !== cols - 1; l++) { + colors.normal(" "); + } + if (align[col] === "r") { + format(value); + } + if (col + 1 < cols && colSizes[col] !== 0) { colors.normal(splitter || " "); + } } newline(); } @@ -981,21 +1005,26 @@ class Stats { colors.magenta(" [prefetched]"); } if (module.failed) colors.red(" [failed]"); - if (module.warnings) + if (module.warnings) { colors.yellow( ` [${module.warnings} warning${module.warnings === 1 ? "" : "s"}]` ); - if (module.errors) + } + if (module.errors) { colors.red( ` [${module.errors} error${module.errors === 1 ? "" : "s"}]` ); + } }; const processModuleContent = (module, prefix) => { if (Array.isArray(module.providedExports)) { colors.normal(prefix); - if (module.providedExports.length === 0) colors.cyan("[no exports]"); - else colors.cyan(`[exports: ${module.providedExports.join(", ")}]`); + if (module.providedExports.length === 0) { + colors.cyan("[no exports]"); + } else { + colors.cyan(`[exports: ${module.providedExports.join(", ")}]`); + } newline(); } if (module.usedExports !== undefined) { @@ -1285,7 +1314,9 @@ class Stats { ); } - while (buf[buf.length - 1] === "\n") buf.pop(); + while (buf[buf.length - 1] === "\n") { + buf.pop(); + } return buf.join(""); } @@ -1356,13 +1387,18 @@ class Stats { static getChildOptions(options, idx) { let innerOptions; if (Array.isArray(options.children)) { - if (idx < options.children.length) innerOptions = options.children[idx]; + if (idx < options.children.length) { + innerOptions = options.children[idx]; + } } else if (typeof options.children === "object" && options.children) { innerOptions = options.children; } - if (typeof innerOptions === "boolean" || typeof innerOptions === "string") + if (typeof innerOptions === "boolean" || typeof innerOptions === "string") { innerOptions = Stats.presetToOptions(innerOptions); - if (!innerOptions) return options; + } + if (!innerOptions) { + return options; + } const childOptions = Object.assign({}, options); delete childOptions.children; // do not inherit children return Object.assign(childOptions, innerOptions); diff --git a/lib/Template.js b/lib/Template.js index 92327ac49f0..ee71eccc5b0 100644 --- a/lib/Template.js +++ b/lib/Template.js @@ -114,13 +114,15 @@ class Template { */ static numberToIdentifer(n) { // lower case - if (n < DELTA_A_TO_Z) + if (n < DELTA_A_TO_Z) { return String.fromCharCode(START_LOWERCASE_ALPHABET_CODE + n); + } // upper case n -= DELTA_A_TO_Z; - if (n < DELTA_A_TO_Z) + if (n < DELTA_A_TO_Z) { return String.fromCharCode(START_UPPERCASE_ALPHABET_CODE + n); + } // use multiple letters return ( diff --git a/lib/TemplatedPathPlugin.js b/lib/TemplatedPathPlugin.js index 791c161a9f0..8cd1ef40a44 100644 --- a/lib/TemplatedPathPlugin.js +++ b/lib/TemplatedPathPlugin.js @@ -39,10 +39,11 @@ const getReplacer = (value, allowEmpty) => { // last argument in replacer is the entire input string const input = args[args.length - 1]; if (value === null || value === undefined) { - if (!allowEmpty) + if (!allowEmpty) { throw new Error( `Path variable ${match} not implemented in this context: ${input}` ); + } return ""; } else { return `${value}`; @@ -150,8 +151,9 @@ class TemplatedPathPlugin { const outputOptions = mainTemplate.outputOptions; const chunkFilename = outputOptions.chunkFilename || outputOptions.filename; - if (REGEXP_CHUNKHASH_FOR_TEST.test(chunkFilename)) + if (REGEXP_CHUNKHASH_FOR_TEST.test(chunkFilename)) { hash.update(JSON.stringify(chunk.getChunkMaps(true).hash)); + } if (REGEXP_CONTENTHASH_FOR_TEST.test(chunkFilename)) { hash.update( JSON.stringify( @@ -159,8 +161,9 @@ class TemplatedPathPlugin { ) ); } - if (REGEXP_NAME_FOR_TEST.test(chunkFilename)) + if (REGEXP_NAME_FOR_TEST.test(chunkFilename)) { hash.update(JSON.stringify(chunk.getChunkMaps(true).name)); + } } ); }); diff --git a/lib/UmdMainTemplatePlugin.js b/lib/UmdMainTemplatePlugin.js index 5c794767f0a..795ae278272 100644 --- a/lib/UmdMainTemplatePlugin.js +++ b/lib/UmdMainTemplatePlugin.js @@ -144,16 +144,21 @@ class UmdMainTemplatePlugin { .map(m => { let expr; let request = m.request; - if (typeof request === "object") request = request[type]; - if (typeof request === "undefined") + if (typeof request === "object") { + request = request[type]; + } + if (typeof request === "undefined") { throw new Error( "Missing external configuration for type:" + type ); + } if (Array.isArray(request)) { expr = `require(${JSON.stringify( request[0] )})${accessorToObjectAccess(request.slice(1))}`; - } else expr = `require(${JSON.stringify(request)})`; + } else { + expr = `require(${JSON.stringify(request)})`; + } if (m.optional) { expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`; } diff --git a/lib/WarnCaseSensitiveModulesPlugin.js b/lib/WarnCaseSensitiveModulesPlugin.js index d29da028ece..867a33fe31e 100644 --- a/lib/WarnCaseSensitiveModulesPlugin.js +++ b/lib/WarnCaseSensitiveModulesPlugin.js @@ -24,8 +24,9 @@ class WarnCaseSensitiveModulesPlugin { } for (const pair of moduleWithoutCase) { const array = pair[1]; - if (array.length > 1) + if (array.length > 1) { compilation.warnings.push(new CaseSensitiveModulesWarning(array)); + } } }); } diff --git a/lib/Watching.js b/lib/Watching.js index 83ae72898e4..92e682146f2 100644 --- a/lib/Watching.js +++ b/lib/Watching.js @@ -128,8 +128,9 @@ class Watching { ) => { this.pausedWatcher = this.watcher; this.watcher = null; - if (err) return this.handler(err); - + if (err) { + return this.handler(err); + } this.compiler.fileTimestamps = fileTimestamps; this.compiler.contextTimestamps = contextTimestamps; this._invalidate(); diff --git a/lib/WebpackOptionsApply.js b/lib/WebpackOptionsApply.js index 0b9ba6c80ea..ccae783a520 100644 --- a/lib/WebpackOptionsApply.js +++ b/lib/WebpackOptionsApply.js @@ -298,38 +298,53 @@ class WebpackOptionsApply extends OptionsApply { new ImportPlugin(options.module).apply(compiler); new SystemPlugin(options.module).apply(compiler); - if (typeof options.mode !== "string") + if (typeof options.mode !== "string") { new WarnNoModeSetPlugin().apply(compiler); + } new EnsureChunkConditionsPlugin().apply(compiler); - if (options.optimization.removeAvailableModules) + if (options.optimization.removeAvailableModules) { new RemoveParentModulesPlugin().apply(compiler); - if (options.optimization.removeEmptyChunks) + } + if (options.optimization.removeEmptyChunks) { new RemoveEmptyChunksPlugin().apply(compiler); - if (options.optimization.mergeDuplicateChunks) + } + if (options.optimization.mergeDuplicateChunks) { new MergeDuplicateChunksPlugin().apply(compiler); - if (options.optimization.flagIncludedChunks) + } + if (options.optimization.flagIncludedChunks) { new FlagIncludedChunksPlugin().apply(compiler); - if (options.optimization.occurrenceOrder) + } + if (options.optimization.occurrenceOrder) { new OccurrenceOrderPlugin(true).apply(compiler); - if (options.optimization.sideEffects) + } + if (options.optimization.sideEffects) { new SideEffectsFlagPlugin().apply(compiler); - if (options.optimization.providedExports) + } + if (options.optimization.providedExports) { new FlagDependencyExportsPlugin().apply(compiler); - if (options.optimization.usedExports) + } + if (options.optimization.usedExports) { new FlagDependencyUsagePlugin().apply(compiler); - if (options.optimization.concatenateModules) + } + if (options.optimization.concatenateModules) { new ModuleConcatenationPlugin().apply(compiler); - if (options.optimization.splitChunks) + } + if (options.optimization.splitChunks) { new SplitChunksPlugin(options.optimization.splitChunks).apply(compiler); - if (options.optimization.runtimeChunk) + } + if (options.optimization.runtimeChunk) { new RuntimeChunkPlugin(options.optimization.runtimeChunk).apply(compiler); - if (options.optimization.noEmitOnErrors) + } + if (options.optimization.noEmitOnErrors) { new NoEmitOnErrorsPlugin().apply(compiler); - if (options.optimization.namedModules) + } + if (options.optimization.namedModules) { new NamedModulesPlugin().apply(compiler); - if (options.optimization.namedChunks) + } + if (options.optimization.namedChunks) { new NamedChunksPlugin().apply(compiler); + } if (options.optimization.nodeEnv) { new DefinePlugin({ "process.env.NODE_ENV": JSON.stringify(options.optimization.nodeEnv) @@ -361,8 +376,9 @@ class WebpackOptionsApply extends OptionsApply { } compiler.hooks.afterPlugins.call(compiler); - if (!compiler.inputFileSystem) + if (!compiler.inputFileSystem) { throw new Error("No input filesystem provided"); + } compiler.resolverFactory.hooks.resolveOptions .for("normal") .tap("WebpackOptionsApply", resolveOptions => { diff --git a/lib/WebpackOptionsDefaulter.js b/lib/WebpackOptionsDefaulter.js index d947e6a97db..e709b402ecb 100644 --- a/lib/WebpackOptionsDefaulter.js +++ b/lib/WebpackOptionsDefaulter.js @@ -136,10 +136,11 @@ class WebpackOptionsDefaulter extends OptionsDefaulter { } }); this.set("output.devtoolNamespace", "make", options => { - if (Array.isArray(options.output.library)) + if (Array.isArray(options.output.library)) { return options.output.library.join("."); - else if (typeof options.output.library === "object") + } else if (typeof options.output.library === "object") { return options.output.library.root || ""; + } return options.output.library || ""; }); this.set("output.libraryTarget", "var"); @@ -305,9 +306,11 @@ class WebpackOptionsDefaulter extends OptionsDefaulter { this.set("resolve.extensions", [".wasm", ".mjs", ".js", ".json"]); this.set("resolve.mainFiles", ["index"]); this.set("resolve.aliasFields", "make", options => { - if (options.target === "web" || options.target === "webworker") + if (options.target === "web" || options.target === "webworker") { return ["browser"]; - else return []; + } else { + return []; + } }); this.set("resolve.mainFields", "make", options => { if ( diff --git a/lib/WebpackOptionsValidationError.js b/lib/WebpackOptionsValidationError.js index 8c5ed0b5bb2..0475991a45a 100644 --- a/lib/WebpackOptionsValidationError.js +++ b/lib/WebpackOptionsValidationError.js @@ -30,15 +30,23 @@ const getSchemaPartText = (schemaPart, additionalPath) => { if (inner) schemaPart = inner; } } - while (schemaPart.$ref) schemaPart = getSchemaPart(schemaPart.$ref); + while (schemaPart.$ref) { + schemaPart = getSchemaPart(schemaPart.$ref); + } let schemaText = WebpackOptionsValidationError.formatSchema(schemaPart); - if (schemaPart.description) schemaText += `\n-> ${schemaPart.description}`; + if (schemaPart.description) { + schemaText += `\n-> ${schemaPart.description}`; + } return schemaText; }; const getSchemaPartDescription = schemaPart => { - while (schemaPart.$ref) schemaPart = getSchemaPart(schemaPart.$ref); - if (schemaPart.description) return `\n-> ${schemaPart.description}`; + while (schemaPart.$ref) { + schemaPart = getSchemaPart(schemaPart.$ref); + } + if (schemaPart.description) { + return `\n-> ${schemaPart.description}`; + } return ""; }; @@ -87,12 +95,15 @@ class WebpackOptionsValidationError extends WebpackError { prevSchemas = prevSchemas || []; const formatInnerSchema = (innerSchema, addSelf) => { - if (!addSelf) + if (!addSelf) { return WebpackOptionsValidationError.formatSchema( innerSchema, prevSchemas ); - if (prevSchemas.includes(innerSchema)) return "(recursive)"; + } + if (prevSchemas.includes(innerSchema)) { + return "(recursive)"; + } return WebpackOptionsValidationError.formatSchema( innerSchema, prevSchemas.concat(schema) @@ -100,15 +111,21 @@ class WebpackOptionsValidationError extends WebpackError { }; if (schema.type === "string") { - if (schema.minLength === 1) return "non-empty string"; - else if (schema.minLength > 1) + if (schema.minLength === 1) { + return "non-empty string"; + } + if (schema.minLength > 1) { return `string (min length ${schema.minLength})`; + } return "string"; - } else if (schema.type === "boolean") { + } + if (schema.type === "boolean") { return "boolean"; - } else if (schema.type === "number") { + } + if (schema.type === "number") { return "number"; - } else if (schema.type === "object") { + } + if (schema.type === "object") { if (schema.properties) { const required = schema.required || []; return `object { ${Object.keys(schema.properties) @@ -125,7 +142,8 @@ class WebpackOptionsValidationError extends WebpackError { )} }`; } return "object"; - } else if (schema.type === "array") { + } + if (schema.type === "array") { return `[${formatInnerSchema(schema.items)}]`; } @@ -135,12 +153,22 @@ class WebpackOptionsValidationError extends WebpackError { case "RegExp": return "RegExp"; } - if (schema.$ref) return formatInnerSchema(getSchemaPart(schema.$ref), true); - if (schema.allOf) return schema.allOf.map(formatInnerSchema).join(" & "); - if (schema.oneOf) return schema.oneOf.map(formatInnerSchema).join(" | "); - if (schema.anyOf) return schema.anyOf.map(formatInnerSchema).join(" | "); - if (schema.enum) + + if (schema.$ref) { + return formatInnerSchema(getSchemaPart(schema.$ref), true); + } + if (schema.allOf) { + return schema.allOf.map(formatInnerSchema).join(" & "); + } + if (schema.oneOf) { + return schema.oneOf.map(formatInnerSchema).join(" | "); + } + if (schema.anyOf) { + return schema.anyOf.map(formatInnerSchema).join(" | "); + } + if (schema.enum) { return schema.enum.map(item => JSON.stringify(item)).join(" | "); + } return JSON.stringify(schema, null, 2); } @@ -283,14 +311,15 @@ class WebpackOptionsValidationError extends WebpackError { err.keyword === "minItems" || err.keyword === "minProperties" ) { - if (err.params.limit === 1) + if (err.params.limit === 1) { return `${dataPath} should not be empty.${getSchemaPartDescription( err.parentSchema )}`; - else + } else { return `${dataPath} ${err.message}${getSchemaPartDescription( err.parentSchema )}`; + } } else if (err.keyword === "absolutePath") { const baseMessage = `${dataPath}: ${ err.message diff --git a/lib/dependencies/AMDDefineDependencyParserPlugin.js b/lib/dependencies/AMDDefineDependencyParserPlugin.js index fb1c9629e63..c4cb5789a22 100644 --- a/lib/dependencies/AMDDefineDependencyParserPlugin.js +++ b/lib/dependencies/AMDDefineDependencyParserPlugin.js @@ -215,11 +215,14 @@ class AMDDefineDependencyParserPlugin { let fnParams = null; let fnParamsOffset = 0; if (fn) { - if (isUnboundFunctionExpression(fn)) fnParams = fn.params; - else if (isBoundFunctionExpression(fn)) { + if (isUnboundFunctionExpression(fn)) { + fnParams = fn.params; + } else if (isBoundFunctionExpression(fn)) { fnParams = fn.callee.object.params; fnParamsOffset = fn.arguments.length - 1; - if (fnParamsOffset < 0) fnParamsOffset = 0; + if (fnParamsOffset < 0) { + fnParamsOffset = 0; + } } } let fnRenames = parser.scope.renames.createChild(); @@ -234,7 +237,7 @@ class AMDDefineDependencyParserPlugin { namedModule ); if (!result) return; - if (fnParams) + if (fnParams) { fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { if (identifiers[idx]) { fnRenames.set(param.name, identifiers[idx]); @@ -242,9 +245,10 @@ class AMDDefineDependencyParserPlugin { } return true; }); + } } else { const identifiers = ["require", "exports", "module"]; - if (fnParams) + if (fnParams) { fnParams = fnParams.slice(fnParamsOffset).filter((param, idx) => { if (identifiers[idx]) { fnRenames.set(param.name, identifiers[idx]); @@ -252,6 +256,7 @@ class AMDDefineDependencyParserPlugin { } return true; }); + } } let inTry; if (fn && isUnboundFunctionExpression(fn)) { @@ -274,12 +279,16 @@ class AMDDefineDependencyParserPlugin { () => { parser.scope.renames = fnRenames; parser.scope.inTry = inTry; - if (fn.callee.object.body.type === "BlockStatement") + if (fn.callee.object.body.type === "BlockStatement") { parser.walkStatement(fn.callee.object.body); - else parser.walkExpression(fn.callee.object.body); + } else { + parser.walkExpression(fn.callee.object.body); + } } ); - if (fn.arguments) parser.walkExpressions(fn.arguments); + if (fn.arguments) { + parser.walkExpressions(fn.arguments); + } } else if (fn || obj) { parser.walkExpression(fn || obj); } diff --git a/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js b/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js index 19770bb3cf3..a5745b98bb8 100644 --- a/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js +++ b/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js @@ -30,9 +30,11 @@ class AMDRequireDependenciesBlockParserPlugin { return !["require", "module", "exports"].includes(i.name); }), () => { - if (fnData.fn.body.type === "BlockStatement") + if (fnData.fn.body.type === "BlockStatement") { parser.walkStatement(fnData.fn.body); - else parser.walkExpression(fnData.fn.body); + } else { + parser.walkExpression(fnData.fn.body); + } } ); parser.walkExpressions(fnData.expressions); @@ -212,7 +214,7 @@ class AMDRequireDependenciesBlockParserPlugin { if (!result) { dep = new UnsupportedDependency("unsupported", expr.range); old.addDependency(dep); - if (parser.state.module) + if (parser.state.module) { parser.state.module.errors.push( new UnsupportedFeatureWarning( parser.state.module, @@ -220,6 +222,7 @@ class AMDRequireDependenciesBlockParserPlugin { expr.loc.start.line ) ); + } dep = null; return true; } diff --git a/lib/dependencies/HarmonyDetectionParserPlugin.js b/lib/dependencies/HarmonyDetectionParserPlugin.js index 4599c2e3d27..062ec21a67b 100644 --- a/lib/dependencies/HarmonyDetectionParserPlugin.js +++ b/lib/dependencies/HarmonyDetectionParserPlugin.js @@ -58,14 +58,16 @@ module.exports = class HarmonyDetectionParserPlugin { const skipInHarmony = () => { const module = parser.state.module; - if (module && module.buildMeta && module.buildMeta.exportsType) + if (module && module.buildMeta && module.buildMeta.exportsType) { return true; + } }; const nullInHarmony = () => { const module = parser.state.module; - if (module && module.buildMeta && module.buildMeta.exportsType) + if (module && module.buildMeta && module.buildMeta.exportsType) { return null; + } }; const nonHarmonyIdentifiers = ["define", "exports"]; diff --git a/lib/dependencies/HarmonyExportImportedSpecifierDependency.js b/lib/dependencies/HarmonyExportImportedSpecifierDependency.js index 2f7616080be..de25fcb2f06 100644 --- a/lib/dependencies/HarmonyExportImportedSpecifierDependency.js +++ b/lib/dependencies/HarmonyExportImportedSpecifierDependency.js @@ -255,8 +255,10 @@ class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { otherImportedModule && Array.isArray(otherImportedModule.buildMeta.providedExports) ) { - for (const exportName of otherImportedModule.buildMeta.providedExports) + for (const exportName of otherImportedModule.buildMeta + .providedExports) { result.add(exportName); + } } } return result; @@ -563,12 +565,14 @@ HarmonyExportImportedSpecifierDependency.Template = class HarmonyExportImportedS // Filter out exports which are defined by other exports // and filter out default export because it cannot be reexported with * - if (activeExports.size > 0) + if (activeExports.size > 0) { content += "if(" + JSON.stringify(Array.from(activeExports).concat("default")) + ".indexOf(__WEBPACK_IMPORT_KEY__) < 0) "; - else content += "if(__WEBPACK_IMPORT_KEY__ !== 'default') "; + } else { + content += "if(__WEBPACK_IMPORT_KEY__ !== 'default') "; + } const exportsName = dep.originModule.exportsArgument; return ( content + diff --git a/lib/dependencies/HarmonyImportDependencyParserPlugin.js b/lib/dependencies/HarmonyImportDependencyParserPlugin.js index 4c975fc06ac..97e28ec4920 100644 --- a/lib/dependencies/HarmonyImportDependencyParserPlugin.js +++ b/lib/dependencies/HarmonyImportDependencyParserPlugin.js @@ -42,8 +42,9 @@ module.exports = class HarmonyImportDependencyParserPlugin { (statement, source, id, name) => { parser.scope.definitions.delete(name); parser.scope.renames.set(name, "imported var"); - if (!parser.state.harmonySpecifier) + if (!parser.state.harmonySpecifier) { parser.state.harmonySpecifier = new Map(); + } parser.state.harmonySpecifier.set(name, { source, id, @@ -152,16 +153,18 @@ module.exports = class HarmonyImportDependencyParserPlugin { return true; }); // TODO webpack 5: refactor this, no custom hooks - if (!parser.hooks.hotAcceptCallback) + if (!parser.hooks.hotAcceptCallback) { parser.hooks.hotAcceptCallback = new SyncBailHook([ "expression", "requests" ]); - if (!parser.hooks.hotAcceptWithoutCallback) + } + if (!parser.hooks.hotAcceptWithoutCallback) { parser.hooks.hotAcceptWithoutCallback = new SyncBailHook([ "expression", "requests" ]); + } parser.hooks.hotAcceptCallback.tap( "HarmonyImportDependencyParserPlugin", (expr, requests) => { diff --git a/lib/dependencies/ImportParserPlugin.js b/lib/dependencies/ImportParserPlugin.js index 40daaf66e02..cb3d996efa8 100644 --- a/lib/dependencies/ImportParserPlugin.js +++ b/lib/dependencies/ImportParserPlugin.js @@ -18,10 +18,11 @@ class ImportParserPlugin { apply(parser) { parser.hooks.importCall.tap("ImportParserPlugin", expr => { - if (expr.arguments.length !== 1) + if (expr.arguments.length !== 1) { throw new Error( "Incorrect number of arguments provided to 'import(module: string) -> Promise'." ); + } const param = parser.evaluateExpression(expr.arguments[0]); diff --git a/lib/dependencies/LoaderPlugin.js b/lib/dependencies/LoaderPlugin.js index efce35e6ab4..14388db5eca 100644 --- a/lib/dependencies/LoaderPlugin.js +++ b/lib/dependencies/LoaderPlugin.js @@ -28,7 +28,7 @@ class LoaderPlugin { const factory = compilation.dependencyFactories.get( dep.constructor ); - if (factory === undefined) + if (factory === undefined) { return callback( new Error( `No module factory available for dependency type: ${ @@ -36,6 +36,7 @@ class LoaderPlugin { }` ) ); + } compilation.semaphore.release(); compilation.addModuleDependencies( module, @@ -50,16 +51,20 @@ class LoaderPlugin { true, err => { compilation.semaphore.acquire(() => { - if (err) return callback(err); - - if (!dep.module) + if (err) { + return callback(err); + } + if (!dep.module) { return callback(new Error("Cannot load the module")); - - if (dep.module.error) return callback(dep.module.error); - if (!dep.module._source) + } + if (dep.module.error) { + return callback(dep.module.error); + } + if (!dep.module._source) { throw new Error( "The module created for a LoaderDependency must have a property _source" ); + } let source, map; const moduleSource = dep.module._source; if (moduleSource.sourceAndMap) { diff --git a/lib/dependencies/LocalModulesHelpers.js b/lib/dependencies/LocalModulesHelpers.js index 73de4b971d4..05662270448 100644 --- a/lib/dependencies/LocalModulesHelpers.js +++ b/lib/dependencies/LocalModulesHelpers.js @@ -10,21 +10,26 @@ const LocalModulesHelpers = exports; const lookup = (parent, mod) => { if (mod.charAt(0) !== ".") return mod; - var path = parent.split("/"), - segs = mod.split("/"); + var path = parent.split("/"); + var segs = mod.split("/"); path.pop(); for (let i = 0; i < segs.length; i++) { const seg = segs[i]; - if (seg === "..") path.pop(); - else if (seg !== ".") path.push(seg); + if (seg === "..") { + path.pop(); + } else if (seg !== ".") { + path.push(seg); + } } return path.join("/"); }; LocalModulesHelpers.addLocalModule = (state, name) => { - if (!state.localModules) state.localModules = []; + if (!state.localModules) { + state.localModules = []; + } const m = new LocalModule(state.module, name, state.localModules.length); state.localModules.push(m); return m; @@ -37,7 +42,9 @@ LocalModulesHelpers.getLocalModule = (state, name, namedModule) => { name = lookup(namedModule, name); } for (let i = 0; i < state.localModules.length; i++) { - if (state.localModules[i].name === name) return state.localModules[i]; + if (state.localModules[i].name === name) { + return state.localModules[i]; + } } return null; }; diff --git a/lib/dependencies/RequireContextPlugin.js b/lib/dependencies/RequireContextPlugin.js index 549ba5c99d3..24312449c22 100644 --- a/lib/dependencies/RequireContextPlugin.js +++ b/lib/dependencies/RequireContextPlugin.js @@ -11,10 +11,12 @@ const RequireContextDependencyParserPlugin = require("./RequireContextDependency class RequireContextPlugin { constructor(modulesDirectories, extensions, mainFiles) { - if (!Array.isArray(modulesDirectories)) + if (!Array.isArray(modulesDirectories)) { throw new Error("modulesDirectories must be an array"); - if (!Array.isArray(extensions)) + } + if (!Array.isArray(extensions)) { throw new Error("extensions must be an array"); + } this.modulesDirectories = modulesDirectories; this.extensions = extensions; this.mainFiles = mainFiles; diff --git a/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js b/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js index 2bc3a2ebe0e..213eaac0a92 100644 --- a/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js +++ b/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js @@ -86,9 +86,11 @@ module.exports = class RequireEnsureDependenciesBlockParserPlugin { return; } if (successExpression) { - if (successExpression.fn.body.type === "BlockStatement") + if (successExpression.fn.body.type === "BlockStatement") { parser.walkStatement(successExpression.fn.body); - else parser.walkExpression(successExpression.fn.body); + } else { + parser.walkExpression(successExpression.fn.body); + } } old.addBlock(dep); } finally { @@ -98,9 +100,11 @@ module.exports = class RequireEnsureDependenciesBlockParserPlugin { parser.walkExpression(successExpressionArg); } if (errorExpression) { - if (errorExpression.fn.body.type === "BlockStatement") + if (errorExpression.fn.body.type === "BlockStatement") { parser.walkStatement(errorExpression.fn.body); - else parser.walkExpression(errorExpression.fn.body); + } else { + parser.walkExpression(errorExpression.fn.body); + } } else if (errorExpressionArg) { parser.walkExpression(errorExpressionArg); } diff --git a/lib/formatLocation.js b/lib/formatLocation.js index 214838beb2b..8bd574d0102 100644 --- a/lib/formatLocation.js +++ b/lib/formatLocation.js @@ -14,11 +14,15 @@ const formatPosition = pos => { case "number": return `${pos}`; case "object": - if (typeof pos.line === "number" && typeof pos.column === "number") + if (typeof pos.line === "number" && typeof pos.column === "number") { return `${pos.line}:${pos.column}`; - else if (typeof pos.line === "number") return `${pos.line}:?`; - else if (typeof pos.index === "number") return `+${pos.index}`; - else return ""; + } else if (typeof pos.line === "number") { + return `${pos.line}:?`; + } else if (typeof pos.index === "number") { + return `+${pos.index}`; + } else { + return ""; + } default: return ""; } @@ -39,11 +43,15 @@ const formatLocation = loc => { typeof loc.end.line === "number" && typeof loc.end.column === "number" && loc.start.line === loc.end.line - ) + ) { return `${formatPosition(loc.start)}-${loc.end.column}`; - return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`; + } else { + return `${formatPosition(loc.start)}-${formatPosition(loc.end)}`; + } + } + if (loc.start) { + return formatPosition(loc.start); } - if (loc.start) return formatPosition(loc.start); return formatPosition(loc); default: return ""; diff --git a/lib/node/NodeMainTemplateAsync.runtime.js b/lib/node/NodeMainTemplateAsync.runtime.js index 926d936c66a..bcdd57dabc6 100644 --- a/lib/node/NodeMainTemplateAsync.runtime.js +++ b/lib/node/NodeMainTemplateAsync.runtime.js @@ -10,7 +10,7 @@ module.exports = function() { require("fs").readFile(filename, "utf-8", function(err, content) { if (err) { if ($require$.onError) return $require$.oe(err); - else throw err; + throw err; } var chunk = {}; require("vm").runInThisContext( diff --git a/lib/node/NodeMainTemplatePlugin.js b/lib/node/NodeMainTemplatePlugin.js index 54ede089ec6..c32ae38da56 100644 --- a/lib/node/NodeMainTemplatePlugin.js +++ b/lib/node/NodeMainTemplatePlugin.js @@ -116,10 +116,11 @@ module.exports = class NodeMainTemplatePlugin { hashWithLength: length => { const shortChunkHashMap = {}; for (const chunkId of Object.keys(chunkMaps.hash)) { - if (typeof chunkMaps.hash[chunkId] === "string") + if (typeof chunkMaps.hash[chunkId] === "string") { shortChunkHashMap[chunkId] = chunkMaps.hash[ chunkId ].substr(0, length); + } } return `" + ${JSON.stringify( shortChunkHashMap @@ -201,10 +202,11 @@ module.exports = class NodeMainTemplatePlugin { hashWithLength: length => { const shortChunkHashMap = {}; for (const chunkId of Object.keys(chunkMaps.hash)) { - if (typeof chunkMaps.hash[chunkId] === "string") + if (typeof chunkMaps.hash[chunkId] === "string") { shortChunkHashMap[chunkId] = chunkMaps.hash[ chunkId ].substr(0, length); + } } return `" + ${JSON.stringify( shortChunkHashMap @@ -278,11 +280,12 @@ module.exports = class NodeMainTemplatePlugin { hashWithLength: length => { const shortChunkHashMap = {}; for (const chunkId of Object.keys(chunkMaps.hash)) { - if (typeof chunkMaps.hash[chunkId] === "string") + if (typeof chunkMaps.hash[chunkId] === "string") { shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr( 0, length ); + } } return `" + ${JSON.stringify(shortChunkHashMap)}[chunkId] + "`; }, diff --git a/lib/node/NodeSourcePlugin.js b/lib/node/NodeSourcePlugin.js index 3a49e637793..31825bb5c87 100644 --- a/lib/node/NodeSourcePlugin.js +++ b/lib/node/NodeSourcePlugin.js @@ -13,22 +13,26 @@ module.exports = class NodeSourcePlugin { } apply(compiler) { const options = this.options; - if (options === false) + if (options === false) { // allow single kill switch to turn off this plugin return; + } const getPathToModule = (module, type) => { if (type === true || (type === undefined && nodeLibsBrowser[module])) { - if (!nodeLibsBrowser[module]) + if (!nodeLibsBrowser[module]) { throw new Error( `No browser version for node.js core module ${module} available` ); + } return nodeLibsBrowser[module]; } else if (type === "mock") { return require.resolve(`node-libs-browser/mock/${module}`); } else if (type === "empty") { return require.resolve("node-libs-browser/mock/empty"); - } else return module; + } else { + return module; + } }; const addExpression = (parser, name, module, type, suffix) => { @@ -58,9 +62,9 @@ module.exports = class NodeSourcePlugin { if (parserOptions.node === false) return; let localOptions = options; - if (parserOptions.node) + if (parserOptions.node) { localOptions = Object.assign({}, localOptions, parserOptions.node); - + } if (localOptions.global) { parser.hooks.expression .for("global") diff --git a/lib/node/NodeWatchFileSystem.js b/lib/node/NodeWatchFileSystem.js index 45c3c34e509..62d8532cdfa 100644 --- a/lib/node/NodeWatchFileSystem.js +++ b/lib/node/NodeWatchFileSystem.js @@ -17,22 +17,33 @@ class NodeWatchFileSystem { } watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { - if (!Array.isArray(files)) throw new Error("Invalid arguments: 'files'"); - if (!Array.isArray(dirs)) throw new Error("Invalid arguments: 'dirs'"); - if (!Array.isArray(missing)) + if (!Array.isArray(files)) { + throw new Error("Invalid arguments: 'files'"); + } + if (!Array.isArray(dirs)) { + throw new Error("Invalid arguments: 'dirs'"); + } + if (!Array.isArray(missing)) { throw new Error("Invalid arguments: 'missing'"); - if (typeof callback !== "function") + } + if (typeof callback !== "function") { throw new Error("Invalid arguments: 'callback'"); - if (typeof startTime !== "number" && startTime) + } + if (typeof startTime !== "number" && startTime) { throw new Error("Invalid arguments: 'startTime'"); - if (typeof options !== "object") + } + if (typeof options !== "object") { throw new Error("Invalid arguments: 'options'"); - if (typeof callbackUndelayed !== "function" && callbackUndelayed) + } + if (typeof callbackUndelayed !== "function" && callbackUndelayed) { throw new Error("Invalid arguments: 'callbackUndelayed'"); + } const oldWatcher = this.watcher; this.watcher = new Watchpack(options); - if (callbackUndelayed) this.watcher.once("change", callbackUndelayed); + if (callbackUndelayed) { + this.watcher.once("change", callbackUndelayed); + } this.watcher.once("aggregated", (changes, removals) => { changes = changes.concat(removals); @@ -68,12 +79,18 @@ class NodeWatchFileSystem { } }, getFileTimestamps: () => { - if (this.watcher) return objectToMap(this.watcher.getTimes()); - else return new Map(); + if (this.watcher) { + return objectToMap(this.watcher.getTimes()); + } else { + return new Map(); + } }, getContextTimestamps: () => { - if (this.watcher) return objectToMap(this.watcher.getTimes()); - else return new Map(); + if (this.watcher) { + return objectToMap(this.watcher.getTimes()); + } else { + return new Map(); + } } }; } diff --git a/lib/optimize/AggressiveSplittingPlugin.js b/lib/optimize/AggressiveSplittingPlugin.js index b68357e9a44..9aec3644bfd 100644 --- a/lib/optimize/AggressiveSplittingPlugin.js +++ b/lib/optimize/AggressiveSplittingPlugin.js @@ -26,14 +26,18 @@ class AggressiveSplittingPlugin { validateOptions(schema, options || {}, "Aggressive Splitting Plugin"); this.options = options || {}; - if (typeof this.options.minSize !== "number") + if (typeof this.options.minSize !== "number") { this.options.minSize = 30 * 1024; - if (typeof this.options.maxSize !== "number") + } + if (typeof this.options.maxSize !== "number") { this.options.maxSize = 50 * 1024; - if (typeof this.options.chunkOverhead !== "number") + } + if (typeof this.options.chunkOverhead !== "number") { this.options.chunkOverhead = 0; - if (typeof this.options.entryChunkMultiplicator !== "number") + } + if (typeof this.options.entryChunkMultiplicator !== "number") { this.options.entryChunkMultiplicator = 1; + } } apply(compiler) { compiler.hooks.thisCompilation.tap( @@ -82,8 +86,9 @@ class AggressiveSplittingPlugin { const applySplit = splitData => { // Cannot split if id is already taken - if (splitData.id !== undefined && usedIds.has(splitData.id)) + if (splitData.id !== undefined && usedIds.has(splitData.id)) { return false; + } // Get module objects from names const selectedModules = splitData.modules.map(name => @@ -188,8 +193,9 @@ class AggressiveSplittingPlugin { for (let k = 0; k < modules.length; k++) { const module = modules[k]; const newSize = selectedModulesSize + module.size(); - if (newSize > maxSize && selectedModulesSize >= minSize) + if (newSize > maxSize && selectedModulesSize >= minSize) { break; + } selectedModulesSize = newSize; selectedModules.push(module); } diff --git a/lib/optimize/ConcatenatedModule.js b/lib/optimize/ConcatenatedModule.js index 4c7ced9cc7c..0ff507d30f5 100644 --- a/lib/optimize/ConcatenatedModule.js +++ b/lib/optimize/ConcatenatedModule.js @@ -114,20 +114,22 @@ const getFinalName = ( case "concatenated": { const directExport = info.exportMap.get(exportName); if (directExport) { - if (exportName === true) + if (exportName === true) { ensureNsObjSource( info, moduleToInfoMap, requestShortener, strictHarmonyModule ); + } const name = info.internalNames.get(directExport); - if (!name) + if (!name) { throw new Error( `The export "${directExport}" in "${info.module.readableIdentifier( requestShortener )}" has no internal name` ); + } return name; } const reexport = info.reexportMap.get(exportName); @@ -325,13 +327,18 @@ class ConcatenatedModule extends Module { } } // populate warnings - for (const warning of m.warnings) this.warnings.push(warning); + for (const warning of m.warnings) { + this.warnings.push(warning); + } // populate errors - for (const error of m.errors) this.errors.push(error); + for (const error of m.errors) { + this.errors.push(error); + } if (m.buildInfo.assets) { - if (this.buildInfo.assets === undefined) + if (this.buildInfo.assets === undefined) { this.buildInfo.assets = Object.create(null); + } Object.assign(this.buildInfo.assets, m.buildInfo.assets); } } @@ -450,10 +457,13 @@ class ConcatenatedModule extends Module { const reexportMap = new Map(); for (const dep of info.module.dependencies) { if (dep instanceof HarmonyExportSpecifierDependency) { - if (!exportMap.has(dep.name)) exportMap.set(dep.name, dep.id); + if (!exportMap.has(dep.name)) { + exportMap.set(dep.name, dep.id); + } } else if (dep instanceof HarmonyExportExpressionDependency) { - if (!exportMap.has("default")) + if (!exportMap.has("default")) { exportMap.set("default", "__WEBPACK_MODULE_DEFAULT_EXPORT__"); + } } else if ( dep instanceof HarmonyExportImportedSpecifierDependency ) { @@ -478,8 +488,9 @@ class ConcatenatedModule extends Module { } } else if (importedModule) { for (const name of importedModule.buildMeta.providedExports) { - if (dep.activeExports.has(name) || name === "default") + if (dep.activeExports.has(name) || name === "default") { continue; + } if (!reexportMap.has(name)) { reexportMap.set(name, { module: importedModule, diff --git a/lib/optimize/MergeDuplicateChunksPlugin.js b/lib/optimize/MergeDuplicateChunksPlugin.js index cc888923c4a..1c3e23aa3e9 100644 --- a/lib/optimize/MergeDuplicateChunksPlugin.js +++ b/lib/optimize/MergeDuplicateChunksPlugin.js @@ -31,8 +31,9 @@ class MergeDuplicateChunksPlugin { !notDuplicates.has(dup) ) { // delay allocating the new Set until here, reduce memory pressure - if (possibleDuplicates === undefined) + if (possibleDuplicates === undefined) { possibleDuplicates = new Set(); + } possibleDuplicates.add(dup); } } @@ -42,8 +43,9 @@ class MergeDuplicateChunksPlugin { // validate existing possible duplicates for (const dup of possibleDuplicates) { // remove possible duplicate when module is not contained - if (!dup.containsModule(module)) + if (!dup.containsModule(module)) { possibleDuplicates.delete(dup); + } } // when all chunks has been removed we can break here if (possibleDuplicates.size === 0) break; @@ -58,8 +60,9 @@ class MergeDuplicateChunksPlugin { for (const otherChunk of possibleDuplicates) { if (otherChunk.hasRuntime() !== chunk.hasRuntime()) continue; // merge them - if (chunk.integrate(otherChunk, "duplicate")) + if (chunk.integrate(otherChunk, "duplicate")) { chunks.splice(chunks.indexOf(otherChunk), 1); + } } } diff --git a/lib/optimize/ModuleConcatenationPlugin.js b/lib/optimize/ModuleConcatenationPlugin.js index 03d31195b90..498d101bc41 100644 --- a/lib/optimize/ModuleConcatenationPlugin.js +++ b/lib/optimize/ModuleConcatenationPlugin.js @@ -172,19 +172,21 @@ class ModuleConcatenationPlugin { ) .sort(); const explanations = Array.from(importingExplanations).sort(); - if (names.length > 0 && explanations.length === 0) + if (names.length > 0 && explanations.length === 0) { return `Module is referenced from these modules with unsupported syntax: ${names.join( ", " )}`; - else if (names.length === 0 && explanations.length > 0) + } else if (names.length === 0 && explanations.length > 0) { return `Module is referenced by: ${explanations.join( ", " )}`; - else if (names.length > 0 && explanations.length > 0) + } else if (names.length > 0 && explanations.length > 0) { return `Module is referenced from these modules with unsupported syntax: ${names.join( ", " )} and by: ${explanations.join(", ")}`; - else return "Module is referenced in a unsupported way"; + } else { + return "Module is referenced in a unsupported way"; + } }); continue; } @@ -226,8 +228,9 @@ class ModuleConcatenationPlugin { if (!currentConfiguration.isEmpty()) { concatConfigurations.push(currentConfiguration); for (const module of currentConfiguration.getModules()) { - if (module !== currentConfiguration.rootModule) + if (module !== currentConfiguration.rootModule) { usedAsInner.add(module); + } } } } @@ -250,13 +253,13 @@ class ModuleConcatenationPlugin { newModule.optimizationBailout.push(requestShortener => { const reason = getBailoutReason(warning[0], requestShortener); const reasonWithPrefix = reason ? ` (<- ${reason})` : ""; - if (warning[0] === warning[1]) + if (warning[0] === warning[1]) { return formatBailoutReason( `Cannot concat with ${warning[0].readableIdentifier( requestShortener )}${reasonWithPrefix}` ); - else + } else { return formatBailoutReason( `Cannot concat with ${warning[0].readableIdentifier( requestShortener @@ -264,6 +267,7 @@ class ModuleConcatenationPlugin { requestShortener )}${reasonWithPrefix}` ); + } }); } const chunks = concatConfiguration.rootModule.getChunks(); @@ -276,8 +280,9 @@ class ModuleConcatenationPlugin { for (const chunk of chunks) { chunk.addModule(newModule); newModule.addChunk(chunk); - if (chunk.entryModule === concatConfiguration.rootModule) + if (chunk.entryModule === concatConfiguration.rootModule) { chunk.entryModule = newModule; + } } compilation.modules.push(newModule); for (const reason of newModule.reasons) { @@ -293,7 +298,9 @@ class ModuleConcatenationPlugin { let reasons = dep.module.reasons; for (let j = 0; j < reasons.length; j++) { let reason = reasons[j]; - if (reason.dependency === dep) reason.module = newModule; + if (reason.dependency === dep) { + reason.module = newModule; + } } } } diff --git a/lib/optimize/OccurrenceOrderPlugin.js b/lib/optimize/OccurrenceOrderPlugin.js index 613e403b6d7..8e23f951473 100644 --- a/lib/optimize/OccurrenceOrderPlugin.js +++ b/lib/optimize/OccurrenceOrderPlugin.js @@ -36,15 +36,22 @@ class OccurrenceOrderPlugin { } const countOccursInEntry = (sum, r) => { - if (!r.module) return sum; + if (!r.module) { + return sum; + } return sum + initialChunkChunkMap.get(r.module); }; const countOccurs = (sum, r) => { - if (!r.module) return sum; + if (!r.module) { + return sum; + } let factor = 1; - if (typeof r.dependency.getNumberOfIdOccurrences === "function") + if (typeof r.dependency.getNumberOfIdOccurrences === "function") { factor = r.dependency.getNumberOfIdOccurrences(); - if (factor === 0) return sum; + } + if (factor === 0) { + return sum; + } return sum + factor * r.module.getNumberOfChunks(); }; diff --git a/lib/optimize/RemoveParentModulesPlugin.js b/lib/optimize/RemoveParentModulesPlugin.js index e901273c536..7fff59207b8 100644 --- a/lib/optimize/RemoveParentModulesPlugin.js +++ b/lib/optimize/RemoveParentModulesPlugin.js @@ -34,7 +34,9 @@ class RemoveParentModulesPlugin { for (const chunkGroup of compilation.entrypoints.values()) { // initialize available modules for chunks without parents availableModulesMap.set(chunkGroup, new Set()); - for (const child of chunkGroup.childrenIterable) queue.enqueue(child); + for (const child of chunkGroup.childrenIterable) { + queue.enqueue(child); + } } while (queue.length > 0) { @@ -49,8 +51,9 @@ class RemoveParentModulesPlugin { // if we have not own info yet: create new entry availableModules = new Set(availableModulesInParent); for (const chunk of parent.chunks) { - for (const m of chunk.modulesIterable) + for (const m of chunk.modulesIterable) { availableModules.add(m); + } } availableModulesMap.set(chunkGroup, availableModules); changed = true; @@ -69,8 +72,9 @@ class RemoveParentModulesPlugin { } if (changed) { // if something changed: enqueue our children - for (const child of chunkGroup.childrenIterable) + for (const child of chunkGroup.childrenIterable) { queue.enqueue(child); + } } } @@ -88,11 +92,17 @@ class RemoveParentModulesPlugin { const numberOfModules = chunk.getNumberOfModules(); const toRemove = new Set(); if (numberOfModules < availableModules.size) { - for (const m of chunk.modulesIterable) - if (availableModules.has(m)) toRemove.add(m); + for (const m of chunk.modulesIterable) { + if (availableModules.has(m)) { + toRemove.add(m); + } + } } else { - for (const m of availableModules) - if (chunk.containsModule(m)) toRemove.add(m); + for (const m of availableModules) { + if (chunk.containsModule(m)) { + toRemove.add(m); + } + } } for (const module of toRemove) { module.rewriteChunkInReasons( diff --git a/lib/optimize/SideEffectsFlagPlugin.js b/lib/optimize/SideEffectsFlagPlugin.js index d176026bc68..7bf30b0ba21 100644 --- a/lib/optimize/SideEffectsFlagPlugin.js +++ b/lib/optimize/SideEffectsFlagPlugin.js @@ -41,10 +41,11 @@ class SideEffectsFlagPlugin { return module; }); nmf.hooks.module.tap("SideEffectsFlagPlugin", (module, data) => { - if (data.settings.sideEffects === false) + if (data.settings.sideEffects === false) { module.factoryMeta.sideEffectFree = true; - else if (data.settings.sideEffects === true) + } else if (data.settings.sideEffects === true) { module.factoryMeta.sideEffectFree = false; + } }); }); compiler.hooks.compilation.tap("SideEffectsFlagPlugin", compilation => { diff --git a/lib/optimize/SplitChunksPlugin.js b/lib/optimize/SplitChunksPlugin.js index 84f1d31b63a..e2487e3e1ce 100644 --- a/lib/optimize/SplitChunksPlugin.js +++ b/lib/optimize/SplitChunksPlugin.js @@ -36,7 +36,9 @@ const getRequests = chunk => { const getModulesSize = modules => { let sum = 0; - for (const m of modules) sum += m.size(); + for (const m of modules) { + sum += m.size(); + } return sum; }; @@ -172,8 +174,9 @@ module.exports = class SplitChunksPlugin { static normalizeCacheGroups({ cacheGroups, automaticNameDelimiter }) { if (typeof cacheGroups === "function") { // TODO webpack 5 remove this - if (cacheGroups.length !== 1) + if (cacheGroups.length !== 1) { return module => cacheGroups(module, module.getChunks()); + } return cacheGroups; } if (cacheGroups && typeof cacheGroups === "object") { @@ -192,12 +195,7 @@ module.exports = class SplitChunksPlugin { if (result) { if (results === undefined) results = []; for (const r of Array.isArray(result) ? result : [result]) { - const result = Object.assign( - { - key - }, - r - ); + const result = Object.assign({ key }, r); if (result.name) result.getName = () => result.name; if (result.chunks) { result.chunksFilter = SplitChunksPlugin.normalizeChunksFilter( @@ -240,23 +238,34 @@ module.exports = class SplitChunksPlugin { static checkTest(test, module) { if (test === undefined) return true; if (typeof test === "function") { - if (test.length !== 1) return test(module, module.getChunks()); + if (test.length !== 1) { + return test(module, module.getChunks()); + } return test(module); } if (typeof test === "boolean") return test; if (typeof test === "string") { - if (module.nameForCondition && module.nameForCondition().startsWith(test)) + if ( + module.nameForCondition && + module.nameForCondition().startsWith(test) + ) { return true; + } for (const chunk of module.chunksIterable) { - if (chunk.name && chunk.name.startsWith(test)) return true; + if (chunk.name && chunk.name.startsWith(test)) { + return true; + } } return false; } if (test instanceof RegExp) { - if (module.nameForCondition && test.test(module.nameForCondition())) + if (module.nameForCondition && test.test(module.nameForCondition())) { return true; + } for (const chunk of module.chunksIterable) { - if (chunk.name && test.test(chunk.name)) return true; + if (chunk.name && test.test(chunk.name)) { + return true; + } } return false; } @@ -447,8 +456,9 @@ module.exports = class SplitChunksPlugin { for (const module of compilation.modules) { // Get cache group let cacheGroups = this.options.getCacheGroups(module); - if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) + if (!Array.isArray(cacheGroups) || cacheGroups.length === 0) { continue; + } // Prepare some values const chunksKey = getKey(module.chunksIterable); @@ -555,18 +565,20 @@ module.exports = class SplitChunksPlugin { if (pair[1] === item.modules.size) { const chunk = pair[0]; if (chunk.hasEntryModule()) continue; - if (!newChunk || !newChunk.name) newChunk = chunk; - else if ( + if (!newChunk || !newChunk.name) { + newChunk = chunk; + } else if ( chunk.name && chunk.name.length < newChunk.name.length - ) + ) { newChunk = chunk; - else if ( + } else if ( chunk.name && chunk.name.length === newChunk.name.length && chunk.name < newChunk.name - ) + ) { newChunk = chunk; + } chunkName = undefined; isReused = true; } @@ -683,8 +695,9 @@ module.exports = class SplitChunksPlugin { } if (info.modules.size !== oldSize) { info.size = getModulesSize(info.modules); - if (info.size < info.cacheGroup.minSize) + if (info.size < info.cacheGroup.minSize) { chunksInfoMap.delete(key); + } } } } diff --git a/lib/util/SortableSet.js b/lib/util/SortableSet.js index 83c164d1cd3..6bc49a60db6 100644 --- a/lib/util/SortableSet.js +++ b/lib/util/SortableSet.js @@ -94,12 +94,15 @@ class SortableSet extends Set { } _invalidateCache() { - if (this._cache !== undefined) this._cache.clear(); + if (this._cache !== undefined) { + this._cache.clear(); + } } _invalidateOrderedCache() { - if (this._cacheOrderIndependent !== undefined) + if (this._cacheOrderIndependent !== undefined) { this._cacheOrderIndependent.clear(); + } } } diff --git a/lib/util/StackedSetMap.js b/lib/util/StackedSetMap.js index 0d1149ce751..589b68d52b8 100644 --- a/lib/util/StackedSetMap.js +++ b/lib/util/StackedSetMap.js @@ -25,8 +25,11 @@ class StackedSetMap { } delete(item) { - if (this.stack.length > 1) this.map.set(item, TOMBSTONE); - else this.map.delete(item); + if (this.stack.length > 1) { + this.map.set(item, TOMBSTONE); + } else { + this.map.delete(item); + } } has(item) { @@ -47,10 +50,11 @@ class StackedSetMap { get(item) { const topValue = this.map.get(item); - if (topValue !== undefined) + if (topValue !== undefined) { return topValue === TOMBSTONE || topValue === UNDEFINED_MARKER ? undefined : topValue; + } if (this.stack.length > 1) { for (var i = this.stack.length - 2; i >= 0; i--) { const value = this.stack[i].get(item); @@ -71,8 +75,11 @@ class StackedSetMap { this.map = new Map(); for (const data of this.stack) { for (const pair of data) { - if (pair[1] === TOMBSTONE) this.map.delete(pair[0]); - else this.map.set(pair[0], pair[1]); + if (pair[1] === TOMBSTONE) { + this.map.delete(pair[0]); + } else { + this.map.set(pair[0], pair[1]); + } } } this.stack = [this.map]; diff --git a/lib/wasm/WasmMainTemplatePlugin.js b/lib/wasm/WasmMainTemplatePlugin.js index 236ff43015c..0e60f8d7327 100644 --- a/lib/wasm/WasmMainTemplatePlugin.js +++ b/lib/wasm/WasmMainTemplatePlugin.js @@ -179,10 +179,11 @@ class WasmMainTemplatePlugin { hashWithLength(length) { const shortChunkHashMap = Object.create(null); for (const wasmModuleId of Object.keys(chunkModuleMaps.hash)) { - if (typeof chunkModuleMaps.hash[wasmModuleId] === "string") + if (typeof chunkModuleMaps.hash[wasmModuleId] === "string") { shortChunkHashMap[wasmModuleId] = chunkModuleMaps.hash[ wasmModuleId ].substr(0, length); + } } return `" + ${JSON.stringify( shortChunkHashMap @@ -274,8 +275,9 @@ class WasmMainTemplatePlugin { mainTemplate.hooks.requireExtensions.tap( "WasmMainTemplatePlugin", (source, chunk) => { - if (!chunk.hasModuleInGraph(m => m.type.startsWith("webassembly"))) + if (!chunk.hasModuleInGraph(m => m.type.startsWith("webassembly"))) { return source; + } return Template.asString([ source, "", diff --git a/lib/web/JsonpMainTemplate.runtime.js b/lib/web/JsonpMainTemplate.runtime.js index 359cfeadf34..d8b642b0861 100644 --- a/lib/web/JsonpMainTemplate.runtime.js +++ b/lib/web/JsonpMainTemplate.runtime.js @@ -24,8 +24,9 @@ module.exports = function() { function hotDownloadManifest(requestTimeout) { requestTimeout = requestTimeout || 10000; return new Promise(function(resolve, reject) { - if (typeof XMLHttpRequest === "undefined") + if (typeof XMLHttpRequest === "undefined") { return reject(new Error("No browser support")); + } try { var request = new XMLHttpRequest(); var requestPath = $require$.p + $hotMainFilename$; diff --git a/lib/web/JsonpMainTemplatePlugin.js b/lib/web/JsonpMainTemplatePlugin.js index 2a842025b2a..5da455269f8 100644 --- a/lib/web/JsonpMainTemplatePlugin.js +++ b/lib/web/JsonpMainTemplatePlugin.js @@ -66,11 +66,12 @@ class JsonpMainTemplatePlugin { hashWithLength(length) { const shortChunkHashMap = Object.create(null); for (const chunkId of Object.keys(chunkMaps.hash)) { - if (typeof chunkMaps.hash[chunkId] === "string") + if (typeof chunkMaps.hash[chunkId] === "string") { shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr( 0, length ); + } } return `" + ${JSON.stringify( shortChunkHashMap diff --git a/lib/webpack.js b/lib/webpack.js index 65c0de44ed8..facfebf6c08 100644 --- a/lib/webpack.js +++ b/lib/webpack.js @@ -44,8 +44,9 @@ const webpack = (options, callback) => { throw new Error("Invalid argument: options"); } if (callback) { - if (typeof callback !== "function") + if (typeof callback !== "function") { throw new Error("Invalid argument: callback"); + } if ( options.watch === true || (Array.isArray(options) && options.some(o => o.watch)) diff --git a/lib/webworker/WebWorkerMainTemplate.runtime.js b/lib/webworker/WebWorkerMainTemplate.runtime.js index 9eab2f1bc00..8c63f7729e3 100644 --- a/lib/webworker/WebWorkerMainTemplate.runtime.js +++ b/lib/webworker/WebWorkerMainTemplate.runtime.js @@ -19,8 +19,9 @@ module.exports = function() { function hotDownloadManifest(requestTimeout) { requestTimeout = requestTimeout || 10000; return new Promise(function(resolve, reject) { - if (typeof XMLHttpRequest === "undefined") + if (typeof XMLHttpRequest === "undefined") { return reject(new Error("No browser support")); + } try { var request = new XMLHttpRequest(); var requestPath = $require$.p + $hotMainFilename$;