Add brackets for multiline if/for statements

This commit is contained in:
Florent Cailhol 2018-05-29 14:50:40 +02:00
parent b80296f0c8
commit 2a9452e51b
84 changed files with 1208 additions and 549 deletions

View File

@ -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;
});

View File

@ -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")

View File

@ -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;
}

View File

@ -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(

View File

@ -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;
}

View File

@ -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
}`
);
}
}
}
}

View File

@ -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) {

View File

@ -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);

View File

@ -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;
}
}

View File

@ -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)
);

View File

@ -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);

View File

@ -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);

View File

@ -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 {

View File

@ -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) {

View File

@ -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;

View File

@ -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 => {

View File

@ -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);
}
};

View File

@ -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");
};

View File

@ -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

View File

@ -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

View File

@ -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;

View File

@ -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) {

View File

@ -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 = [];

View File

@ -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);
}

View File

@ -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: () =>

View File

@ -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;
}

View File

@ -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);

View File

@ -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;
}

View File

@ -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, ";");
}

View File

@ -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;
}

View File

@ -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;
};

View File

@ -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();
}
}
}
};

View File

@ -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 {

View File

@ -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

View File

@ -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;
}

View File

@ -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];

View File

@ -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;

View File

@ -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 {

View File

@ -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;
};
};

View File

@ -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) {

View File

@ -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);
}
}
);
});

View File

@ -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);

View File

@ -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;
}
};

View File

@ -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 {

View File

@ -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");

View File

@ -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);

View File

@ -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 (

View File

@ -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));
}
}
);
});

View File

@ -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) {} }())`;
}

View File

@ -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));
}
}
});
}

View File

@ -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();

View File

@ -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 => {

View File

@ -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 (

View File

@ -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

View File

@ -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);
}

View File

@ -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;
}

View File

@ -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"];

View File

@ -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 +

View File

@ -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) => {

View File

@ -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]);

View File

@ -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) {

View File

@ -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;
};

View File

@ -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;

View File

@ -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);
}

View File

@ -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 "";

View File

@ -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(

View File

@ -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] + "`;
},

View File

@ -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")

View File

@ -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();
}
}
};
}

View File

@ -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);
}

View File

@ -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,

View File

@ -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);
}
}
}

View File

@ -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;
}
}
}
}

View File

@ -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();
};

View File

@ -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(

View File

@ -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 => {

View File

@ -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);
}
}
}
}

View File

@ -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();
}
}
}

View File

@ -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];

View File

@ -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,
"",

View File

@ -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$;

View File

@ -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

View File

@ -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))

View File

@ -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$;