From 0a340f2b1a3b0dff3375836ccc81ed96abeb075f Mon Sep 17 00:00:00 2001 From: Avi Haiat Date: Mon, 13 Jul 2015 01:20:09 +0300 Subject: [PATCH] feat(app): Beautify all lib files --- lib/APIPlugin.js | 1 - lib/AbstractPlugin.js | 2 +- lib/AmdMainTemplatePlugin.js | 4 +- lib/ArrayMap.js | 14 +- lib/AutomaticPrefetchPlugin.js | 5 +- lib/BannerPlugin.js | 4 +- lib/BasicEvaluatedExpression.js | 49 +- lib/CachePlugin.js | 8 +- lib/Chunk.js | 53 +- lib/ChunkTemplate.js | 6 +- lib/CompatibilityPlugin.js | 13 +- lib/Compilation.js | 210 +++---- lib/Compiler.js | 107 ++-- lib/ConstPlugin.js | 14 +- lib/ContextModule.js | 30 +- lib/ContextModuleFactory.js | 38 +- lib/ContextReplacementPlugin.js | 30 +- lib/CriticalDependenciesWarning.js | 4 +- lib/DefinePlugin.js | 31 +- lib/DelegatedModule.js | 6 +- lib/DelegatedModuleFactoryPlugin.js | 12 +- lib/DependenciesBlock.js | 4 +- lib/DependenciesBlockVariable.js | 2 +- lib/Dependency.js | 30 +- lib/DllPlugin.js | 4 +- lib/EntryOptionPlugin.js | 6 +- lib/EvalDevToolModulePlugin.js | 1 - lib/EvalDevToolModuleTemplatePlugin.js | 2 +- ...valSourceMapDevToolModuleTemplatePlugin.js | 12 +- lib/EvalSourceMapDevToolPlugin.js | 2 +- lib/ExtendedAPIPlugin.js | 3 +- lib/ExternalModule.js | 14 +- lib/ExternalModuleFactoryPlugin.js | 41 +- lib/FunctionModuleTemplatePlugin.js | 7 +- lib/HotModuleReplacement.runtime.js | 196 ++++--- lib/HotModuleReplacementPlugin.js | 47 +- lib/HotUpdateChunkTemplate.js | 5 +- lib/IgnorePlugin.js | 8 +- lib/JsonpChunkTemplatePlugin.js | 3 +- lib/JsonpHotUpdateChunkTemplatePlugin.js | 3 +- lib/JsonpMainTemplate.runtime.js | 16 +- lib/JsonpMainTemplatePlugin.js | 46 +- lib/JsonpTemplatePlugin.js | 1 - lib/LibManifestPlugin.js | 8 +- lib/LibraryTemplatePlugin.js | 82 +-- lib/MainTemplate.js | 20 +- lib/Module.js | 23 +- lib/ModuleFilenameHelpers.js | 36 +- lib/ModuleParseError.js | 4 +- lib/ModuleParserHelpers.js | 2 +- lib/MultiCompiler.js | 32 +- lib/MultiModule.js | 6 +- lib/NamedModulesPlugin.js | 2 +- lib/NewWatchingPlugin.js | 3 +- lib/NoErrorsPlugin.js | 7 +- lib/NodeStuffPlugin.js | 21 +- lib/NormalModule.js | 92 +-- lib/NormalModuleFactory.js | 39 +- lib/NormalModuleReplacementPlugin.js | 9 +- lib/NullFactory.js | 3 +- lib/OldWatchingPlugin.js | 3 +- lib/OptionsApply.js | 5 +- lib/Parser.js | 553 +++++++++--------- lib/PrefetchPlugin.js | 2 +- lib/ProgressPlugin.js | 5 +- lib/ProvidePlugin.js | 12 +- lib/RawModule.js | 2 +- lib/RecordIdsPlugin.js | 57 +- lib/RequestShortener.js | 20 +- lib/RequireJsStuffPlugin.js | 4 +- lib/ResolverPlugin.js | 6 +- lib/SetVarMainTemplatePlugin.js | 5 +- lib/Source.js | 1 - lib/SourceMapDevToolModuleOptionsPlugin.js | 10 +- lib/SourceMapDevToolPlugin.js | 30 +- lib/SourceMapSource.js | 1 - lib/Stats.js | 282 +++++---- lib/Template.js | 46 +- lib/TemplatedPathPlugin.js | 21 +- lib/UmdMainTemplatePlugin.js | 60 +- lib/WarnCaseSensitiveModulesPlugin.js | 5 +- lib/WatchIgnorePlugin.js | 3 +- lib/WebpackOptionsApply.js | 205 +++---- lib/WebpackOptionsDefaulter.js | 73 +-- lib/dependencies/AMDDefineDependency.js | 15 +- .../AMDDefineDependencyParserPlugin.js | 190 +++--- lib/dependencies/AMDPlugin.js | 1 + lib/dependencies/AMDRequireArrayDependency.js | 6 +- .../AMDRequireDependenciesBlock.js | 1 - ...AMDRequireDependenciesBlockParserPlugin.js | 97 ++- lib/dependencies/AMDRequireDependency.js | 14 +- .../CommonJsRequireDependencyParserPlugin.js | 17 +- lib/dependencies/ConstDependency.js | 2 +- lib/dependencies/ContextDependency.js | 2 +- lib/dependencies/ContextDependencyHelpers.js | 4 +- .../ContextDependencyTemplateAsId.js | 6 +- .../ContextDependencyTemplateAsRequireCall.js | 8 +- lib/dependencies/DepBlockHelpers.js | 8 +- lib/dependencies/LabeledModuleDependency.js | 9 +- .../LabeledModuleDependencyParserPlugin.js | 95 ++- lib/dependencies/LabeledModulesPlugin.js | 3 +- lib/dependencies/LoaderPlugin.js | 25 +- lib/dependencies/LocalModuleDependency.js | 2 +- lib/dependencies/LocalModulesHelpers.js | 15 +- lib/dependencies/ModuleDependency.js | 2 +- .../ModuleDependencyTemplateAsId.js | 8 +- .../ModuleDependencyTemplateAsRequireId.js | 8 +- .../RequireContextDependencyParserPlugin.js | 39 +- lib/dependencies/RequireContextPlugin.js | 8 +- .../RequireEnsureDependenciesBlock.js | 1 - ...uireEnsureDependenciesBlockParserPlugin.js | 94 +-- lib/dependencies/RequireEnsureDependency.js | 5 +- lib/dependencies/RequireEnsurePlugin.js | 3 +- lib/dependencies/RequireHeaderDependency.js | 2 +- lib/dependencies/RequireIncludeDependency.js | 4 +- .../RequireIncludeDependencyParserPlugin.js | 5 +- lib/dependencies/RequireIncludePlugin.js | 3 +- .../RequireResolveDependencyParserPlugin.js | 13 +- .../RequireResolveHeaderDependency.js | 2 +- .../TemplateArgumentDependency.js | 4 +- lib/dependencies/getFunctionExpression.js | 6 +- lib/node/NodeChunkTemplatePlugin.js | 3 +- lib/node/NodeEnvironmentPlugin.js | 5 +- lib/node/NodeHotUpdateChunkTemplatePlugin.js | 3 +- lib/node/NodeMainTemplate.runtime.js | 2 +- lib/node/NodeMainTemplateAsync.runtime.js | 8 +- lib/node/NodeMainTemplatePlugin.js | 10 +- lib/node/NodeSourcePlugin.js | 26 +- lib/node/NodeTargetPlugin.js | 3 +- lib/node/NodeWatchFileSystem.js | 20 +- lib/node/OldNodeWatchFileSystem.js | 74 +-- lib/optimize/AggressiveMergingPlugin.js | 47 +- lib/optimize/CommonsChunkPlugin.js | 57 +- lib/optimize/DedupePlugin.js | 48 +- lib/optimize/FlagIncludedChunksPlugin.js | 12 +- lib/optimize/LimitChunkCountPlugin.js | 17 +- lib/optimize/MergeDuplicateChunksPlugin.js | 10 +- lib/optimize/MinChunkSizePlugin.js | 9 +- lib/optimize/OccurenceOrderPlugin.js | 1 - lib/optimize/OccurrenceOrderPlugin.js | 53 +- lib/optimize/RemoveEmptyChunksPlugin.js | 4 +- lib/optimize/RemoveParentModulesPlugin.js | 20 +- lib/optimize/UglifyJsPlugin.js | 32 +- lib/removeAndDo.js | 2 +- lib/webpack.js | 12 +- lib/webpack.web.js | 2 +- lib/webworker/WebWorkerChunkTemplatePlugin.js | 3 +- lib/webworker/WebWorkerMainTemplatePlugin.js | 25 +- lib/webworker/WebWorkerTemplatePlugin.js | 3 +- 149 files changed, 2109 insertions(+), 2023 deletions(-) diff --git a/lib/APIPlugin.js b/lib/APIPlugin.js index 86cb8e06c..703c4e2da 100644 --- a/lib/APIPlugin.js +++ b/lib/APIPlugin.js @@ -47,4 +47,3 @@ APIPlugin.prototype.apply = function(compiler) { }); }); }; - diff --git a/lib/AbstractPlugin.js b/lib/AbstractPlugin.js index 585fb7490..12eaafbc5 100644 --- a/lib/AbstractPlugin.js +++ b/lib/AbstractPlugin.js @@ -16,7 +16,7 @@ AbstractPlugin.create = function(plugins) { }; AbstractPlugin.prototype.apply = function(object) { - for(var name in this._plugins) { + for (var name in this._plugins) { object.plugin(name, this._plugins[name]); } }; diff --git a/lib/AmdMainTemplatePlugin.js b/lib/AmdMainTemplatePlugin.js index 0effad5cc..27ae5b851 100644 --- a/lib/AmdMainTemplatePlugin.js +++ b/lib/AmdMainTemplatePlugin.js @@ -20,13 +20,13 @@ AmdMainTemplatePlugin.prototype.apply = function(compilation) { var externalsArguments = externals.map(function(m) { return "__WEBPACK_EXTERNAL_MODULE_" + m.id + "__"; }).join(", "); - if(this.name) { + if (this.name) { var name = mainTemplate.applyPluginsWaterfall("asset-path", this.name, { hash: hash, chunk: chunk }); return new ConcatSource("define(" + JSON.stringify(name) + ", " + externalsDepsArray + ", function(" + externalsArguments + ") { return ", source, "});"); - } else if(externalsArguments) { + } else if (externalsArguments) { return new ConcatSource("define(" + externalsDepsArray + ", function(" + externalsArguments + ") { return ", source, "});"); } else { return new ConcatSource("define(function() { return ", source, "});"); diff --git a/lib/ArrayMap.js b/lib/ArrayMap.js index 8de10d27d..f4d3bd085 100644 --- a/lib/ArrayMap.js +++ b/lib/ArrayMap.js @@ -9,8 +9,8 @@ function ArrayMap() { module.exports = ArrayMap; ArrayMap.prototype.get = function(key) { - for(var i = 0; i < this.keys.length; i++) { - if(this.keys[i] === key) { + for (var i = 0; i < this.keys.length; i++) { + if (this.keys[i] === key) { return this.values[i]; } } @@ -18,8 +18,8 @@ ArrayMap.prototype.get = function(key) { }; ArrayMap.prototype.set = function(key, value) { - for(var i = 0; i < this.keys.length; i++) { - if(this.keys[i] === key) { + for (var i = 0; i < this.keys.length; i++) { + if (this.keys[i] === key) { this.values[i] = value; return this; } @@ -30,8 +30,8 @@ ArrayMap.prototype.set = function(key, value) { }; ArrayMap.prototype.remove = function(key) { - for(var i = 0; i < this.keys.length; i++) { - if(this.keys[i] === key) { + for (var i = 0; i < this.keys.length; i++) { + if (this.keys[i] === key) { this.keys.splice(i, 1); this.values.splice(i, 1); return true; @@ -42,7 +42,7 @@ ArrayMap.prototype.remove = function(key) { ArrayMap.prototype.clone = function() { var newMap = new ArrayMap(); - for(var i = 0; i < this.keys.length; i++) { + for (var i = 0; i < this.keys.length; i++) { newMap.keys.push(this.keys[i]); newMap.values.push(this.values[i]); } diff --git a/lib/AutomaticPrefetchPlugin.js b/lib/AutomaticPrefetchPlugin.js index e1669ae04..e57f94ae6 100644 --- a/lib/AutomaticPrefetchPlugin.js +++ b/lib/AutomaticPrefetchPlugin.js @@ -6,8 +6,7 @@ var async = require("async"); var PrefetchDependency = require("./dependencies/PrefetchDependency"); var NormalModule = require("./NormalModule"); -function AutomaticPrefetchPlugin() { -} +function AutomaticPrefetchPlugin() {} module.exports = AutomaticPrefetchPlugin; AutomaticPrefetchPlugin.prototype.apply = function(compiler) { compiler.plugin("compilation", function(compilation, params) { @@ -28,7 +27,7 @@ AutomaticPrefetchPlugin.prototype.apply = function(compiler) { callback(); }); compiler.plugin("make", function(compilation, callback) { - if(!lastModules) return callback(); + if (!lastModules) return callback(); async.forEach(lastModules, function(m, callback) { compilation.prefetch(m.context || compiler.context, new PrefetchDependency(m.request), callback); }, callback); diff --git a/lib/BannerPlugin.js b/lib/BannerPlugin.js index a3c1143aa..d55997413 100644 --- a/lib/BannerPlugin.js +++ b/lib/BannerPlugin.js @@ -6,7 +6,7 @@ var ConcatSource = require("webpack-core/lib/ConcatSource"); var ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); function wrapComment(str) { - if(str.indexOf("\n") < 0) return "/*! " + str + " */"; + if (str.indexOf("\n") < 0) return "/*! " + str + " */"; return "/*!\n * " + str.split("\n").join("\n * ") + "\n */"; } @@ -23,7 +23,7 @@ BannerPlugin.prototype.apply = function(compiler) { compiler.plugin("compilation", function(compilation) { compilation.plugin("optimize-chunk-assets", function(chunks, callback) { chunks.forEach(function(chunk) { - if(options.entryOnly && !chunk.initial) return; + if (options.entryOnly && !chunk.initial) return; chunk.files.filter(ModuleFilenameHelpers.matchObject.bind(undefined, options)).forEach(function(file) { compilation.assets[file] = new ConcatSource(banner, "\n", compilation.assets[file]); }); diff --git a/lib/BasicEvaluatedExpression.js b/lib/BasicEvaluatedExpression.js index f00307a3f..2c03e510f 100644 --- a/lib/BasicEvaluatedExpression.js +++ b/lib/BasicEvaluatedExpression.js @@ -38,27 +38,27 @@ BasicEvaluatedExpression.prototype.isWrapped = function() { return Object.prototype.hasOwnProperty.call(this, "prefix") || Object.prototype.hasOwnProperty.call(this, "postfix"); }; BasicEvaluatedExpression.prototype.asBool = function() { - 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; - else if(this.isRegExp()) return true; - else if(this.isArray()) return true; - else if(this.isConstArray()) return true; - else if(this.isWrapped()) return this.prefix && this.prefix.asBool() || this.postfix && this.postfix.asBool() ? true : undefined; + 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; + else if (this.isRegExp()) return true; + else if (this.isArray()) return true; + else if (this.isConstArray()) return true; + else if (this.isWrapped()) return this.prefix && this.prefix.asBool() || this.postfix && this.postfix.asBool() ? true : undefined; return undefined; }; BasicEvaluatedExpression.prototype.set = function(value) { - if(typeof value === "string") return this.setString(value); - if(typeof value === "number") return this.setNumber(value); - if(typeof value === "boolean") return this.setBoolean(value); - if(value === null) return this.setNull(); - if(value instanceof RegExp) return this.setRegExp(value); - if(Array.isArray(value)) return this.setArray(value); + if (typeof value === "string") return this.setString(value); + if (typeof value === "number") return this.setNumber(value); + if (typeof value === "boolean") return this.setBoolean(value); + if (value === null) return this.setNull(); + if (value instanceof RegExp) return this.setRegExp(value); + if (Array.isArray(value)) return this.setArray(value); return this; }; BasicEvaluatedExpression.prototype.setString = function(str) { - if(str === null) + if (str === null) delete this.string; else this.string = str; @@ -69,28 +69,28 @@ BasicEvaluatedExpression.prototype.setNull = function() { return this; }; BasicEvaluatedExpression.prototype.setNumber = function(num) { - if(num === null) + if (num === null) delete this.number; else this.number = num; return this; }; BasicEvaluatedExpression.prototype.setBoolean = function(bool) { - if(bool === null) + if (bool === null) delete this.bool; else this.bool = bool; return this; }; BasicEvaluatedExpression.prototype.setRegExp = function(regExp) { - if(regExp === null) + if (regExp === null) delete this.regExp; else this.regExp = regExp; return this; }; BasicEvaluatedExpression.prototype.setIdentifier = function(identifier) { - if(identifier === null) + if (identifier === null) delete this.identifier; else this.identifier = identifier; @@ -107,28 +107,28 @@ BasicEvaluatedExpression.prototype.unsetWrapped = function() { return this; }; BasicEvaluatedExpression.prototype.setOptions = function(options) { - if(options === null) + if (options === null) delete this.options; else this.options = options; return this; }; BasicEvaluatedExpression.prototype.setItems = function(items) { - if(items === null) + if (items === null) delete this.items; else this.items = items; return this; }; BasicEvaluatedExpression.prototype.setArray = function(array) { - if(array === null) + if (array === null) delete this.array; else this.array = array; return this; }; BasicEvaluatedExpression.prototype.addOptions = function(options) { - if(!this.options) this.options = []; + if (!this.options) this.options = []; options.forEach(function(item) { this.options.push(item); }, this); @@ -138,6 +138,3 @@ BasicEvaluatedExpression.prototype.setRange = function(range) { this.range = range; return this; }; - - - diff --git a/lib/CachePlugin.js b/lib/CachePlugin.js index 3e5334e92..f7cc6437c 100644 --- a/lib/CachePlugin.js +++ b/lib/CachePlugin.js @@ -10,7 +10,7 @@ function CachePlugin(cache) { module.exports = CachePlugin; CachePlugin.prototype.apply = function(compiler) { - if(Array.isArray(compiler.compilers)) { + if (Array.isArray(compiler.compilers)) { compiler.compilers.forEach(function(c, idx) { c.apply(new CachePlugin(this.cache[idx] = this.cache[idx] || {})); }, this); @@ -19,13 +19,13 @@ CachePlugin.prototype.apply = function(compiler) { compilation.cache = this.cache; }.bind(this)); compiler.plugin("run", function(compiler, callback) { - if(!compiler._lastCompilationFileDependencies) return callback(); + if (!compiler._lastCompilationFileDependencies) return callback(); var fs = compiler.inputFileSystem; var fileTs = compiler.fileTimestamps = {}; async.forEach(compiler._lastCompilationFileDependencies, function(file, callback) { fs.stat(file, function(err, stat) { - if(err) { - if(err.code === "ENOENT") return callback(); + if (err) { + if (err.code === "ENOENT") return callback(); return callback(err); } diff --git a/lib/Chunk.js b/lib/Chunk.js index 1334743e3..cbbcb76b0 100644 --- a/lib/Chunk.js +++ b/lib/Chunk.js @@ -15,7 +15,7 @@ function Chunk(name, module, loc) { this.rendered = false; this.entry = false; this.initial = false; - if(module) { + if (module) { this.origins.push({ module: module, loc: loc, @@ -26,7 +26,7 @@ function Chunk(name, module, loc) { module.exports = Chunk; Chunk.prototype.addModule = function(module) { - if(this.modules.indexOf(module) >= 0) { + if (this.modules.indexOf(module) >= 0) { return false; } this.modules.push(module); @@ -49,10 +49,10 @@ Chunk.prototype.removeParent = function(chunk) { function createAdder(collection) { return function(chunk) { - if(chunk === this) { + if (chunk === this) { return false; } - if(this[collection].indexOf(chunk) >= 0) { + if (this[collection].indexOf(chunk) >= 0) { return false; } this[collection].push(chunk); @@ -65,7 +65,7 @@ Chunk.prototype.addChunk = createAdder("chunks"); Chunk.prototype.addParent = createAdder("parents"); Chunk.prototype.addBlock = function(block) { - if(this.blocks.indexOf(block) >= 0) { + if (this.blocks.indexOf(block) >= 0) { return false; } this.blocks.push(block); @@ -73,7 +73,11 @@ Chunk.prototype.addBlock = function(block) { }; Chunk.prototype.addOrigin = function(module, loc) { - this.origins.push({module: module, loc: loc, name: this.name}); + this.origins.push({ + module: module, + loc: loc, + name: this.name + }); }; Chunk.prototype.remove = function(reason) { @@ -82,7 +86,7 @@ Chunk.prototype.remove = function(reason) { }, this); this.parents.forEach(function(c) { var idx = c.chunks.indexOf(this); - if(idx >= 0) { + if (idx >= 0) { c.chunks.splice(idx, 1); } this.chunks.forEach(function(cc) { @@ -91,7 +95,7 @@ Chunk.prototype.remove = function(reason) { }, this); this.chunks.forEach(function(c) { var idx = c.parents.indexOf(this); - if(idx >= 0) { + if (idx >= 0) { c.parents.splice(idx, 1); } this.parents.forEach(function(cc) { @@ -100,9 +104,9 @@ Chunk.prototype.remove = function(reason) { }, this); this.blocks.forEach(function(b) { var idx = b.chunks.indexOf(this); - if(idx >= 0) { + if (idx >= 0) { b.chunks.splice(idx, 1); - if(b.chunks.length === 0) { + if (b.chunks.length === 0) { b.chunks = null; b.chunkReason = reason; } @@ -111,7 +115,7 @@ Chunk.prototype.remove = function(reason) { }; Chunk.prototype.integrate = function(other, reason) { - if(!this.canBeIntegrated(other)) { + if (!this.canBeIntegrated(other)) { return false; } @@ -123,23 +127,24 @@ Chunk.prototype.integrate = function(other, reason) { m.rewriteChunkInReasons(other, [this]); }, this); other.modules.length = 0; + function moveChunks(chunks, kind, onChunk) { chunks.forEach(function(c) { var idx = c[kind].indexOf(other); - if(idx >= 0) { + if (idx >= 0) { c[kind].splice(idx, 1); } onChunk(c); }); } moveChunks(other.parents, "chunks", function(c) { - if(c !== this && this.addParent(c)) { + if (c !== this && this.addParent(c)) { c.addChunk(this); } }.bind(this)); other.parents.length = 0; moveChunks(other.chunks, "parents", function(c) { - if(c !== this && this.addChunk(c)) { + if (c !== this && this.addChunk(c)) { c.addParent(this); } }.bind(this)); @@ -153,9 +158,9 @@ Chunk.prototype.integrate = function(other, reason) { }, this); other.blocks.length = 0; other.origins.forEach(function(origin) { - if(!origin.reasons) { + if (!origin.reasons) { origin.reasons = [reason]; - } else if(origin.reasons[0] !== reason) { + } else if (origin.reasons[0] !== reason) { origin.reasons.unshift(reason); } this.origins.push(origin); @@ -187,11 +192,11 @@ Chunk.prototype.size = function(options) { }; Chunk.prototype.canBeIntegrated = function(other) { - if(other.initial) { + if (other.initial) { return false; } - if(this.initial) { - if(other.parents.length !== 1 || other.parents[0] !== this) { + if (this.initial) { + if (other.parents.length !== 1 || other.parents[0] !== this) { return false; } } @@ -200,7 +205,7 @@ Chunk.prototype.canBeIntegrated = function(other) { Chunk.prototype.integratedSize = function(other, options) { // Chunk if it's possible to integrate this chunk - if(!this.canBeIntegrated(other)) { + if (!this.canBeIntegrated(other)) { return false; } @@ -209,7 +214,7 @@ Chunk.prototype.integratedSize = function(other, options) { var mergedModules = this.modules.slice(); other.modules.forEach(function(m) { - if(this.modules.indexOf(m) < 0) { + if (this.modules.indexOf(m) < 0) { mergedModules.push(m); } }, this); @@ -227,11 +232,11 @@ Chunk.prototype.getChunkMaps = function(includeEntries) { var chunkHashMap = {}; var chunkNameMap = {}; (function addChunk(c) { - if(chunksProcessed.indexOf(c) >= 0) return; + if (chunksProcessed.indexOf(c) >= 0) return; chunksProcessed.push(c); - if(!c.entry || includeEntries) { + if (!c.entry || includeEntries) { chunkHashMap[c.id] = c.renderedHash; - if(c.name) + if (c.name) chunkNameMap[c.id] = c.name; } c.chunks.forEach(addChunk); diff --git a/lib/ChunkTemplate.js b/lib/ChunkTemplate.js index f08a81229..9f836749e 100644 --- a/lib/ChunkTemplate.js +++ b/lib/ChunkTemplate.js @@ -16,9 +16,9 @@ ChunkTemplate.prototype.render = function(chunk, moduleTemplate, dependencyTempl var modules = this.renderChunkModules(chunk, moduleTemplate, dependencyTemplates); var core = this.applyPluginsWaterfall("modules", modules, chunk, moduleTemplate, dependencyTemplates); var source = this.applyPluginsWaterfall("render", core, chunk, moduleTemplate, dependencyTemplates); - if(chunk.modules.some(function(module) { - return (module.id === 0); - })) { + if (chunk.modules.some(function(module) { + return (module.id === 0); + })) { source = this.applyPluginsWaterfall("render-with-entry", source, chunk); } chunk.rendered = true; diff --git a/lib/CompatibilityPlugin.js b/lib/CompatibilityPlugin.js index 85458bb3d..8543414aa 100644 --- a/lib/CompatibilityPlugin.js +++ b/lib/CompatibilityPlugin.js @@ -9,8 +9,7 @@ var ModuleAliasPlugin = require("enhanced-resolve/lib/ModuleAliasPlugin"); var NullFactory = require("./NullFactory"); -function CompatibilityPlugin() { -} +function CompatibilityPlugin() {} module.exports = CompatibilityPlugin; CompatibilityPlugin.prototype.apply = function(compiler) { @@ -25,15 +24,15 @@ CompatibilityPlugin.prototype.apply = function(compiler) { ); compiler.parser.plugin("call require", function(expr) { // support for browserify style require delegator: "require(o, !0)" - if(expr.arguments.length !== 2) return; + if (expr.arguments.length !== 2) return; var second = this.evaluateExpression(expr.arguments[1]); - if(!second.isBoolean()) return; - if(second.asBool() !== true) return; + if (!second.isBoolean()) return; + if (second.asBool() !== true) return; var dep = new ConstDependency("require", expr.callee.range); dep.loc = expr.loc; - if(this.state.current.dependencies.length > 1) { + if (this.state.current.dependencies.length > 1) { var last = this.state.current.dependencies[this.state.current.dependencies.length - 1]; - if(last.critical && last.request === "." && last.userRequest === "." && last.recursive) + if (last.critical && last.request === "." && last.userRequest === "." && last.recursive) this.state.current.dependencies.pop(); } dep.critical = "This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results."; diff --git a/lib/Compilation.js b/lib/Compilation.js index 304d28dc9..fcbe1f365 100644 --- a/lib/Compilation.js +++ b/lib/Compilation.js @@ -67,18 +67,18 @@ Compilation.prototype.templatesPlugin = function(name, fn) { Compilation.prototype.addModule = function(module, cacheGroup) { cacheGroup = cacheGroup || "m"; var identifier = module.identifier(); - if(this._modules[identifier]) { + if (this._modules[identifier]) { return false; } - if(this.cache && this.cache[cacheGroup + identifier]) { + if (this.cache && this.cache[cacheGroup + identifier]) { var cacheModule = this.cache[cacheGroup + identifier]; var rebuild = true; - if(!cacheModule.error && cacheModule.cacheable && this.fileTimestamps && this.contextTimestamps) { + if (!cacheModule.error && cacheModule.cacheable && this.fileTimestamps && this.contextTimestamps) { rebuild = cacheModule.needRebuild(this.fileTimestamps, this.contextTimestamps); } - if(!rebuild) { + if (!rebuild) { cacheModule.disconnect(); this._modules[identifier] = cacheModule; this.modules.push(cacheModule); @@ -94,7 +94,7 @@ Compilation.prototype.addModule = function(module, cacheGroup) { } } this._modules[identifier] = module; - if(this.cache) { + if (this.cache) { this.cache[cacheGroup + identifier] = module; } this.modules.push(module); @@ -112,7 +112,7 @@ Compilation.prototype.findModule = function(identifier) { Compilation.prototype.buildModule = function(module, thisCallback) { this.applyPlugins("build-module", module); - if(module.building) return module.building.push(thisCallback); + if (module.building) return module.building.push(thisCallback); var building = module.building = [thisCallback]; function callback(err) { @@ -129,7 +129,7 @@ Compilation.prototype.buildModule = function(module, thisCallback) { this.warnings.push(err); }, this); module.dependencies.sort(Dependency.compare); - if(err) { + if (err) { module.error = err; this.applyPlugins("failed-module", module); return callback(err); @@ -143,8 +143,8 @@ Compilation.prototype.processModuleDependencies = function(module, callback) { var dependencies = []; function addDependency(dep) { - for(var i = 0; i < dependencies.length; i++) { - if(dep.isEqualResource(dependencies[i][0])) { + for (var i = 0; i < dependencies.length; i++) { + if (dep.isEqualResource(dependencies[i][0])) { return dependencies[i].push(dep); } } @@ -152,13 +152,13 @@ Compilation.prototype.processModuleDependencies = function(module, callback) { } function addDependenciesBlock(block) { - if(block.dependencies) { + if (block.dependencies) { block.dependencies.forEach(addDependency); } - if(block.blocks) { + if (block.blocks) { block.blocks.forEach(addDependenciesBlock); } - if(block.variables) { + if (block.variables) { block.variables.forEach(function(v) { v.dependencies.forEach(addDependency); }); @@ -172,9 +172,9 @@ Compilation.prototype.addModuleDependencies = function(module, dependencies, bai var start = this.profile && +new Date(); var factories = []; - for(var i = 0; i < dependencies.length; i++) { + for (var i = 0; i < dependencies.length; i++) { var factory = this.dependencyFactories.get(dependencies[i][0].Class); - if(!factory) { + if (!factory) { return callback(new Error("No module factory available for dependency type: " + dependencies[i][0].Class.name)); } factories[i] = [factory, dependencies[i]]; @@ -184,7 +184,7 @@ Compilation.prototype.addModuleDependencies = function(module, dependencies, bai var criticalDependencies = dependencies.filter(function(d) { return !!d.critical; }); - if(criticalDependencies.length > 0) { + if (criticalDependencies.length > 0) { this.warnings.push(new CriticalDependenciesWarning(module, criticalDependencies)); } @@ -193,7 +193,7 @@ Compilation.prototype.addModuleDependencies = function(module, dependencies, bai err.origin = module; module.dependenciesErrors.push(err); this.errors.push(err); - if(bail) { + if (bail) { callback(err); } else { callback(); @@ -216,20 +216,20 @@ Compilation.prototype.addModuleDependencies = function(module, dependencies, bai } function errorOrWarningAndCallback(err) { - if(isOptional()) { + if (isOptional()) { return warningAndCallback(err); } else { return errorAndCallback(err); } } - if(err) { + if (err) { return errorOrWarningAndCallback(new ModuleNotFoundError(module, err)); } - if(!dependantModule) { + if (!dependantModule) { return process.nextTick(callback); } - if(this.profile) { - if(!dependantModule.profile) { + if (this.profile) { + if (!dependantModule.profile) { dependantModule.profile = {}; } var afterFactory = +new Date(); @@ -239,14 +239,14 @@ Compilation.prototype.addModuleDependencies = function(module, dependencies, bai dependantModule.issuer = module.identifier(); var newModule = this.addModule(dependantModule, cacheGroup); - if(!newModule) { // from cache + if (!newModule) { // from cache dependantModule = this.getModule(dependantModule); - if(dependantModule.optional) { + if (dependantModule.optional) { dependantModule.optional = isOptional(); } - if(dependantModule.id === 0) { + if (dependantModule.id === 0) { return errorOrWarningAndCallback( new ModuleNotFoundError(module, new Error("a dependency to an entry point is not allowed")) ); @@ -257,12 +257,12 @@ Compilation.prototype.addModuleDependencies = function(module, dependencies, bai dependantModule.addReason(module, dep); }); - if(this.profile) { - if(!module.profile) { + if (this.profile) { + if (!module.profile) { module.profile = {}; } var time = +new Date() - start; - if(!module.profile.dependencies || time > module.profile.dependencies) { + if (!module.profile.dependencies || time > module.profile.dependencies) { module.profile.dependencies = time; } } @@ -270,8 +270,8 @@ Compilation.prototype.addModuleDependencies = function(module, dependencies, bai return process.nextTick(callback); } - if(newModule instanceof Module) { - if(this.profile) { + if (newModule instanceof Module) { + if (this.profile) { newModule.profile = dependantModule.profile; } @@ -284,12 +284,12 @@ Compilation.prototype.addModuleDependencies = function(module, dependencies, bai dependantModule.addReason(module, dep); }); - if(this.profile) { + if (this.profile) { var afterBuilding = +new Date(); module.profile.building = afterBuilding - afterFactory; } - if(recursive) { + if (recursive) { return process.nextTick(this.processModuleDependencies.bind(this, dependantModule, callback)); } else { return process.nextTick(callback); @@ -304,16 +304,16 @@ Compilation.prototype.addModuleDependencies = function(module, dependencies, bai }); this.buildModule(dependantModule, function(err) { - if(err) { + if (err) { return errorOrWarningAndCallback(err); } - if(this.profile) { + if (this.profile) { var afterBuilding = +new Date(); dependantModule.profile.building = afterBuilding - afterFactory; } - if(recursive) { + if (recursive) { this.processModuleDependencies(dependantModule, callback); } else { return callback(); @@ -322,7 +322,7 @@ Compilation.prototype.addModuleDependencies = function(module, dependencies, bai }.bind(this)); }.bind(this), function(err) { - if(err) { + if (err) { return callback(err); } @@ -341,22 +341,22 @@ Compilation.prototype._addModuleChain = function process(context, dependency, on callback(); }.bind(this); - if(typeof dependency !== "object" || dependency === null || !dependency.Class) { + if (typeof dependency !== "object" || dependency === null || !dependency.Class) { throw new Error("Parameter 'dependency' must be a Dependency"); } var moduleFactory = this.dependencyFactories.get(dependency.Class); - if(!moduleFactory) { + if (!moduleFactory) { throw new Error("No dependency factory available for this dependency type: " + dependency.Class.name); } moduleFactory.create(context, dependency, function(err, module) { - if(err) { + if (err) { return errorAndCallback(new EntryModuleNotFoundError(err)); } - if(this.profile) { - if(!module.profile) { + if (this.profile) { + if (!module.profile) { module.profile = {}; } var afterFactory = +new Date(); @@ -364,12 +364,12 @@ Compilation.prototype._addModuleChain = function process(context, dependency, on } var result = this.addModule(module); - if(!result) { + if (!result) { module = this.getModule(module); onModule(module); - if(this.profile) { + if (this.profile) { var afterBuilding = +new Date(); module.profile.building = afterBuilding - afterFactory; } @@ -377,8 +377,8 @@ Compilation.prototype._addModuleChain = function process(context, dependency, on return callback(null, module); } - if(result instanceof Module) { - if(this.profile) { + if (result instanceof Module) { + if (this.profile) { result.profile = module.profile; } @@ -393,11 +393,11 @@ Compilation.prototype._addModuleChain = function process(context, dependency, on onModule(module); this.buildModule(module, function(err) { - if(err) { + if (err) { return errorAndCallback(err); } - if(this.profile) { + if (this.profile) { var afterBuilding = +new Date(); module.profile.building = afterBuilding - afterFactory; } @@ -407,7 +407,7 @@ Compilation.prototype._addModuleChain = function process(context, dependency, on function moduleReady() { this.processModuleDependencies(module, function(err) { - if(err) { + if (err) { return callback(err); } @@ -426,12 +426,12 @@ Compilation.prototype.addEntry = function process(context, entry, name, callback module.id = 0; }.bind(this), function(err, module) { - if(err) { + if (err) { return callback(err); } - if(module) { - if(module.reasons.length > 0) { + if (module) { + if (module.reasons.length > 0) { return callback(new Error("module cannot be added as entry point, because it's already in the bundle")); } this.preparedChunks.push({ @@ -453,9 +453,9 @@ Compilation.prototype.prefetch = function process(context, dependency, callback) }; Compilation.prototype.rebuildModule = function(module, thisCallback) { - if(module.variables.length || module.blocks.length) + if (module.variables.length || module.blocks.length) throw new Error("Cannot rebuild a complex module with variables or blocks"); - if(module.rebuilding) { + if (module.rebuilding) { return module.rebuilding.push(thisCallback); } var rebuilding = module.rebuilding = [thisCallback]; @@ -468,15 +468,15 @@ Compilation.prototype.rebuildModule = function(module, thisCallback) { } var deps = module.dependencies.slice(); this.buildModule(module, function(err) { - if(err) return callback(err); + if (err) return callback(err); this.processModuleDependencies(module, function(err) { - if(err) return callback(err); + if (err) return callback(err); deps.forEach(function(d) { - if(d.module && d.module.removeReason(module, d)) { + if (d.module && d.module.removeReason(module, d)) { module.chunks.forEach(function(chunk) { - if(!d.module.hasReasonForChunk(chunk)) { - if(d.module.removeChunk(chunk)) { + if (!d.module.hasReasonForChunk(chunk)) { + if (d.module.removeChunk(chunk)) { this.removeChunkFromDependencies(d.module, chunk); } } @@ -492,8 +492,8 @@ Compilation.prototype.rebuildModule = function(module, thisCallback) { Compilation.prototype.seal = function seal(callback) { this.applyPlugins("seal"); this.preparedChunks.sort(function(a, b) { - if(a.name < b.name) return -1; - if(a.name > b.name) return 1; + if (a.name < b.name) return -1; + if (a.name > b.name) return 1; return 0; }); this.preparedChunks.forEach(function(preparedChunk) { @@ -502,11 +502,11 @@ Compilation.prototype.seal = function seal(callback) { chunk.initial = chunk.entry = true; chunk.addModule(module); module.addChunk(chunk); - if(typeof module.index !== "number") { + if (typeof module.index !== "number") { module.index = this.nextFreeModuleIndex++; } this.processDependenciesBlockForChunk(module, chunk); - if(typeof module.index2 !== "number") { + if (typeof module.index2 !== "number") { module.index2 = this.nextFreeModuleIndex2++; } }, this); @@ -520,7 +520,7 @@ Compilation.prototype.seal = function seal(callback) { this.applyPlugins("after-optimize-chunks", this.chunks); this.applyPluginsAsync("optimize-tree", this.chunks, this.modules, function(err) { - if(err) { + if (err) { return callback(err); } @@ -534,7 +534,7 @@ Compilation.prototype.seal = function seal(callback) { this.applyModuleIds(); this.applyPlugins("optimize-module-ids", this.modules); this.applyPlugins("after-optimize-module-ids", this.modules); - if(shouldRecord) + if (shouldRecord) this.applyPlugins("record-modules", this.modules, this.records); this.applyPlugins("revive-chunks", this.chunks, this.records); @@ -543,7 +543,7 @@ Compilation.prototype.seal = function seal(callback) { this.applyChunkIds(); this.applyPlugins("optimize-chunk-ids", this.chunks); this.applyPlugins("after-optimize-chunk-ids", this.chunks); - if(shouldRecord) + if (shouldRecord) this.applyPlugins("record-chunks", this.chunks, this.records); this.sortItems(); @@ -554,20 +554,20 @@ Compilation.prototype.seal = function seal(callback) { this.createChunkAssets(); this.applyPlugins("additional-chunk-assets", this.chunks); this.summarizeDependencies(); - if(shouldRecord) + if (shouldRecord) this.applyPlugins("record", this, this.records); this.applyPluginsAsync("additional-assets", function(err) { - if(err) { + if (err) { return callback(err); } this.applyPluginsAsync("optimize-chunk-assets", this.chunks, function(err) { - if(err) { + if (err) { return callback(err); } this.applyPlugins("after-optimize-chunk-assets", this.chunks); this.applyPluginsAsync("optimize-assets", this.assets, function(err) { - if(err) { + if (err) { return callback(err); } this.applyPlugins("after-optimize-assets", this.assets); @@ -580,18 +580,18 @@ Compilation.prototype.seal = function seal(callback) { Compilation.prototype.sortModules = function sortModules(modules) { modules.sort(function(a, b) { - if(a.index < b.index) return -1; - if(a.index > b.index) return 1; + if (a.index < b.index) return -1; + if (a.index > b.index) return 1; return 0; }); }; Compilation.prototype.addChunk = function addChunk(name, module, loc) { var chunk; - if(name) { - if(Object.prototype.hasOwnProperty.call(this.namedChunks, name)) { + if (name) { + if (Object.prototype.hasOwnProperty.call(this.namedChunks, name)) { chunk = this.namedChunks[name]; - if(module) { + if (module) { chunk.addOrigin(module, loc); } return chunk; @@ -599,25 +599,25 @@ Compilation.prototype.addChunk = function addChunk(name, module, loc) { } chunk = new Chunk(name, module, loc); this.chunks.push(chunk); - if(name) { + if (name) { this.namedChunks[name] = chunk; } return chunk; }; Compilation.prototype.processDependenciesBlockForChunk = function processDependenciesBlockForChunk(block, chunk) { - if(block.variables) { + if (block.variables) { block.variables.forEach(function(v) { v.dependencies.forEach(iteratorDependency, this); }, this); } - if(block.dependencies) { + if (block.dependencies) { block.dependencies.forEach(iteratorDependency, this); } - if(block.blocks) { + if (block.blocks) { block.blocks.forEach(function(b) { var c; - if(!b.chunks) { + if (!b.chunks) { c = this.addChunk(b.chunkName, b.module, b.loc); b.chunks = [c]; c.addBlock(b); @@ -631,24 +631,24 @@ Compilation.prototype.processDependenciesBlockForChunk = function processDepende } function iteratorDependency(d) { - if(!d.module) { + if (!d.module) { return; } - if(typeof d.module.index !== "number") { + if (typeof d.module.index !== "number") { d.module.index = this.nextFreeModuleIndex++; } - if(d.weak) { + if (d.weak) { return; } - if(d.module.error) { + if (d.module.error) { d.module = null; return; } - if(chunk.addModule(d.module)) { + if (chunk.addModule(d.module)) { d.module.addChunk(chunk); this.processDependenciesBlockForChunk(d.module, chunk); } - if(typeof d.module.index2 !== "number") { + if (typeof d.module.index2 !== "number") { d.module.index2 = this.nextFreeModuleIndex2++; } } @@ -664,11 +664,11 @@ Compilation.prototype.removeChunkFromDependencies = function removeChunkFromDepe }, this); function iteratorDependency(d) { - if(!d.module) { + if (!d.module) { return; } - if(!d.module.hasReasonForChunk(chunk)) { - if(d.module.removeChunk(chunk)) { + if (!d.module.hasReasonForChunk(chunk)) { + if (d.module.removeChunk(chunk)) { this.removeChunkFromDependencies(d.module, chunk); } } @@ -682,7 +682,7 @@ Compilation.prototype.removeChunkFromDependencies = function removeChunkFromDepe Compilation.prototype.applyModuleIds = function applyModuleIds() { this.modules.forEach(function(module) { - if(module.id === null) { + if (module.id === null) { module.id = this.nextFreeModuleId++; } }, this); @@ -690,10 +690,10 @@ Compilation.prototype.applyModuleIds = function applyModuleIds() { Compilation.prototype.applyChunkIds = function applyChunkIds() { this.chunks.forEach(function(chunk) { - if(chunk.id === null) { + if (chunk.id === null) { chunk.id = this.nextFreeChunkId++; } - if(!chunk.ids) { + if (!chunk.ids) { chunk.ids = [chunk.id]; } }, this); @@ -719,8 +719,8 @@ Compilation.prototype.sortItems = function sortItems() { Compilation.prototype.summarizeDependencies = function summarizeDependencies() { function filterDups(array) { var newArray = []; - for(var i = 0; i < array.length; i++) { - if(i === 0 || array[i - 1] !== array[i]) + for (var i = 0; i < array.length; i++) { + if (i === 0 || array[i - 1] !== array[i]) newArray.push(array[i]); } return newArray; @@ -734,19 +734,19 @@ Compilation.prototype.summarizeDependencies = function summarizeDependencies() { this.missingDependencies = this.missingDependencies.concat(child.missingDependencies); }.bind(this)); this.modules.forEach(function(module) { - if(module.fileDependencies) { + if (module.fileDependencies) { module.fileDependencies.forEach(function(item) { this.fileDependencies.push(item); }, this); } - if(module.contextDependencies) { + if (module.contextDependencies) { module.contextDependencies.forEach(function(item) { this.contextDependencies.push(item); }, this); } }, this); this.errors.forEach(function(error) { - if(Array.isArray(error.missing)) { + if (Array.isArray(error.missing)) { error.missing.forEach(function(item) { this.missingDependencies.push(item); }, this); @@ -770,11 +770,11 @@ Compilation.prototype.createHash = function createHash() { this.chunkTemplate.updateHash(hash); this.moduleTemplate.updateHash(hash); var i, chunk; - for(i = 0; i < this.chunks.length; i++) { + for (i = 0; i < this.chunks.length; i++) { chunk = this.chunks[i]; var chunkHash = require("crypto").createHash(hashFunction); chunk.updateHash(chunkHash); - if(chunk.entry) { + if (chunk.entry) { this.mainTemplate.updateHashForChunk(chunkHash, chunk); } else { this.chunkTemplate.updateHashForChunk(chunkHash); @@ -805,9 +805,9 @@ Compilation.prototype.createChunkAssets = function createChunkAssets() { var filename = outputOptions.filename || "bundle.js"; var chunkFilename = outputOptions.chunkFilename || "[id]." + filename; var namedChunkFilename = outputOptions.namedChunkFilename || null; - for(var i = 0; i < this.modules.length; i++) { + for (var i = 0; i < this.modules.length; i++) { var module = this.modules[i]; - if(module.assets) { + if (module.assets) { Object.keys(module.assets).forEach(function(name) { var file = this.getPath(name); this.assets[file] = module.assets[name]; @@ -815,7 +815,7 @@ Compilation.prototype.createChunkAssets = function createChunkAssets() { }, this); } } - for(i = 0; i < this.chunks.length; i++) { + for (i = 0; i < this.chunks.length; i++) { var chunk = this.chunks[i]; chunk.files = []; var chunkHash = chunk.hash; @@ -827,15 +827,15 @@ Compilation.prototype.createChunkAssets = function createChunkAssets() { try { var useChunkHash = !chunk.entry || (this.mainTemplate.useChunkHash && this.mainTemplate.useChunkHash(chunk)); var usedHash = useChunkHash ? chunkHash : this.fullHash; - if(this.cache && this.cache["c" + chunk.id] && this.cache["c" + chunk.id].hash === usedHash) { + if (this.cache && this.cache["c" + chunk.id] && this.cache["c" + chunk.id].hash === usedHash) { source = this.cache["c" + chunk.id].source; } else { - if(chunk.entry) { + if (chunk.entry) { source = this.mainTemplate.render(this.hash, chunk, this.moduleTemplate, this.dependencyTemplates); } else { source = this.chunkTemplate.render(chunk, this.moduleTemplate, this.dependencyTemplates); } - if(this.cache) { + if (this.cache) { this.cache["c" + chunk.id] = { hash: usedHash, source: source = (source instanceof CachedSource ? source : new CachedSource(source)) @@ -851,7 +851,7 @@ Compilation.prototype.createChunkAssets = function createChunkAssets() { chunk.files.push(file); this.applyPlugins("chunk-asset", chunk, file); file = undefined; - if(chunk.id !== 0 && namedChunkFilename && chunk.name) { + if (chunk.id !== 0 && namedChunkFilename && chunk.name) { this.assets[ file = this.getPath(namedChunkFilename, { noChunkHash: !useChunkHash, @@ -861,7 +861,7 @@ Compilation.prototype.createChunkAssets = function createChunkAssets() { chunk.files.push(file); this.applyPlugins("chunk-asset", chunk, file); } - } catch(err) { + } catch (err) { this.errors.push(new ChunkRenderError(chunk, file || filenameTemplate, err)); } } diff --git a/lib/Compiler.js b/lib/Compiler.js index a245c4d71..1e608662d 100644 --- a/lib/Compiler.js +++ b/lib/Compiler.js @@ -18,11 +18,11 @@ function Watching(compiler, watchOptions, handler) { this.error = null; this.stats = null; this.handler = handler; - if(typeof watchOptions === "number") { + if (typeof watchOptions === "number") { this.watchOptions = { aggregateTimeout: watchOptions }; - } else if(watchOptions && typeof watchOptions === "object") { + } else if (watchOptions && typeof watchOptions === "object") { this.watchOptions = Object.create(watchOptions); } else { this.watchOptions = {}; @@ -31,7 +31,7 @@ function Watching(compiler, watchOptions, handler) { this.compiler = compiler; this.running = true; this.compiler.readRecords(function(err) { - if(err) return this._done(err); + if (err) return this._done(err); this._go(); }.bind(this)); @@ -42,21 +42,21 @@ Watching.prototype._go = function() { this.running = true; this.invalid = false; this.compiler.applyPluginsAsync("watch-run", this, function(err) { - if(err) return this._done(err); + if (err) return this._done(err); this.compiler.compile(function(err, compilation) { - if(err) return this._done(err); - if(this.invalid) return this._done(); + if (err) return this._done(err); + if (this.invalid) return this._done(); - if(this.compiler.applyPluginsBailResult("should-emit", compilation) === false) { + if (this.compiler.applyPluginsBailResult("should-emit", compilation) === false) { return this._done(null, compilation); } this.compiler.emitAssets(compilation, function(err) { - if(err) return this._done(err); - if(this.invalid) return this._done(); + if (err) return this._done(err); + if (this.invalid) return this._done(); this.compiler.emitRecords(function(err) { - if(err) return this._done(err); + if (err) return this._done(err); return this._done(null, compilation); }.bind(this)); @@ -67,26 +67,26 @@ Watching.prototype._go = function() { Watching.prototype._done = function(err, compilation) { this.running = false; - if(this.invalid) return this._go(); + if (this.invalid) return this._go(); this.error = err || null; this.stats = compilation ? compilation.getStats() : null; - if(this.stats) { + if (this.stats) { this.stats.startTime = this.startTime; this.stats.endTime = new Date().getTime(); } - if(this.stats) + if (this.stats) this.compiler.applyPlugins("done", this.stats); else this.compiler.applyPlugins("failed", this.error); this.handler(this.error, this.stats); - if(!this.error) + if (!this.error) this.watch(compilation.fileDependencies, compilation.contextDependencies, compilation.missingDependencies); }; Watching.prototype.watch = function(files, dirs, missing) { this.watcher = this.compiler.watchFileSystem.watch(files, dirs, missing, this.startTime, this.watchOptions, function(err, filesModified, contextModified, missingModified, fileTimestamps, contextTimestamps) { this.watcher = null; - if(err) return this.handler(err); + if (err) return this.handler(err); this.compiler.fileTimestamps = fileTimestamps; this.compiler.contextTimestamps = contextTimestamps; @@ -97,11 +97,11 @@ Watching.prototype.watch = function(files, dirs, missing) { }; Watching.prototype.invalidate = function() { - if(this.watcher) { + if (this.watcher) { this.watcher.pause(); this.watcher = null; } - if(this.running) { + if (this.running) { this.invalid = true; return false; } else { @@ -110,13 +110,13 @@ Watching.prototype.invalidate = function() { }; Watching.prototype.close = function(callback) { - if(callback === undefined) callback = function(){}; + if (callback === undefined) callback = function() {}; - if(this.watcher) { + if (this.watcher) { this.watcher.close(); this.watcher = null; } - if(this.running) { + if (this.running) { this.invalid = true; this._done = function() { callback(); @@ -164,15 +164,15 @@ Compiler.prototype.watch = function(watchOptions, handler) { Compiler.prototype.run = function(callback) { var startTime = new Date().getTime(); this.applyPluginsAsync("run", this, function(err) { - if(err) return callback(err); + if (err) return callback(err); this.readRecords(function(err) { - if(err) return callback(err); + if (err) return callback(err); this.compile(function(err, compilation) { - if(err) return callback(err); + if (err) return callback(err); - if(this.applyPluginsBailResult("should-emit", compilation) === false) { + if (this.applyPluginsBailResult("should-emit", compilation) === false) { var stats = compilation.getStats(); stats.startTime = startTime; stats.endTime = new Date().getTime(); @@ -181,10 +181,10 @@ Compiler.prototype.run = function(callback) { } this.emitAssets(compilation, function(err) { - if(err) return callback(err); + if (err) return callback(err); this.emitRecords(function(err) { - if(err) return callback(err); + if (err) return callback(err); var stats = compilation.getStats(); stats.startTime = startTime; @@ -200,7 +200,7 @@ Compiler.prototype.run = function(callback) { Compiler.prototype.runAsChild = function(callback) { this.compile(function(err, compilation) { - if(err) return callback(err); + if (err) return callback(err); this.parentCompilation.children.push(compilation); Object.keys(compilation.assets).forEach(function(name) { @@ -215,7 +215,7 @@ Compiler.prototype.runAsChild = function(callback) { }; Compiler.prototype.purgeInputFileSystem = function() { - if(this.inputFileSystem && this.inputFileSystem.purge) + if (this.inputFileSystem && this.inputFileSystem.purge) this.inputFileSystem.purge(); }; @@ -223,36 +223,37 @@ Compiler.prototype.emitAssets = function(compilation, callback) { var outputPath; this.applyPluginsAsync("emit", compilation, function(err) { - if(err) return callback(err); + if (err) return callback(err); outputPath = compilation.getPath(this.outputPath); this.outputFileSystem.mkdirp(outputPath, emitFiles.bind(this)); }.bind(this)); function emitFiles(err) { - if(err) return callback(err); + if (err) return callback(err); require("async").forEach(Object.keys(compilation.assets), function(file, callback) { var targetFile = file; var queryStringIdx = targetFile.indexOf("?"); - if(queryStringIdx >= 0) { + if (queryStringIdx >= 0) { targetFile = targetFile.substr(0, queryStringIdx); } - if(targetFile.match(/\/|\\/)) { + if (targetFile.match(/\/|\\/)) { var dir = path.dirname(targetFile); this.outputFileSystem.mkdirp(this.outputFileSystem.join(outputPath, dir), writeOut.bind(this)); } else writeOut.call(this); + function writeOut(err) { - if(err) return callback(err); + if (err) return callback(err); var targetPath = this.outputFileSystem.join(outputPath, targetFile); var source = compilation.assets[file]; - if(source.existsAt === targetPath) { + if (source.existsAt === targetPath) { source.emitted = false; return callback(); } var content = source.source(); - if(!Buffer.isBuffer(content)) + if (!Buffer.isBuffer(content)) content = new Buffer(content, "utf-8"); source.existsAt = targetPath; source.emitted = true; @@ -260,7 +261,7 @@ Compiler.prototype.emitAssets = function(compilation, callback) { } }.bind(this), function(err) { - if(err) return callback(err); + if (err) return callback(err); afterEmit.call(this); }.bind(this)); @@ -268,7 +269,7 @@ Compiler.prototype.emitAssets = function(compilation, callback) { function afterEmit() { this.applyPluginsAsync("after-emit", compilation, function(err) { - if(err) return callback(err); + if (err) return callback(err); return callback(); }); @@ -277,15 +278,15 @@ Compiler.prototype.emitAssets = function(compilation, callback) { }; Compiler.prototype.emitRecords = function emitRecords(callback) { - if(!this.recordsOutputPath) return callback(); + if (!this.recordsOutputPath) return callback(); var idx1 = this.recordsOutputPath.lastIndexOf("/"); var idx2 = this.recordsOutputPath.lastIndexOf("\\"); var recordsOutputPathDirectory = null; - if(idx1 > idx2) recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx1); - if(idx1 < idx2) recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx2); - if(!recordsOutputPathDirectory) return writeFile.call(this); + if (idx1 > idx2) recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx1); + if (idx1 < idx2) recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx2); + if (!recordsOutputPathDirectory) return writeFile.call(this); this.outputFileSystem.mkdirp(recordsOutputPathDirectory, function(err) { - if(err) return callback(err); + if (err) return callback(err); writeFile.call(this); }.bind(this)); @@ -295,21 +296,21 @@ Compiler.prototype.emitRecords = function emitRecords(callback) { }; Compiler.prototype.readRecords = function readRecords(callback) { - if(!this.recordsInputPath) { + if (!this.recordsInputPath) { this.records = {}; return callback(); } this.inputFileSystem.stat(this.recordsInputPath, function(err) { // It doesn't exist // We can ignore this. - if(err) return callback(); + if (err) return callback(); this.inputFileSystem.readFile(this.recordsInputPath, function(err, content) { - if(err) return callback(err); + if (err) return callback(err); try { this.records = JSON.parse(content); - } catch(e) { + } catch (e) { e.message = "Cannot parse records: " + e.message; return callback(e); } @@ -321,8 +322,8 @@ Compiler.prototype.readRecords = function readRecords(callback) { Compiler.prototype.createChildCompiler = function(compilation, compilerName, outputOptions) { var childCompiler = new Compiler(); - for(var name in this._plugins) { - if(["make", "compile", "emit", "after-emit", "invalid", "done", "this-compilation"].indexOf(name) < 0) + for (var name in this._plugins) { + if (["make", "compile", "emit", "after-emit", "invalid", "done", "this-compilation"].indexOf(name) < 0) childCompiler._plugins[name] = this._plugins[name].slice(); } childCompiler.name = compilerName; @@ -333,11 +334,11 @@ Compiler.prototype.createChildCompiler = function(compilation, compilerName, out childCompiler.parser = this.parser; childCompiler.fileTimestamps = this.fileTimestamps; childCompiler.contextTimestamps = this.contextTimestamps; - if(!this.records[compilerName]) this.records[compilerName] = []; + if (!this.records[compilerName]) this.records[compilerName] = []; this.records[compilerName].push(childCompiler.records = {}); childCompiler.options = Object.create(this.options); childCompiler.options.output = Object.create(childCompiler.options.output); - for(name in outputOptions) { + for (name in outputOptions) { childCompiler.options.output[name] = outputOptions[name]; } childCompiler.parentCompilation = compilation; @@ -390,13 +391,13 @@ Compiler.prototype.compile = function(callback) { var compilation = this.newCompilation(params); this.applyPluginsParallel("make", compilation, function(err) { - if(err) return callback(err); + if (err) return callback(err); compilation.seal(function(err) { - if(err) return callback(err); + if (err) return callback(err); this.applyPluginsAsync("after-compile", compilation, function(err) { - if(err) return callback(err); + if (err) return callback(err); return callback(null, compilation); }); diff --git a/lib/ConstPlugin.js b/lib/ConstPlugin.js index ccc37c663..51c9d95b6 100644 --- a/lib/ConstPlugin.js +++ b/lib/ConstPlugin.js @@ -18,8 +18,8 @@ ConstPlugin.prototype.apply = function(compiler) { compiler.parser.plugin("statement if", function(statement) { var param = this.evaluateExpression(statement.test); var bool = param.asBool(); - if(typeof bool === "boolean") { - if(statement.test.type !== "Literal") { + if (typeof bool === "boolean") { + if (statement.test.type !== "Literal") { var dep = new ConstDependency(bool + "", param.range); dep.loc = statement.loc; this.state.current.addDependency(dep); @@ -30,8 +30,8 @@ ConstPlugin.prototype.apply = function(compiler) { compiler.parser.plugin("expression ?:", function(expression) { var param = this.evaluateExpression(expression.test); var bool = param.asBool(); - if(typeof bool === "boolean") { - if(expression.test.type !== "Literal") { + if (typeof bool === "boolean") { + if (expression.test.type !== "Literal") { var dep = new ConstDependency(bool + "", param.range); dep.loc = expression.loc; this.state.current.addDependency(dep); @@ -40,17 +40,15 @@ ConstPlugin.prototype.apply = function(compiler) { } }); compiler.parser.plugin("evaluate Identifier __resourceQuery", function(expr) { - if(!this.state.module) return; + if (!this.state.module) return; var res = new BasicEvaluatedExpression(); res.setString(this.state.module.splitQuery(this.state.module.resource)[1]); res.setRange(expr.range); return res; }); compiler.parser.plugin("expression __resourceQuery", function() { - if(!this.state.module) return; + if (!this.state.module) return; this.state.current.addVariable("__resourceQuery", JSON.stringify(this.state.module.splitQuery(this.state.module.resource)[1])); return true; }); }; - - diff --git a/lib/ContextModule.js b/lib/ContextModule.js index aeeb15c1e..01b070a13 100644 --- a/lib/ContextModule.js +++ b/lib/ContextModule.js @@ -24,11 +24,11 @@ ContextModule.prototype = Object.create(Module.prototype); ContextModule.prototype.identifier = function() { var identifier = ""; identifier += this.context + " "; - if(!this.recursive) + if (!this.recursive) identifier += "nonrecursive "; - if(this.addon) + if (this.addon) identifier += this.addon; - if(this.regExp) + if (this.regExp) identifier += this.regExp; return identifier.replace(/ $/, ""); }; @@ -40,18 +40,18 @@ function prettyRegExp(str) { ContextModule.prototype.readableIdentifier = function(requestShortener) { var identifier = ""; identifier += requestShortener.shorten(this.context) + " "; - if(!this.recursive) + if (!this.recursive) identifier += "nonrecursive "; - if(this.addon) + if (this.addon) identifier += requestShortener.shorten(this.addon); - if(this.regExp) + if (this.regExp) identifier += prettyRegExp(this.regExp + ""); return identifier.replace(/ $/, ""); }; ContextModule.prototype.needRebuild = function(fileTimestamps, contextTimestamps) { var ts = contextTimestamps[this.context]; - if(!ts) return true; + if (!ts) return true; return ts >= this.builtTime; }; @@ -65,8 +65,8 @@ ContextModule.prototype.build = function(options, compilation, resolver, fs, cal this.builtTime = new Date().getTime(); var addon = this.addon; this.resolveDependencies(fs, this.context, this.recursive, this.regExp, function(err, dependencies) { - if(err) return callback(err); - if(dependencies) { + if (err) return callback(err); + if (dependencies) { dependencies.forEach(function(dep) { dep.loc = dep.userRequest; dep.userRequest = dep.request; @@ -80,13 +80,13 @@ ContextModule.prototype.build = function(options, compilation, resolver, fs, cal ContextModule.prototype.source = function() { var str; - if(this.dependencies && this.dependencies.length > 0) { + if (this.dependencies && this.dependencies.length > 0) { var map = {}; this.dependencies.slice().sort(function(a, b) { - if(a.userRequest === b.userRequest) return 0; + if (a.userRequest === b.userRequest) return 0; return a.userRequest < b.userRequest ? -1 : 1; }).forEach(function(dep) { - if(dep.module) + if (dep.module) map[dep.userRequest] = dep.module.id; }); str = [ @@ -115,7 +115,7 @@ ContextModule.prototype.source = function() { "webpackContext.id = " + this.id + ";\n" ]; } - if(this.useSourceMap) { + if (this.useSourceMap) { return new OriginalSource(str.join(""), this.identifier()); } else { return new RawSource(str.join("")); @@ -125,5 +125,7 @@ ContextModule.prototype.source = function() { ContextModule.prototype.size = function() { return this.dependencies.map(function(dep) { return dep.userRequest.length + 5; - }).reduce(function(a, b) { return a + b; }, 160); + }).reduce(function(a, b) { + return a + b; + }, 160); }; diff --git a/lib/ContextModuleFactory.js b/lib/ContextModuleFactory.js index 2a4e02a29..f7d526f80 100644 --- a/lib/ContextModuleFactory.js +++ b/lib/ContextModuleFactory.js @@ -23,10 +23,10 @@ ContextModuleFactory.prototype.create = function(context, dependency, callback) recursive: dependency.recursive, regExp: dependency.regExp }, function(err, result) { - if(err) return callback(err); + if (err) return callback(err); // Ignored - if(!result) return callback(); + if (!result) return callback(); var context = result.context; var request = result.request; @@ -35,13 +35,13 @@ ContextModuleFactory.prototype.create = function(context, dependency, callback) var loaders, resource, loadersPrefix = ""; var idx = request.lastIndexOf("!"); - if(idx >= 0) { + if (idx >= 0) { loaders = request.substr(0, idx + 1); - for(var i = 0; i < loaders.length && loaders[i] === "!"; i++) { + for (var i = 0; i < loaders.length && loaders[i] === "!"; i++) { loadersPrefix += "!"; } loaders = loaders.substr(i).replace(/!+$/, "").replace(/!!+/g, "!"); - if(loaders === "") loaders = []; + if (loaders === "") loaders = []; else loaders = loaders.split("!"); resource = request.substr(idx + 1); } else { @@ -53,7 +53,7 @@ ContextModuleFactory.prototype.create = function(context, dependency, callback) this.resolvers.context.resolve.bind(this.resolvers.context, context, resource), async.map.bind(async, loaders, this.resolvers.loader.resolve.bind(this.resolvers.loader, context)) ], function(err, result) { - if(err) return callback(err); + if (err) return callback(err); this.applyPluginsAsyncWaterfall("after-resolve", { loaders: loadersPrefix + result[1].join("!") + (result[1].length > 0 ? "!" : ""), @@ -61,10 +61,10 @@ ContextModuleFactory.prototype.create = function(context, dependency, callback) recursive: recursive, regExp: regExp }, function(err, result) { - if(err) return callback(err); + if (err) return callback(err); // Ignored - if(!result) return callback(); + if (!result) return callback(); return callback(null, new ContextModule(this.resolveDependencies.bind(this), result.resource, result.recursive, result.regExp, result.loaders)); }.bind(this)); @@ -75,8 +75,8 @@ ContextModuleFactory.prototype.create = function(context, dependency, callback) ContextModuleFactory.prototype.resolveDependencies = function resolveDependencies(fs, resource, recursive, regExp, callback) { (function addDirectory(directory, callback) { fs.readdir(directory, function(err, files) { - if(err) return callback(err); - if(!files || files.length === 0) return callback(null, []); + if (err) return callback(err); + if (!files || files.length === 0) return callback(null, []); async.map(files.filter(function(p) { return p.indexOf(".") !== 0; }), function(seqment, callback) { @@ -84,21 +84,21 @@ ContextModuleFactory.prototype.resolveDependencies = function resolveDependencie var subResource = path.join(directory, seqment); fs.stat(subResource, function(err, stat) { - if(err) return callback(err); + if (err) return callback(err); - if(stat.isDirectory()) { + if (stat.isDirectory()) { - if(!recursive) return callback(); + if (!recursive) return callback(); addDirectory.call(this, subResource, callback); - } else if(stat.isFile()) { + } else if (stat.isFile()) { var obj = { context: resource, request: "." + subResource.substr(resource.length).replace(/\\/g, "/") }; this.applyPluginsAsyncWaterfall("alternatives", [obj], function(err, alternatives) { - if(err) return callback(err); + if (err) return callback(err); alternatives = alternatives.filter(function(obj) { return regExp.test(obj.request); }).map(function(obj) { @@ -114,11 +114,13 @@ ContextModuleFactory.prototype.resolveDependencies = function resolveDependencie }.bind(this)); }.bind(this), function(err, result) { - if(err) return callback(err); + if (err) return callback(err); - if(!result) return callback(null, []); + if (!result) return callback(null, []); - callback(null, result.filter(function(i) { return !!i; }).reduce(function(a, i) { + callback(null, result.filter(function(i) { + return !!i; + }).reduce(function(a, i) { return a.concat(i); }, [])); }); diff --git a/lib/ContextReplacementPlugin.js b/lib/ContextReplacementPlugin.js index cadc1cf73..ee23ea925 100644 --- a/lib/ContextReplacementPlugin.js +++ b/lib/ContextReplacementPlugin.js @@ -6,15 +6,15 @@ var path = require("path"); function ContextReplacementPlugin(resourceRegExp, newContentResource, newContentRecursive, newContentRegExp) { this.resourceRegExp = resourceRegExp; - if(typeof newContentResource === "function") { + if (typeof newContentResource === "function") { this.newContentCallback = newContentResource; } else { - if(typeof newContentResource !== "string") { + if (typeof newContentResource !== "string") { newContentRegExp = newContentRecursive; newContentRecursive = newContentResource; newContentResource = undefined; } - if(typeof newContentRecursive !== "boolean") { + if (typeof newContentRecursive !== "boolean") { newContentRegExp = newContentRecursive; newContentRecursive = undefined; } @@ -32,36 +32,36 @@ ContextReplacementPlugin.prototype.apply = function(compiler) { var newContentRegExp = this.newContentRegExp; compiler.plugin("context-module-factory", function(cmf) { cmf.plugin("before-resolve", function(result, callback) { - if(!result) return callback(); - if(resourceRegExp.test(result.request)) { - if(typeof newContentCallback === "function") { + if (!result) return callback(); + if (resourceRegExp.test(result.request)) { + if (typeof newContentCallback === "function") { newContentCallback(result); } else { - 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; } } return callback(null, result); }); cmf.plugin("after-resolve", function(result, callback) { - if(!result) return callback(); - if(resourceRegExp.test(result.resource)) { - if(typeof newContentCallback === "function") { + if (!result) return callback(); + if (resourceRegExp.test(result.resource)) { + if (typeof newContentCallback === "function") { var origResource = result.resource; newContentCallback(result); if (result.resource !== origResource) { result.resource = path.resolve(origResource, result.resource); } } else { - 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; } } diff --git a/lib/CriticalDependenciesWarning.js b/lib/CriticalDependenciesWarning.js index c5c09e821..03061e395 100644 --- a/lib/CriticalDependenciesWarning.js +++ b/lib/CriticalDependenciesWarning.js @@ -11,9 +11,9 @@ function CriticalDependenciesWarning(module, dependencies) { return typeof d.critical === "string" || d.loc; }).map(function(dep) { var line = []; - if(dep.loc) line.push(dep.loc.start.line + ":" + dep.loc.start.column + "-" + + if (dep.loc) line.push(dep.loc.start.line + ":" + dep.loc.start.column + "-" + (dep.loc.start.line !== dep.loc.end.line ? dep.loc.end.line + ":" : "") + dep.loc.end.column); - if(typeof dep.critical === "string") line.push(dep.critical); + if (typeof dep.critical === "string") line.push(dep.critical); return "\n" + line.join(" "); }).join(""); this.dependencies = dependencies; diff --git a/lib/DefinePlugin.js b/lib/DefinePlugin.js index 1dd5b8af8..95b15c3b8 100644 --- a/lib/DefinePlugin.js +++ b/lib/DefinePlugin.js @@ -19,7 +19,7 @@ DefinePlugin.prototype.apply = function(compiler) { (function walkDefinitions(definitions, prefix) { Object.keys(definitions).forEach(function(key) { var code = definitions[key]; - if(code && typeof code === "object" && !(code instanceof RegExp)) { + if (code && typeof code === "object" && !(code instanceof RegExp)) { walkDefinitions(code, prefix + key + "."); applyObjectDefine(prefix + key, code); return; @@ -28,39 +28,45 @@ DefinePlugin.prototype.apply = function(compiler) { applyDefine(prefix + key, code); }); }(this.definitions, "")); + function stringifyObj(obj) { return "{" + Object.keys(obj).map(function(key) { var code = obj[key]; return JSON.stringify(key) + ":" + toCode(code); }).join(",") + "}"; } + function 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) return code.toString(); - else if(typeof code === "object") return stringifyObj(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) return code.toString(); + else if (typeof code === "object") return stringifyObj(code); else return code + ""; } + function applyDefineKey(prefix, key) { var splittedKey = key.split("."); splittedKey.slice(1).forEach(function(_, i) { var fullKey = prefix + splittedKey.slice(0, i + 1).join("."); - compiler.parser.plugin("can-rename " + fullKey, function() { return true; }); + compiler.parser.plugin("can-rename " + fullKey, function() { + return true; + }); }); } + function applyDefine(key, code) { var isTypeof = /^typeof\s+/.test(key); - if(isTypeof) key = key.replace(/^typeof\s+/, ""); + if (isTypeof) key = key.replace(/^typeof\s+/, ""); var recurse = false; var recurseTypeof = false; code = toCode(code); - if(!isTypeof) { + if (!isTypeof) { compiler.parser.plugin("can-rename " + key, function() { return true; }); compiler.parser.plugin("evaluate Identifier " + key, function(expr) { - if(recurse) return; + if (recurse) return; recurse = true; var res = compiler.parser.evaluate(code); recurse = false; @@ -76,7 +82,7 @@ DefinePlugin.prototype.apply = function(compiler) { } var typeofCode = isTypeof ? code : "typeof (" + code + ")"; compiler.parser.plugin("evaluate typeof " + key, function(expr) { - if(recurseTypeof) return; + if (recurseTypeof) return; recurseTypeof = true; var res = compiler.parser.evaluate(typeofCode); recurseTypeof = false; @@ -85,13 +91,14 @@ DefinePlugin.prototype.apply = function(compiler) { }); compiler.parser.plugin("typeof " + key, function(expr) { var res = compiler.parser.evaluate(typeofCode); - if(!res.isString()) return; + if (!res.isString()) return; var dep = new ConstDependency(JSON.stringify(res.string), expr.range); dep.loc = expr.loc; this.state.current.addDependency(dep); return true; }); } + function applyObjectDefine(key, obj) { var code = stringifyObj(obj); compiler.parser.plugin("can-rename " + key, function() { diff --git a/lib/DelegatedModule.js b/lib/DelegatedModule.js index 263c075c2..7949c339b 100644 --- a/lib/DelegatedModule.js +++ b/lib/DelegatedModule.js @@ -44,11 +44,11 @@ DelegatedModule.prototype.build = function(options, compilation, resolver, fs, c DelegatedModule.prototype.source = function() { var sourceModule = this.dependencies[0].module; var str; - if(!sourceModule) { + if (!sourceModule) { str = WebpackMissingModule.moduleCode(this.sourceRequest); } else { str = "module.exports = (__webpack_require__(" + sourceModule.id + "))"; - switch(this.type) { + switch (this.type) { case "require": str += "(" + JSON.stringify(this.request) + ");"; break; @@ -57,7 +57,7 @@ DelegatedModule.prototype.source = function() { break; } } - if(this.useSourceMap) { + if (this.useSourceMap) { return new OriginalSource(str, this.identifier()); } else { return new RawSource(str); diff --git a/lib/DelegatedModuleFactoryPlugin.js b/lib/DelegatedModuleFactoryPlugin.js index 0cbc67a97..93c40694f 100644 --- a/lib/DelegatedModuleFactoryPlugin.js +++ b/lib/DelegatedModuleFactoryPlugin.js @@ -18,16 +18,16 @@ module.exports = DelegatedModuleFactoryPlugin; DelegatedModuleFactoryPlugin.prototype.apply = function(normalModuleFactory) { var scope = this.options.scope; - if(scope) { + if (scope) { normalModuleFactory.plugin("factory", function(factory) { return function(data, callback) { var dependency = data.dependency; var request = dependency.request; - if(request && request.indexOf(scope + "/") === 0) { + if (request && request.indexOf(scope + "/") === 0) { var innerRequest = "." + request.substr(scope.length); - for(var i = 0; i < this.options.extensions.length; i++) { + for (var i = 0; i < this.options.extensions.length; i++) { var requestPlusExt = innerRequest + this.options.extensions[i]; - if(requestPlusExt in this.options.content) { + if (requestPlusExt in this.options.content) { var resolved = this.options.content[requestPlusExt]; return callback(null, new DelegatedModule(this.options.source, resolved, this.options.type, requestPlusExt)); } @@ -38,9 +38,9 @@ DelegatedModuleFactoryPlugin.prototype.apply = function(normalModuleFactory) { }.bind(this)); } else { normalModuleFactory.plugin("module", function(module) { - if(module.libIdent) { + if (module.libIdent) { var request = module.libIdent(this.options); - if(request && request in this.options.content) { + if (request && request in this.options.content) { var resolved = this.options.content[request]; return new DelegatedModule(this.options.source, resolved, this.options.type, request); } diff --git a/lib/DependenciesBlock.js b/lib/DependenciesBlock.js index cac9965e5..bcacdc328 100644 --- a/lib/DependenciesBlock.js +++ b/lib/DependenciesBlock.js @@ -17,9 +17,9 @@ DependenciesBlock.prototype.addBlock = function(block) { }; DependenciesBlock.prototype.addVariable = function(name, expression, dependencies) { - for(var i = 0; i < this.variables.length; i++) { + for (var i = 0; i < this.variables.length; i++) { var v = this.variables[i]; - if(v.name === name && v.expression === expression) return; + if (v.name === name && v.expression === expression) return; } this.variables.push(new DependenciesBlockVariable(name, expression, dependencies)); }; diff --git a/lib/DependenciesBlockVariable.js b/lib/DependenciesBlockVariable.js index 56eb15c03..fe92b6a60 100644 --- a/lib/DependenciesBlockVariable.js +++ b/lib/DependenciesBlockVariable.js @@ -24,7 +24,7 @@ DependenciesBlockVariable.prototype.expressionSource = function(dependencyTempla var source = new ReplaceSource(new RawSource(this.expression)); this.dependencies.forEach(function(dep) { var template = dependencyTemplates.get(dep.Class); - if(!template) throw new Error("No template for dependency: " + dep.Class.name); + if (!template) throw new Error("No template for dependency: " + dep.Class.name); template.apply(dep, source, outputOptions, requestShortener, dependencyTemplates); }); return source; diff --git a/lib/Dependency.js b/lib/Dependency.js index 76fcf3e09..35b169802 100644 --- a/lib/Dependency.js +++ b/lib/Dependency.js @@ -8,7 +8,7 @@ function Dependency() { } module.exports = Dependency; -Dependency.prototype.isEqualResource = function(/* other */) { +Dependency.prototype.isEqualResource = function( /* other */ ) { return false; }; @@ -25,26 +25,26 @@ Dependency.compare = function(a, b) { }; Dependency.compareLocations = function(a, b) { - if(typeof a === "string") { - if(typeof b === "string") { - if(a < b) return -1; - if(a > b) return 1; + if (typeof a === "string") { + if (typeof b === "string") { + if (a < b) return -1; + if (a > b) return 1; return 0; - } else if(typeof b === "object") { + } else if (typeof b === "object") { return 1; } else { return 0; } - } else if(typeof a === "object") { - if(typeof b === "string") { + } else if (typeof a === "object") { + if (typeof b === "string") { return -1; - } else if(typeof b === "object") { - if(a.line < b.line) return -1; - if(a.line > b.line) return 1; - if(a.column < b.column) return -1; - if(a.column > b.column) return 1; - if(a.index < b.index) return -1; - if(a.index > b.index) return 1; + } else if (typeof b === "object") { + if (a.line < b.line) return -1; + if (a.line > b.line) return 1; + if (a.column < b.column) return -1; + if (a.column > b.column) return 1; + if (a.index < b.index) return -1; + if (a.index > b.index) return 1; return 0; } else { return 0; diff --git a/lib/DllPlugin.js b/lib/DllPlugin.js index 4d207f408..a86d2c029 100644 --- a/lib/DllPlugin.js +++ b/lib/DllPlugin.js @@ -12,12 +12,12 @@ module.exports = DllPlugin; DllPlugin.prototype.apply = function(compiler) { compiler.plugin("entry-option", function(context, entry) { function itemToPlugin(item, name) { - if(Array.isArray(item)) + if (Array.isArray(item)) return new DllEntryPlugin(context, item, name); else throw new Error("DllPlugin: supply an Array as entry"); } - if(typeof entry === "object") { + if (typeof entry === "object") { Object.keys(entry).forEach(function(name) { compiler.apply(itemToPlugin(entry[name], name)); }); diff --git a/lib/EntryOptionPlugin.js b/lib/EntryOptionPlugin.js index 688529c83..fac60e81f 100644 --- a/lib/EntryOptionPlugin.js +++ b/lib/EntryOptionPlugin.js @@ -11,14 +11,14 @@ module.exports = EntryOptionPlugin; EntryOptionPlugin.prototype.apply = function(compiler) { compiler.plugin("entry-option", function(context, entry) { function itemToPlugin(item, name) { - if(Array.isArray(item)) + if (Array.isArray(item)) return new MultiEntryPlugin(context, item, name); else return new SingleEntryPlugin(context, item, name); } - if(typeof entry === "string" || Array.isArray(entry)) { + if (typeof entry === "string" || Array.isArray(entry)) { compiler.apply(itemToPlugin(entry, "main")); - } else if(typeof entry === "object") { + } else if (typeof entry === "object") { Object.keys(entry).forEach(function(name) { compiler.apply(itemToPlugin(entry[name], name)); }); diff --git a/lib/EvalDevToolModulePlugin.js b/lib/EvalDevToolModulePlugin.js index 740720de9..86101f1cb 100644 --- a/lib/EvalDevToolModulePlugin.js +++ b/lib/EvalDevToolModulePlugin.js @@ -15,4 +15,3 @@ EvalDevToolModulePlugin.prototype.apply = function(compiler) { compilation.moduleTemplate.apply(new EvalDevToolModuleTemplatePlugin(self.sourceUrlComment, self.moduleFilenameTemplate)); }); }; - diff --git a/lib/EvalDevToolModuleTemplatePlugin.js b/lib/EvalDevToolModuleTemplatePlugin.js index 0e0541507..a8ebee80c 100644 --- a/lib/EvalDevToolModuleTemplatePlugin.js +++ b/lib/EvalDevToolModuleTemplatePlugin.js @@ -20,7 +20,7 @@ EvalDevToolModuleTemplatePlugin.prototype.apply = function(moduleTemplate) { ModuleFilenameHelpers.createFooter(module, this.requestShortener), self.sourceUrlComment.replace(/\[url\]/g, encodeURI(str).replace(/%2F/g, "/").replace(/%20/g, "_").replace(/%5E/g, "^").replace(/%5C/g, "\\").replace(/^\//, "")) ].join("\n"); - return new RawSource("eval(" + JSON.stringify(content + footer) + ");" ); + return new RawSource("eval(" + JSON.stringify(content + footer) + ");"); }); moduleTemplate.plugin("hash", function(hash) { hash.update("EvalDevToolModuleTemplatePlugin"); diff --git a/lib/EvalSourceMapDevToolModuleTemplatePlugin.js b/lib/EvalSourceMapDevToolModuleTemplatePlugin.js index 7c509b311..bfb5e7cba 100644 --- a/lib/EvalSourceMapDevToolModuleTemplatePlugin.js +++ b/lib/EvalSourceMapDevToolModuleTemplatePlugin.js @@ -17,10 +17,10 @@ EvalSourceMapDevToolModuleTemplatePlugin.prototype.apply = function(moduleTempla var self = this; var options = this.options; moduleTemplate.plugin("module", function(source, module) { - if(source.__EvalSourceMapDevToolData) + if (source.__EvalSourceMapDevToolData) return source.__EvalSourceMapDevToolData; - if(source.sourceAndMap) { + if (source.sourceAndMap) { var sourceAndMap = source.sourceAndMap(options); var sourceMap = sourceAndMap.map; var content = sourceAndMap.source; @@ -28,7 +28,7 @@ EvalSourceMapDevToolModuleTemplatePlugin.prototype.apply = function(moduleTempla var sourceMap = source.map(options); var content = source.source(); } - if(!sourceMap) { + if (!sourceMap) { return source; } @@ -45,12 +45,12 @@ EvalSourceMapDevToolModuleTemplatePlugin.prototype.apply = function(moduleTempla return ModuleFilenameHelpers.createFilename(module, self.moduleFilenameTemplate, this.requestShortener); }, this); moduleFilenames = ModuleFilenameHelpers.replaceDuplicates(moduleFilenames, function(filename, i, n) { - for(var j = 0; j < n; j++) + for (var j = 0; j < n; j++) filename += "*"; return filename; }); sourceMap.sources = moduleFilenames; - if(sourceMap.sourcesContent) { + if (sourceMap.sourcesContent) { sourceMap.sourcesContent = sourceMap.sourcesContent.map(function(content, i) { return content + "\n\n\n" + ModuleFilenameHelpers.createFooter(modules[i], this.requestShortener); }, this); @@ -58,7 +58,7 @@ EvalSourceMapDevToolModuleTemplatePlugin.prototype.apply = function(moduleTempla sourceMap.sourceRoot = ""; sourceMap.file = module.id + ".js"; var footer = self.sourceMapComment.replace(/\[url\]/g, "data:application/json;base64," + new Buffer(JSON.stringify(sourceMap)).toString("base64")); - source.__EvalSourceMapDevToolData = new RawSource("eval(" + JSON.stringify(content + footer) + ");" ); + source.__EvalSourceMapDevToolData = new RawSource("eval(" + JSON.stringify(content + footer) + ");"); return source.__EvalSourceMapDevToolData; }); moduleTemplate.plugin("hash", function(hash) { diff --git a/lib/EvalSourceMapDevToolPlugin.js b/lib/EvalSourceMapDevToolPlugin.js index 37963264d..dedadf15c 100644 --- a/lib/EvalSourceMapDevToolPlugin.js +++ b/lib/EvalSourceMapDevToolPlugin.js @@ -6,7 +6,7 @@ var EvalSourceMapDevToolModuleTemplatePlugin = require("./EvalSourceMapDevToolMo var SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin"); function EvalSourceMapDevToolPlugin(options, moduleFilenameTemplate) { - if(!options || typeof options !== "object") { + if (!options || typeof options !== "object") { this.options = { append: options, moduleFilenameTemplate: moduleFilenameTemplate diff --git a/lib/ExtendedAPIPlugin.js b/lib/ExtendedAPIPlugin.js index a6df94383..a914545ad 100644 --- a/lib/ExtendedAPIPlugin.js +++ b/lib/ExtendedAPIPlugin.js @@ -7,8 +7,7 @@ var BasicEvaluatedExpression = require("./BasicEvaluatedExpression"); var NullFactory = require("./NullFactory"); -function ExtendedAPIPlugin() { -} +function ExtendedAPIPlugin() {} module.exports = ExtendedAPIPlugin; var REPLACEMENTS = { diff --git a/lib/ExternalModule.js b/lib/ExternalModule.js index e59e4f04f..4e4ec3f5d 100644 --- a/lib/ExternalModule.js +++ b/lib/ExternalModule.js @@ -39,12 +39,12 @@ ExternalModule.prototype.build = function(options, compilation, resolver, fs, ca ExternalModule.prototype.source = function() { var str = "throw new Error('Externals not supported');"; var request = this.request; - if(typeof request === "object") request = request[this.type]; - switch(this.type) { + if (typeof request === "object") request = request[this.type]; + switch (this.type) { case "this": case "window": case "global": - if(Array.isArray(request)) { + if (Array.isArray(request)) { str = "(function() { module.exports = " + this.type + request.map(function(r) { return "[" + JSON.stringify(r) + "]"; }).join("") + "; }());"; @@ -53,7 +53,7 @@ ExternalModule.prototype.source = function() { break; case "commonjs": case "commonjs2": - if(Array.isArray(request)) { + if (Array.isArray(request)) { str = "module.exports = require(" + JSON.stringify(request[0]) + ")" + request.slice(1).map(function(r) { return "[" + JSON.stringify(r) + "]"; }).join("") + ";"; @@ -64,20 +64,20 @@ ExternalModule.prototype.source = function() { case "umd": case "umd2": str = ""; - if(this.optional) { + if (this.optional) { str += "if(typeof __WEBPACK_EXTERNAL_MODULE_" + this.id + "__ === 'undefined') {" + WebpackMissingModule.moduleCode(request) + "}\n"; } str += "module.exports = __WEBPACK_EXTERNAL_MODULE_" + this.id + "__;"; break; default: str = ""; - if(this.optional) { + if (this.optional) { str += "if(typeof " + request + " === 'undefined') {" + WebpackMissingModule.moduleCode(request) + "}\n"; } str += "module.exports = " + request + ";"; break; } - if(this.useSourceMap) { + if (this.useSourceMap) { return new OriginalSource(str, this.identifier()); } else { return new RawSource(str); diff --git a/lib/ExternalModuleFactoryPlugin.js b/lib/ExternalModuleFactoryPlugin.js index 27433b3ab..9ce630931 100644 --- a/lib/ExternalModuleFactoryPlugin.js +++ b/lib/ExternalModuleFactoryPlugin.js @@ -16,14 +16,15 @@ ExternalModuleFactoryPlugin.prototype.apply = function(normalModuleFactory) { return function(data, callback) { var context = data.context; var dependency = data.dependency; + function handleExternal(value, type, callback) { - if(typeof type === "function") { + if (typeof type === "function") { callback = type; type = undefined; } - if(value === false) return factory(data, callback); - if(value === true) value = dependency.request; - if(typeof type === "undefined" && /^[a-z0-9]+ /.test(value)) { + if (value === false) return factory(data, callback); + if (value === true) value = dependency.request; + if (typeof type === "undefined" && /^[a-z0-9]+ /.test(value)) { var idx = value.indexOf(" "); type = value.substr(0, idx); value = value.substr(idx + 1); @@ -32,20 +33,20 @@ ExternalModuleFactoryPlugin.prototype.apply = function(normalModuleFactory) { return true; } (function handleExternals(externals, callback) { - if(typeof externals === "string") { - if(externals === dependency.request) { + if (typeof externals === "string") { + if (externals === dependency.request) { return handleExternal(dependency.request, callback); } - } else if(Array.isArray(externals)) { + } else if (Array.isArray(externals)) { var i = 0; (function next() { do { var async = true; - if(i >= externals.length) return callback(); + if (i >= externals.length) return callback(); handleExternals(externals[i++], function(err, module) { - if(err) return callback(err); - if(!module) { - if(async) { + if (err) return callback(err); + if (!module) { + if (async) { async = false; return; } @@ -53,31 +54,31 @@ ExternalModuleFactoryPlugin.prototype.apply = function(normalModuleFactory) { } callback(null, module); }); - } while(!async); + } while (!async); async = false; }()); return; - } else if(externals instanceof RegExp) { - if(externals.test(dependency.request)) { + } else if (externals instanceof RegExp) { + if (externals.test(dependency.request)) { return handleExternal(dependency.request, callback); } - } else if(typeof externals === "function") { + } else if (typeof externals === "function") { externals.call(null, context, dependency.request, function(err, value, type) { - if(err) return callback(err); - if(typeof value !== "undefined") { + if (err) return callback(err); + if (typeof value !== "undefined") { handleExternal(value, type, callback); } else { callback(); } }); return; - } else if(typeof externals === "object" && Object.prototype.hasOwnProperty.call(externals, dependency.request)) { + } else if (typeof externals === "object" && Object.prototype.hasOwnProperty.call(externals, dependency.request)) { return handleExternal(externals[dependency.request], callback); } callback(); }(this.externals, function(err, module) { - if(err) return callback(err); - if(!module) return handleExternal(false, callback); + if (err) return callback(err); + if (!module) return handleExternal(false, callback); return callback(null, module); })); }.bind(this); diff --git a/lib/FunctionModuleTemplatePlugin.js b/lib/FunctionModuleTemplatePlugin.js index 3b225745d..3167d75ed 100644 --- a/lib/FunctionModuleTemplatePlugin.js +++ b/lib/FunctionModuleTemplatePlugin.js @@ -5,15 +5,14 @@ var ConcatSource = require("webpack-core/lib/ConcatSource"); var PrefixSource = require("webpack-core/lib/PrefixSource"); -function FunctionModuleTemplatePlugin() { -} +function FunctionModuleTemplatePlugin() {} module.exports = FunctionModuleTemplatePlugin; FunctionModuleTemplatePlugin.prototype.apply = function(moduleTemplate) { moduleTemplate.plugin("render", function(moduleSource, module) { var source = new ConcatSource(); var defaultArguments = ["module", "exports"]; - if((module.arguments && module.arguments.length !== 0) || module.hasDependencies()) { + if ((module.arguments && module.arguments.length !== 0) || module.hasDependencies()) { defaultArguments.push("__webpack_require__"); } source.add("/***/ function(" + defaultArguments.concat(module.arguments || []).join(", ") + ") {\n\n"); @@ -22,7 +21,7 @@ FunctionModuleTemplatePlugin.prototype.apply = function(moduleTemplate) { return source; }); moduleTemplate.plugin("package", function(moduleSource, module) { - if(this.outputOptions.pathinfo) { + if (this.outputOptions.pathinfo) { var source = new ConcatSource(); var req = module.readableIdentifier(this.requestShortener); source.add("/*!****" + req.replace(/./g, "*") + "****!*\\\n"); diff --git a/lib/HotModuleReplacement.runtime.js b/lib/HotModuleReplacement.runtime.js index 25de4d403..a4db73f82 100644 --- a/lib/HotModuleReplacement.runtime.js +++ b/lib/HotModuleReplacement.runtime.js @@ -12,13 +12,13 @@ module.exports = function() { function hotCreateRequire(moduleId) { // eslint-disable-line no-unused-vars var me = installedModules[moduleId]; - if(!me) return $require$; + if (!me) return $require$; var fn = function(request) { - if(me.hot.active) { - if(installedModules[request]) { - if(installedModules[request].parents.indexOf(moduleId) < 0) + if (me.hot.active) { + if (installedModules[request]) { + if (installedModules[request].parents.indexOf(moduleId) < 0) installedModules[request].parents.push(moduleId); - if(me.children.indexOf(request) < 0) + if (me.children.indexOf(request) < 0) me.children.push(request); } else hotCurrentParents = [moduleId]; } else { @@ -27,13 +27,13 @@ module.exports = function() { } return $require$(request); }; - for(var name in $require$) { - if(Object.prototype.hasOwnProperty.call($require$, name)) { + for (var name in $require$) { + if (Object.prototype.hasOwnProperty.call($require$, name)) { fn[name] = $require$[name]; } } fn.e = function(chunkId, callback) { - if(hotStatus === "ready") + if (hotStatus === "ready") hotSetStatus("prepare"); hotChunksLoading++; $require$.e(chunkId, function() { @@ -42,13 +42,14 @@ module.exports = function() { } finally { finishChunkLoading(); } + function finishChunkLoading() { hotChunksLoading--; - if(hotStatus === "prepare") { - if(!hotWaitingFilesMap[chunkId]) { + if (hotStatus === "prepare") { + if (!hotWaitingFilesMap[chunkId]) { hotEnsureUpdateChunk(chunkId); } - if(hotChunksLoading === 0 && hotWaitingFiles === 0) { + if (hotChunksLoading === 0 && hotWaitingFiles === 0) { hotUpdateDownloaded(); } } @@ -70,23 +71,24 @@ module.exports = function() { // Module API active: true, accept: function(dep, callback) { - if(typeof dep === "undefined") + if (typeof dep === "undefined") hot._selfAccepted = true; - else if(typeof dep === "function") + else if (typeof dep === "function") hot._selfAccepted = dep; - else if(typeof dep === "object") - for(var i = 0; i < dep.length; i++) - hot._acceptedDependencies[dep[i]] = callback; + else if (typeof dep === "object") + for (var i = 0; i < dep.length; i++) + hot._acceptedDependencies[dep[i]] = callback; else hot._acceptedDependencies[dep] = callback; }, decline: function(dep) { - if(typeof dep === "undefined") + if (typeof dep === "undefined") hot._selfDeclined = true; - else if(typeof dep === "number") + else if (typeof dep === "number") hot._declinedDependencies[dep] = true; - else for(var i = 0; i < dep.length; i++) - hot._declinedDependencies[dep[i]] = true; + else + for (var i = 0; i < dep.length; i++) + hot._declinedDependencies[dep[i]] = true; }, dispose: function(callback) { hot._disposeHandlers.push(callback); @@ -96,14 +98,14 @@ module.exports = function() { }, removeDisposeHandler: function(callback) { var idx = hot._disposeHandlers.indexOf(callback); - if(idx >= 0) hot._disposeHandlers.splice(idx, 1); + if (idx >= 0) hot._disposeHandlers.splice(idx, 1); }, // Management API check: hotCheck, apply: hotApply, status: function(l) { - if(!l) return hotStatus; + if (!l) return hotStatus; hotStatusHandlers.push(l); }, addStatusHandler: function(l) { @@ -111,7 +113,7 @@ module.exports = function() { }, removeStatusHandler: function(l) { var idx = hotStatusHandlers.indexOf(l); - if(idx >= 0) hotStatusHandlers.splice(idx, 1); + if (idx >= 0) hotStatusHandlers.splice(idx, 1); }, //inherit from previous dispose call @@ -125,7 +127,7 @@ module.exports = function() { function hotSetStatus(newStatus) { hotStatus = newStatus; - for(var i = 0; i < hotStatusHandlers.length; i++) + for (var i = 0; i < hotStatusHandlers.length; i++) hotStatusHandlers[i].call(null, newStatus); } @@ -145,18 +147,20 @@ module.exports = function() { } function hotCheck(apply, callback) { - if(hotStatus !== "idle") throw new Error("check() is only allowed in idle status"); - if(typeof apply === "function") { + if (hotStatus !== "idle") throw new Error("check() is only allowed in idle status"); + if (typeof apply === "function") { hotApplyOnUpdate = false; callback = apply; } else { hotApplyOnUpdate = apply; - callback = callback || function(err) { if(err) throw err; }; + callback = callback || function(err) { + if (err) throw err; + }; } hotSetStatus("check"); hotDownloadManifest(function(err, update) { - if(err) return callback(err); - if(!update) { + if (err) return callback(err); + if (!update) { hotSetStatus("idle"); callback(null, null); return; @@ -165,39 +169,40 @@ module.exports = function() { hotRequestedFilesMap = {}; hotAvailibleFilesMap = {}; hotWaitingFilesMap = {}; - for(var i = 0; i < update.c.length; i++) + for (var i = 0; i < update.c.length; i++) hotAvailibleFilesMap[update.c[i]] = true; hotUpdateNewHash = update.h; hotSetStatus("prepare"); hotCallback = callback; hotUpdate = {}; - /*foreachInstalledChunks*/ { // eslint-disable-line no-lone-blocks + /*foreachInstalledChunks*/ + { // eslint-disable-line no-lone-blocks /*globals chunkId */ hotEnsureUpdateChunk(chunkId); } - if(hotStatus === "prepare" && hotChunksLoading === 0 && hotWaitingFiles === 0) { + if (hotStatus === "prepare" && hotChunksLoading === 0 && hotWaitingFiles === 0) { hotUpdateDownloaded(); } }); } function hotAddUpdateChunk(chunkId, moreModules) { // eslint-disable-line no-unused-vars - if(!hotAvailibleFilesMap[chunkId] || !hotRequestedFilesMap[chunkId]) + if (!hotAvailibleFilesMap[chunkId] || !hotRequestedFilesMap[chunkId]) return; hotRequestedFilesMap[chunkId] = false; - for(var moduleId in moreModules) { - if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { + for (var moduleId in moreModules) { + if (Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { hotUpdate[moduleId] = moreModules[moduleId]; } } - if(--hotWaitingFiles === 0 && hotChunksLoading === 0) { + if (--hotWaitingFiles === 0 && hotChunksLoading === 0) { hotUpdateDownloaded(); } } function hotEnsureUpdateChunk(chunkId) { - if(!hotAvailibleFilesMap[chunkId]) { + if (!hotAvailibleFilesMap[chunkId]) { hotWaitingFilesMap[chunkId] = true; } else { hotRequestedFilesMap[chunkId] = true; @@ -210,13 +215,13 @@ module.exports = function() { hotSetStatus("ready"); var callback = hotCallback; hotCallback = null; - if(!callback) return; - if(hotApplyOnUpdate) { + if (!callback) return; + if (hotApplyOnUpdate) { hotApply(hotApplyOnUpdate, callback); } else { var outdatedModules = []; - for(var id in hotUpdate) { - if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) { + for (var id in hotUpdate) { + if (Object.prototype.hasOwnProperty.call(hotUpdate, id)) { outdatedModules.push(toModuleId(id)); } } @@ -225,15 +230,19 @@ module.exports = function() { } function hotApply(options, callback) { - if(hotStatus !== "ready") throw new Error("apply() is only allowed in ready status"); - if(typeof options === "function") { + if (hotStatus !== "ready") throw new Error("apply() is only allowed in ready status"); + if (typeof options === "function") { callback = options; options = {}; - } else if(options && typeof options === "object") { - callback = callback || function(err) { if(err) throw err; }; + } else if (options && typeof options === "object") { + callback = callback || function(err) { + if (err) throw err; + }; } else { options = {}; - callback = callback || function(err) { if(err) throw err; }; + callback = callback || function(err) { + if (err) throw err; + }; } function getAffectedStuff(module) { @@ -241,26 +250,26 @@ module.exports = function() { var outdatedDependencies = {}; var queue = outdatedModules.slice(); - while(queue.length > 0) { + while (queue.length > 0) { var moduleId = queue.pop(); var module = installedModules[moduleId]; - if(!module || module.hot._selfAccepted) + if (!module || module.hot._selfAccepted) continue; - if(module.hot._selfDeclined) { + if (module.hot._selfDeclined) { return new Error("Aborted because of self decline: " + moduleId); } - if(moduleId === 0) { + if (moduleId === 0) { return; } - for(var i = 0; i < module.parents.length; i++) { + for (var i = 0; i < module.parents.length; i++) { var parentId = module.parents[i]; var parent = installedModules[parentId]; - if(parent.hot._declinedDependencies[moduleId]) { + if (parent.hot._declinedDependencies[moduleId]) { return new Error("Aborted because of declined dependency: " + moduleId + " in " + parentId); } - if(outdatedModules.indexOf(parentId) >= 0) continue; - if(parent.hot._acceptedDependencies[moduleId]) { - if(!outdatedDependencies[parentId]) + if (outdatedModules.indexOf(parentId) >= 0) continue; + if (parent.hot._acceptedDependencies[moduleId]) { + if (!outdatedDependencies[parentId]) outdatedDependencies[parentId] = []; addAllToSet(outdatedDependencies[parentId], [moduleId]); continue; @@ -273,10 +282,11 @@ module.exports = function() { return [outdatedModules, outdatedDependencies]; } + function addAllToSet(a, b) { - for(var i = 0; i < b.length; i++) { + for (var i = 0; i < b.length; i++) { var item = b[i]; - if(a.indexOf(item) < 0) + if (a.indexOf(item) < 0) a.push(item); } } @@ -286,25 +296,25 @@ module.exports = function() { var outdatedDependencies = {}; var outdatedModules = []; var appliedUpdate = {}; - for(var id in hotUpdate) { - if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) { + for (var id in hotUpdate) { + if (Object.prototype.hasOwnProperty.call(hotUpdate, id)) { var moduleId = toModuleId(id); var result = getAffectedStuff(moduleId); - if(!result) { - if(options.ignoreUnaccepted) + if (!result) { + if (options.ignoreUnaccepted) continue; hotSetStatus("abort"); return callback(new Error("Aborted because " + moduleId + " is not accepted")); } - if(result instanceof Error) { + if (result instanceof Error) { hotSetStatus("abort"); return callback(result); } appliedUpdate[moduleId] = hotUpdate[moduleId]; addAllToSet(outdatedModules, result[0]); - for(var moduleId in result[1]) { - if(Object.prototype.hasOwnProperty.call(result[1], moduleId)) { - if(!outdatedDependencies[moduleId]) + for (var moduleId in result[1]) { + if (Object.prototype.hasOwnProperty.call(result[1], moduleId)) { + if (!outdatedDependencies[moduleId]) outdatedDependencies[moduleId] = []; addAllToSet(outdatedDependencies[moduleId], result[1][moduleId]); } @@ -314,9 +324,9 @@ module.exports = function() { // Store self accepted outdated modules to require them later by the module system var outdatedSelfAcceptedModules = []; - for(var i = 0; i < outdatedModules.length; i++) { + for (var i = 0; i < outdatedModules.length; i++) { var moduleId = outdatedModules[i]; - if(installedModules[moduleId] && installedModules[moduleId].hot._selfAccepted) + if (installedModules[moduleId] && installedModules[moduleId].hot._selfAccepted) outdatedSelfAcceptedModules.push({ module: moduleId, errorHandler: installedModules[moduleId].hot._selfAccepted @@ -326,16 +336,16 @@ module.exports = function() { // Now in "dispose" phase hotSetStatus("dispose"); var queue = outdatedModules.slice(); - while(queue.length > 0) { + while (queue.length > 0) { var moduleId = queue.pop(); var module = installedModules[moduleId]; - if(!module) continue; + if (!module) continue; var data = {}; // Call dispose handlers var disposeHandlers = module.hot._disposeHandlers; - for(var j = 0; j < disposeHandlers.length; j++) { + for (var j = 0; j < disposeHandlers.length; j++) { var cb = disposeHandlers[j]; cb(data); } @@ -348,25 +358,25 @@ module.exports = function() { delete installedModules[moduleId]; // remove "parents" references from all children - for(var j = 0; j < module.children.length; j++) { + for (var j = 0; j < module.children.length; j++) { var child = installedModules[module.children[j]]; - if(!child) continue; + if (!child) continue; var idx = child.parents.indexOf(moduleId); - if(idx >= 0) { + if (idx >= 0) { child.parents.splice(idx, 1); } } } // remove outdated dependency from module children - for(var moduleId in outdatedDependencies) { - if(Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) { + for (var moduleId in outdatedDependencies) { + if (Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) { var module = installedModules[moduleId]; var moduleOutdatedDependencies = outdatedDependencies[moduleId]; - for(var j = 0; j < moduleOutdatedDependencies.length; j++) { + for (var j = 0; j < moduleOutdatedDependencies.length; j++) { var dependency = moduleOutdatedDependencies[j]; var idx = module.children.indexOf(dependency); - if(idx >= 0) module.children.splice(idx, 1); + if (idx >= 0) module.children.splice(idx, 1); } } } @@ -377,31 +387,31 @@ module.exports = function() { hotCurrentHash = hotUpdateNewHash; // insert new code - for(var moduleId in appliedUpdate) { - if(Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) { + for (var moduleId in appliedUpdate) { + if (Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) { modules[moduleId] = appliedUpdate[moduleId]; } } // call accept handlers var error = null; - for(var moduleId in outdatedDependencies) { - if(Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) { + for (var moduleId in outdatedDependencies) { + if (Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) { var module = installedModules[moduleId]; var moduleOutdatedDependencies = outdatedDependencies[moduleId]; var callbacks = []; - for(var i = 0; i < moduleOutdatedDependencies.length; i++) { + for (var i = 0; i < moduleOutdatedDependencies.length; i++) { var dependency = moduleOutdatedDependencies[i]; var cb = module.hot._acceptedDependencies[dependency]; - if(callbacks.indexOf(cb) >= 0) continue; + if (callbacks.indexOf(cb) >= 0) continue; callbacks.push(cb); } - for(var i = 0; i < callbacks.length; i++) { + for (var i = 0; i < callbacks.length; i++) { var cb = callbacks[i]; try { cb(outdatedDependencies); - } catch(err) { - if(!error) + } catch (err) { + if (!error) error = err; } } @@ -409,27 +419,27 @@ module.exports = function() { } // Load self accepted modules - for(var i = 0; i < outdatedSelfAcceptedModules.length; i++) { + for (var i = 0; i < outdatedSelfAcceptedModules.length; i++) { var item = outdatedSelfAcceptedModules[i]; var moduleId = item.module; hotCurrentParents = [moduleId]; try { $require$(moduleId); - } catch(err) { - if(typeof item.errorHandler === "function") { + } catch (err) { + if (typeof item.errorHandler === "function") { try { item.errorHandler(err); - } catch(err) { - if(!error) + } catch (err) { + if (!error) error = err; } - } else if(!error) + } else if (!error) error = err; } } // handle errors in accept handlers and self accepted module load - if(error) { + if (error) { hotSetStatus("fail"); return callback(error); } diff --git a/lib/HotModuleReplacementPlugin.js b/lib/HotModuleReplacementPlugin.js index 8a13ee835..9ee8a2547 100644 --- a/lib/HotModuleReplacementPlugin.js +++ b/lib/HotModuleReplacementPlugin.js @@ -10,8 +10,7 @@ var RawSource = require("webpack-core/lib/RawSource"); var ConstDependency = require("./dependencies/ConstDependency"); var NullFactory = require("./NullFactory"); -function HotModuleReplacementPlugin() { -} +function HotModuleReplacementPlugin() {} module.exports = HotModuleReplacementPlugin; HotModuleReplacementPlugin.prototype.apply = function(compiler) { @@ -19,7 +18,7 @@ HotModuleReplacementPlugin.prototype.apply = function(compiler) { var hotUpdateMainFilename = compiler.options.output.hotUpdateMainFilename; compiler.plugin("compilation", function(compilation, params) { var hotUpdateChunkTemplate = compilation.hotUpdateChunkTemplate; - if(!hotUpdateChunkTemplate) return; + if (!hotUpdateChunkTemplate) return; var normalModuleFactory = params.normalModuleFactory; @@ -33,7 +32,7 @@ HotModuleReplacementPlugin.prototype.apply = function(compiler) { compilation.dependencyTemplates.set(ModuleHotDeclineDependency, new ModuleHotDeclineDependency.Template()); compilation.plugin("record", function(compilation, records) { - if(records.hash === this.hash) return; + if (records.hash === this.hash) return; records.hash = compilation.hash; records.moduleHashs = {}; this.modules.forEach(function(module) { @@ -48,15 +47,17 @@ HotModuleReplacementPlugin.prototype.apply = function(compiler) { }); records.chunkModuleIds = {}; this.chunks.forEach(function(chunk) { - records.chunkModuleIds[chunk.id] = chunk.modules.map(function(m) { return m.id; }); + records.chunkModuleIds[chunk.id] = chunk.modules.map(function(m) { + return m.id; + }); }); }); compilation.plugin("after-hash", function() { var records = this.records; - if(!records) return; + if (!records) return; var preHash = records.preHash || "x"; var prepreHash = records.prepreHash || "x"; - if(preHash === this.hash) { + if (preHash === this.hash) { this.modifyHash(prepreHash); return; } @@ -66,8 +67,8 @@ HotModuleReplacementPlugin.prototype.apply = function(compiler) { }); compilation.plugin("additional-chunk-assets", function() { var records = this.records; - if(records.hash === this.hash) return; - if(!records.moduleHashs || !records.chunkHashs || !records.chunkModuleIds) return; + if (records.hash === this.hash) return; + if (!records.moduleHashs || !records.chunkHashs || !records.chunkModuleIds) return; this.modules.forEach(function(module) { var identifier = module.identifier(); var hash = require("crypto").createHash("md5"); @@ -84,11 +85,11 @@ HotModuleReplacementPlugin.prototype.apply = function(compiler) { var currentChunk = this.chunks.filter(function(chunk) { return chunk.id === chunkId; })[0]; - if(currentChunk) { + if (currentChunk) { var newModules = currentChunk.modules.filter(function(module) { return module.hotUpdate; }); - if(newModules.length > 0) { + if (newModules.length > 0) { var source = hotUpdateChunkTemplate.render(chunkId, newModules, this.hash, this.moduleTemplate, this.dependencyTemplates); var filename = this.getPath(hotUpdateChunkFilename, { hash: records.hash, @@ -131,9 +132,9 @@ HotModuleReplacementPlugin.prototype.apply = function(compiler) { source, "", hotInitCode - .replace(/\$require\$/g, this.requireFn) - .replace(/\$hash\$/g, JSON.stringify(hash)) - .replace(/\/\*foreachInstalledChunks\*\//g, chunk.chunks.length > 0 ? "for(var chunkId in installedChunks)" : "var chunkId = " + chunk.id + ";") + .replace(/\$require\$/g, this.requireFn) + .replace(/\$hash\$/g, JSON.stringify(hash)) + .replace(/\/\*foreachInstalledChunks\*\//g, chunk.chunks.length > 0 ? "for(var chunkId in installedChunks)" : "var chunkId = " + chunk.id + ";") ]); }); @@ -142,7 +143,7 @@ HotModuleReplacementPlugin.prototype.apply = function(compiler) { }); compilation.mainTemplate.plugin("current-hash", function(_, length) { - if(isFinite(length)) + if (isFinite(length)) return "hotCurrentHash.substr(0, " + length + ")"; else return "hotCurrentHash"; @@ -173,13 +174,13 @@ HotModuleReplacementPlugin.prototype.apply = function(compiler) { .setRange(expr.range); }); compiler.parser.plugin("call module.hot.accept", function(expr) { - if(!this.state.compilation.hotUpdateChunkTemplate) return false; - if(expr.arguments.length > 1) { + if (!this.state.compilation.hotUpdateChunkTemplate) return false; + if (expr.arguments.length > 1) { var arg = this.evaluateExpression(expr.arguments[0]); var params = []; - if(arg.isString()) { + if (arg.isString()) { params = [arg]; - } else if(arg.isArray()) { + } else if (arg.isArray()) { params = arg.items.filter(function(param) { return param.isString(); }); @@ -194,13 +195,13 @@ HotModuleReplacementPlugin.prototype.apply = function(compiler) { } }); compiler.parser.plugin("call module.hot.decline", function(expr) { - if(!this.state.compilation.hotUpdateChunkTemplate) return false; - if(expr.arguments.length === 1) { + if (!this.state.compilation.hotUpdateChunkTemplate) return false; + if (expr.arguments.length === 1) { var arg = this.evaluateExpression(expr.arguments[0]); var params = []; - if(arg.isString()) { + if (arg.isString()) { params = [arg]; - } else if(arg.isArray()) { + } else if (arg.isArray()) { params = arg.items.filter(function(param) { return param.isString(); }); diff --git a/lib/HotUpdateChunkTemplate.js b/lib/HotUpdateChunkTemplate.js index a288c4da8..e9daaba60 100644 --- a/lib/HotUpdateChunkTemplate.js +++ b/lib/HotUpdateChunkTemplate.js @@ -12,7 +12,10 @@ module.exports = HotUpdateChunkTemplate; HotUpdateChunkTemplate.prototype = Object.create(Template.prototype); HotUpdateChunkTemplate.prototype.render = function(id, modules, hash, moduleTemplate, dependencyTemplates) { - var modulesSource = this.renderChunkModules({ id: id, modules: modules }, moduleTemplate, dependencyTemplates); + var modulesSource = this.renderChunkModules({ + id: id, + modules: modules + }, moduleTemplate, dependencyTemplates); var core = this.applyPluginsWaterfall("modules", modulesSource, modules, moduleTemplate, dependencyTemplates); var source = this.applyPluginsWaterfall("render", core, modules, hash, id, moduleTemplate, dependencyTemplates); return source; diff --git a/lib/IgnorePlugin.js b/lib/IgnorePlugin.js index 71a4340db..f3511aba9 100644 --- a/lib/IgnorePlugin.js +++ b/lib/IgnorePlugin.js @@ -12,8 +12,8 @@ IgnorePlugin.prototype.apply = function(compiler) { var contextRegExp = this.contextRegExp; compiler.plugin("normal-module-factory", function(nmf) { nmf.plugin("before-resolve", function(result, callback) { - if(!result) return callback(); - if(resourceRegExp.test(result.request) && + if (!result) return callback(); + if (resourceRegExp.test(result.request) && (!contextRegExp || contextRegExp.test(result.context))) { return callback(); } @@ -22,8 +22,8 @@ IgnorePlugin.prototype.apply = function(compiler) { }); compiler.plugin("context-module-factory", function(cmf) { cmf.plugin("before-resolve", function(result, callback) { - if(!result) return callback(); - if(resourceRegExp.test(result.request)) { + if (!result) return callback(); + if (resourceRegExp.test(result.request)) { return callback(); } return callback(null, result); diff --git a/lib/JsonpChunkTemplatePlugin.js b/lib/JsonpChunkTemplatePlugin.js index b1edc8099..a74bf0f2b 100644 --- a/lib/JsonpChunkTemplatePlugin.js +++ b/lib/JsonpChunkTemplatePlugin.js @@ -5,8 +5,7 @@ var ConcatSource = require("webpack-core/lib/ConcatSource"); var Template = require("./Template"); -function JsonpChunkTemplatePlugin() { -} +function JsonpChunkTemplatePlugin() {} module.exports = JsonpChunkTemplatePlugin; JsonpChunkTemplatePlugin.prototype.apply = function(chunkTemplate) { diff --git a/lib/JsonpHotUpdateChunkTemplatePlugin.js b/lib/JsonpHotUpdateChunkTemplatePlugin.js index e6553c00f..b859320bf 100644 --- a/lib/JsonpHotUpdateChunkTemplatePlugin.js +++ b/lib/JsonpHotUpdateChunkTemplatePlugin.js @@ -6,8 +6,7 @@ var ConcatSource = require("webpack-core/lib/ConcatSource"); var Template = require("./Template"); -function JsonpHotUpdateChunkTemplatePlugin() { -} +function JsonpHotUpdateChunkTemplatePlugin() {} module.exports = JsonpHotUpdateChunkTemplatePlugin; JsonpHotUpdateChunkTemplatePlugin.prototype.apply = function(hotUpdateChunkTemplate) { diff --git a/lib/JsonpMainTemplate.runtime.js b/lib/JsonpMainTemplate.runtime.js index 4fcc81c6b..525477e4b 100644 --- a/lib/JsonpMainTemplate.runtime.js +++ b/lib/JsonpMainTemplate.runtime.js @@ -6,7 +6,7 @@ module.exports = function() { function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars hotAddUpdateChunk(chunkId, moreModules); - if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); + if (parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); } function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars @@ -19,7 +19,7 @@ module.exports = function() { } function hotDownloadManifest(callback) { // eslint-disable-line no-unused-vars - if(typeof XMLHttpRequest === "undefined") + if (typeof XMLHttpRequest === "undefined") return callback(new Error("No browser support")); try { var request = new XMLHttpRequest(); @@ -27,25 +27,25 @@ module.exports = function() { request.open("GET", requestPath, true); request.timeout = 10000; request.send(null); - } catch(err) { + } catch (err) { return callback(err); } request.onreadystatechange = function() { - if(request.readyState !== 4) return; - if(request.status === 0) { + if (request.readyState !== 4) return; + if (request.status === 0) { // timeout callback(new Error("Manifest request to " + requestPath + " timed out.")); - } else if(request.status === 404) { + } else if (request.status === 404) { // no update available callback(); - } else if(request.status !== 200 && request.status !== 304) { + } else if (request.status !== 200 && request.status !== 304) { // other failure callback(new Error("Manifest request to " + requestPath + " failed.")); } else { // success try { var update = JSON.parse(request.responseText); - } catch(e) { + } catch (e) { callback(e); return; } diff --git a/lib/JsonpMainTemplatePlugin.js b/lib/JsonpMainTemplatePlugin.js index 812ffd0e4..0d3bb7f77 100644 --- a/lib/JsonpMainTemplatePlugin.js +++ b/lib/JsonpMainTemplatePlugin.js @@ -4,14 +4,13 @@ */ var Template = require("./Template"); -function JsonpMainTemplatePlugin() { -} +function JsonpMainTemplatePlugin() {} module.exports = JsonpMainTemplatePlugin; JsonpMainTemplatePlugin.prototype.constructor = JsonpMainTemplatePlugin; JsonpMainTemplatePlugin.prototype.apply = function(mainTemplate) { mainTemplate.plugin("local-vars", function(source, chunk) { - if(chunk.chunks.length > 0) { + if (chunk.chunks.length > 0) { return this.asString([ source, "", @@ -53,32 +52,32 @@ JsonpMainTemplatePlugin.prototype.apply = function(mainTemplate) { "script.async = true;", crossOriginLoading ? "script.crossOrigin = '" + crossOriginLoading + "';" : "", "script.src = " + this.requireFn + ".p + " + - this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), { - hash: "\" + " + this.renderCurrentHashCode(hash) + " + \"", + this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), { + hash: "\" + " + this.renderCurrentHashCode(hash) + " + \"", + hashWithLength: function(length) { + return "\" + " + this.renderCurrentHashCode(hash, length) + " + \""; + }.bind(this), + chunk: { + id: "\" + chunkId + \"", + hash: "\" + " + JSON.stringify(chunkMaps.hash) + "[chunkId] + \"", hashWithLength: function(length) { - return "\" + " + this.renderCurrentHashCode(hash, length) + " + \""; - }.bind(this), - chunk: { - id: "\" + chunkId + \"", - hash: "\" + " + JSON.stringify(chunkMaps.hash) + "[chunkId] + \"", - hashWithLength: function(length) { - var shortChunkHashMap = {}; - Object.keys(chunkMaps.hash).forEach(function(chunkId) { - if(typeof chunkMaps.hash[chunkId] === "string") - shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr(0, length); - }); - return "\" + " + JSON.stringify(shortChunkHashMap) + "[chunkId] + \""; - }, - name: "\" + (" + JSON.stringify(chunkMaps.name) + "[chunkId]||chunkId) + \"" - } - }) + ";", + var shortChunkHashMap = {}; + Object.keys(chunkMaps.hash).forEach(function(chunkId) { + if (typeof chunkMaps.hash[chunkId] === "string") + shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr(0, length); + }); + return "\" + " + JSON.stringify(shortChunkHashMap) + "[chunkId] + \""; + }, + name: "\" + (" + JSON.stringify(chunkMaps.name) + "[chunkId]||chunkId) + \"" + } + }) + ";", "head.appendChild(script);" ]), "}" ]); }); mainTemplate.plugin("bootstrap", function(source, chunk, hash) { - if(chunk.chunks.length > 0) { + if (chunk.chunks.length > 0) { var jsonpFunction = this.outputOptions.jsonpFunction || Template.toIdentifier("webpackJsonp" + (this.outputOptions.library || "")); return this.asString([ source, @@ -103,8 +102,7 @@ JsonpMainTemplatePlugin.prototype.apply = function(mainTemplate) { "}", "if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules);", "while(callbacks.length)", - this.indent("callbacks.shift().call(null, " + this.requireFn + ");"), - (this.entryPointInChildren(chunk) ? [ + this.indent("callbacks.shift().call(null, " + this.requireFn + ");"), (this.entryPointInChildren(chunk) ? [ "if(moreModules[0]) {", this.indent([ "installedModules[0] = 0;", diff --git a/lib/JsonpTemplatePlugin.js b/lib/JsonpTemplatePlugin.js index f2adff5c7..451cfafbd 100644 --- a/lib/JsonpTemplatePlugin.js +++ b/lib/JsonpTemplatePlugin.js @@ -15,4 +15,3 @@ JsonpTemplatePlugin.prototype.apply = function(compiler) { compilation.hotUpdateChunkTemplate.apply(new JsonpHotUpdateChunkTemplatePlugin()); }); }; - diff --git a/lib/LibManifestPlugin.js b/lib/LibManifestPlugin.js index e97f8d1ee..1748b4284 100644 --- a/lib/LibManifestPlugin.js +++ b/lib/LibManifestPlugin.js @@ -12,7 +12,7 @@ module.exports = LibManifestPlugin; LibManifestPlugin.prototype.apply = function(compiler) { compiler.plugin("emit", function(compilation, callback) { async.forEach(compilation.chunks, function(chunk, callback) { - if(!chunk.initial) + if (!chunk.initial) return; var targetPath = compilation.getPath(this.options.path, { hash: compilation.hash, @@ -26,11 +26,11 @@ LibManifestPlugin.prototype.apply = function(compiler) { name: name, type: this.options.type, content: chunk.modules.reduce(function(obj, module) { - if(module.libIdent) { + if (module.libIdent) { var ident = module.libIdent({ context: this.options.context || compiler.options.context }); - if(ident) { + if (ident) { obj[ident] = module.id; } } @@ -39,7 +39,7 @@ LibManifestPlugin.prototype.apply = function(compiler) { }; var content = new Buffer(JSON.stringify(manifest, null, 2), "utf-8"); compiler.outputFileSystem.mkdirp(path.dirname(targetPath), function(err) { - if(err) return callback(err); + if (err) return callback(err); compiler.outputFileSystem.writeFile(targetPath, content, callback); }); }.bind(this), callback); diff --git a/lib/LibraryTemplatePlugin.js b/lib/LibraryTemplatePlugin.js index c32029cc0..4647f3ed9 100644 --- a/lib/LibraryTemplatePlugin.js +++ b/lib/LibraryTemplatePlugin.js @@ -16,8 +16,8 @@ function accessorAccess(base, accessor, joinWith) { a = base ? base + accessorToObjectAccess(accessor.slice(0, idx + 1)) : accessor[0] + accessorToObjectAccess(accessor.slice(1, idx + 1)); - if(idx === accessor.length - 1) return a; - if(idx === 0 && typeof base === "undefined") return a + " = typeof " + a + " === \"object\" ? " + a + " : {}"; + if (idx === accessor.length - 1) return a; + if (idx === 0 && typeof base === "undefined") return a + " = typeof " + a + " === \"object\" ? " + a + " : {}"; return a + " = " + a + " || {}"; }).join(joinWith || "; "); } @@ -29,45 +29,45 @@ function LibraryTemplatePlugin(name, target) { module.exports = LibraryTemplatePlugin; LibraryTemplatePlugin.prototype.apply = function(compiler) { compiler.plugin("this-compilation", function(compilation) { - switch(this.target) { - case "var": - compilation.apply(new SetVarMainTemplatePlugin("var " + accessorAccess(false, this.name))); - break; - case "assign": - compilation.apply(new SetVarMainTemplatePlugin(accessorAccess(undefined, this.name))); - break; - case "this": - case "window": - case "global": - if(this.name) - compilation.apply(new SetVarMainTemplatePlugin(accessorAccess(this.target, this.name))); - else - compilation.apply(new SetVarMainTemplatePlugin(this.target, true)); - break; - case "commonjs": - if(this.name) - compilation.apply(new SetVarMainTemplatePlugin(accessorAccess("exports", this.name))); - else - compilation.apply(new SetVarMainTemplatePlugin("exports", true)); - break; - case "commonjs2": - compilation.apply(new SetVarMainTemplatePlugin("module.exports")); - break; - case "amd": - var AmdMainTemplatePlugin = require("./AmdMainTemplatePlugin"); - compilation.apply(new AmdMainTemplatePlugin(this.name)); - break; - case "umd": - case "umd2": - var UmdMainTemplatePlugin = require("./UmdMainTemplatePlugin"); - compilation.apply(new UmdMainTemplatePlugin(this.name, this.target === "umd2")); - break; - case "jsonp": - var JsonpExportMainTemplatePlugin = require("./JsonpExportMainTemplatePlugin"); - compilation.apply(new JsonpExportMainTemplatePlugin(this.name)); - break; - default: - throw new Error(this.target + " is not a valid Library target"); + switch (this.target) { + case "var": + compilation.apply(new SetVarMainTemplatePlugin("var " + accessorAccess(false, this.name))); + break; + case "assign": + compilation.apply(new SetVarMainTemplatePlugin(accessorAccess(undefined, this.name))); + break; + case "this": + case "window": + case "global": + if (this.name) + compilation.apply(new SetVarMainTemplatePlugin(accessorAccess(this.target, this.name))); + else + compilation.apply(new SetVarMainTemplatePlugin(this.target, true)); + break; + case "commonjs": + if (this.name) + compilation.apply(new SetVarMainTemplatePlugin(accessorAccess("exports", this.name))); + else + compilation.apply(new SetVarMainTemplatePlugin("exports", true)); + break; + case "commonjs2": + compilation.apply(new SetVarMainTemplatePlugin("module.exports")); + break; + case "amd": + var AmdMainTemplatePlugin = require("./AmdMainTemplatePlugin"); + compilation.apply(new AmdMainTemplatePlugin(this.name)); + break; + case "umd": + case "umd2": + var UmdMainTemplatePlugin = require("./UmdMainTemplatePlugin"); + compilation.apply(new UmdMainTemplatePlugin(this.name, this.target === "umd2")); + break; + case "jsonp": + var JsonpExportMainTemplatePlugin = require("./JsonpExportMainTemplatePlugin"); + compilation.apply(new JsonpExportMainTemplatePlugin(this.name)); + break; + default: + throw new Error(this.target + " is not a valid Library target"); } }.bind(this)); }; diff --git a/lib/MainTemplate.js b/lib/MainTemplate.js index c7bd23a20..51c233a21 100644 --- a/lib/MainTemplate.js +++ b/lib/MainTemplate.js @@ -11,7 +11,9 @@ function MainTemplate(outputOptions) { Template.call(this, outputOptions); this.plugin("startup", function(source, chunk, hash) { var buf = []; - if(chunk.modules.some(function(m) { return m.id === 0; })) { + if (chunk.modules.some(function(m) { + return m.id === 0; + })) { buf.push(""); buf.push("// Load entry module and return exports"); buf.push("return " + this.renderRequireFunctionForModule(hash, chunk, "0") + "(0);"); @@ -30,7 +32,7 @@ function MainTemplate(outputOptions) { source.add(")"); return source; }); - this.plugin("local-vars", function(source/*, chunk, hash*/) { + this.plugin("local-vars", function(source /*, chunk, hash*/ ) { return this.asString([ source, "// The module cache", @@ -59,7 +61,7 @@ function MainTemplate(outputOptions) { "return module.exports;" ]); }); - this.plugin("module-obj", function(/*source, chunk, hash, varModuleId*/) { + this.plugin("module-obj", function( /*source, chunk, hash, varModuleId*/ ) { return this.asString([ "exports: {},", "id: moduleId,", @@ -68,7 +70,7 @@ function MainTemplate(outputOptions) { }); this.plugin("require-extensions", function(source, chunk, hash) { var buf = []; - if(chunk.chunks.length > 0) { + if (chunk.chunks.length > 0) { buf.push("// This file contains only the entry chunk."); buf.push("// The chunk loading function for additional chunks"); buf.push(this.requireFn + ".e = function requireEnsure(chunkId, callback) {"); @@ -109,12 +111,12 @@ MainTemplate.prototype.render = function(hash, chunk, moduleTemplate, dependency buf.push(this.asString(this.applyPluginsWaterfall("require-extensions", "", chunk, hash))); buf.push(this.asString(this.applyPluginsWaterfall("startup", "", chunk, hash))); var source = this.applyPluginsWaterfall("render", new OriginalSource(this.prefix(buf, " \t") + "\n", "webpack/bootstrap " + hash), chunk, hash, moduleTemplate, dependencyTemplates); - if(chunk.modules.some(function(module) { - return (module.id === 0); - })) { + if (chunk.modules.some(function(module) { + return (module.id === 0); + })) { source = this.applyPluginsWaterfall("render-with-entry", source, chunk, hash); } - if(!source) throw new Error("Compiler error: MainTemplate plugin 'render' should return something"); + if (!source) throw new Error("Compiler error: MainTemplate plugin 'render' should return something"); chunk.rendered = true; return new ConcatSource(source, ";"); }; @@ -135,7 +137,7 @@ MainTemplate.prototype.renderCurrentHashCode = function(hash, length) { MainTemplate.prototype.entryPointInChildren = function(chunk) { return (function checkChildren(chunk, alreadyCheckedChunks) { return chunk.chunks.some(function(child) { - if(alreadyCheckedChunks.indexOf(child) >= 0) return; + if (alreadyCheckedChunks.indexOf(child) >= 0) return; alreadyCheckedChunks.push(child); return child.modules.some(function(module) { return (module.id === 0); diff --git a/lib/Module.js b/lib/Module.js index 252086b37..98355f73e 100644 --- a/lib/Module.js +++ b/lib/Module.js @@ -6,6 +6,7 @@ var DependenciesBlock = require("./DependenciesBlock"); var ModuleReason = require("./ModuleReason"); var debugId = 1000; + function Module() { DependenciesBlock.call(this); this.context = null; @@ -37,7 +38,7 @@ Module.prototype.disconnect = function() { Module.prototype.addChunk = function(chunk) { var idx = this.chunks.indexOf(chunk); - if(idx < 0) + if (idx < 0) this.chunks.push(chunk); }; @@ -52,9 +53,9 @@ Module.prototype.addReason = function(module, dependency) { }; Module.prototype.removeReason = function(module, dependency) { - for(var i = 0; i < this.reasons.length; i++) { + for (var i = 0; i < this.reasons.length; i++) { var r = this.reasons[i]; - if(r.module === module && r.dependency === dependency) { + if (r.module === module && r.dependency === dependency) { this.reasons.splice(i, 1); return true; } @@ -63,12 +64,12 @@ Module.prototype.removeReason = function(module, dependency) { }; Module.prototype.hasReasonForChunk = function(chunk) { - for(var i = 0; i < this.reasons.length; i++) { + for (var i = 0; i < this.reasons.length; i++) { var r = this.reasons[i]; - if(r.chunks) { - if(r.chunks.indexOf(chunk) >= 0) + if (r.chunks) { + if (r.chunks.indexOf(chunk) >= 0) return true; - } else if(r.module.chunks.indexOf(chunk) >= 0) + } else if (r.module.chunks.indexOf(chunk) >= 0) return true; } return false; @@ -76,15 +77,15 @@ Module.prototype.hasReasonForChunk = function(chunk) { function addToSet(set, items) { items.forEach(function(item) { - if(set.indexOf(item) < 0) + if (set.indexOf(item) < 0) set.push(item); }); } Module.prototype.rewriteChunkInReasons = function(oldChunk, newChunks) { this.reasons.forEach(function(r) { - if(!r.chunks) { - if(r.module.chunks.indexOf(oldChunk) < 0) + if (!r.chunks) { + if (r.module.chunks.indexOf(oldChunk) < 0) return; r.chunks = r.module.chunks; } @@ -99,7 +100,7 @@ Module.prototype.toString = function() { return "Module[" + (this.id || this.debugId) + "]"; }; -Module.prototype.needRebuild = function(/* fileTimestamps, contextTimestamps */) { +Module.prototype.needRebuild = function( /* fileTimestamps, contextTimestamps */ ) { return true; }; diff --git a/lib/ModuleFilenameHelpers.js b/lib/ModuleFilenameHelpers.js index 5ea968fcf..4ef2b7b6a 100644 --- a/lib/ModuleFilenameHelpers.js +++ b/lib/ModuleFilenameHelpers.js @@ -42,13 +42,13 @@ function getHash(str) { } function asRegExp(test) { - if(typeof test === "string") test = new RegExp("^" + test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); + if (typeof test === "string") test = new RegExp("^" + test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")); return test; } ModuleFilenameHelpers.createFilename = function createFilename(module, moduleFilenameTemplate, requestShortener) { - if(!module) module = ""; - if(typeof module === "string") { + if (!module) module = ""; + if (typeof module === "string") { var shortIdentifier = requestShortener.shorten(module); var identifier = shortIdentifier; var moduleId = ""; @@ -66,7 +66,7 @@ ModuleFilenameHelpers.createFilename = function createFilename(module, moduleFil var allLoaders = getBefore(identifier, "!"); var query = getAfter(resource, "?"); var resourcePath = resource.substr(0, resource.length - query.length); - if(typeof moduleFilenameTemplate === "function") { + if (typeof moduleFilenameTemplate === "function") { return moduleFilenameTemplate({ identifier: identifier, shortIdentifier: shortIdentifier, @@ -94,7 +94,7 @@ ModuleFilenameHelpers.createFilename = function createFilename(module, moduleFil }; ModuleFilenameHelpers.createFooter = function createFooter(module, requestShortener) { - if(typeof module === "string") { + if (typeof module === "string") { return [ "/** WEBPACK FOOTER **", " ** " + requestShortener.shorten(module), @@ -106,7 +106,9 @@ ModuleFilenameHelpers.createFooter = function createFooter(module, requestShorte " ** WEBPACK FOOTER", " ** " + module.readableIdentifier(requestShortener), " ** module id = " + module.id, - " ** module chunks = " + module.chunks.map(function(c) { return c.id; }).join(" "), + " ** module chunks = " + module.chunks.map(function(c) { + return c.id; + }).join(" "), " **/" ].join("\n"); } @@ -120,14 +122,14 @@ ModuleFilenameHelpers.replaceDuplicates = function replaceDuplicates(array, fn, countMap[item].push(idx); posMap[item] = 0; }); - if(comparator) { + if (comparator) { Object.keys(countMap).forEach(function(item) { countMap[item].sort(comparator); }); } return array.map(function(item, i) { - if(countMap[item].length > 1) { - if(comparator && countMap[item][0] === i) + if (countMap[item].length > 1) { + if (comparator && countMap[item][0] === i) return item; return fn(item, i, posMap[item]++); } else return item; @@ -136,9 +138,9 @@ ModuleFilenameHelpers.replaceDuplicates = function replaceDuplicates(array, fn, ModuleFilenameHelpers.matchPart = function matchPart(str, test) { - if(!test) return true; + if (!test) return true; test = asRegExp(test); - if(Array.isArray(test)) { + if (Array.isArray(test)) { return test.map(asRegExp).filter(function(regExp) { return regExp.test(str); }).length > 0; @@ -148,11 +150,11 @@ ModuleFilenameHelpers.matchPart = function matchPart(str, test) { }; ModuleFilenameHelpers.matchObject = function matchObject(obj, str) { - if(obj.test) - if(!ModuleFilenameHelpers.matchPart(str, obj.test)) return false; - if(obj.include) - if(!ModuleFilenameHelpers.matchPart(str, obj.include)) return false; - if(obj.exclude) - if(ModuleFilenameHelpers.matchPart(str, obj.exclude)) return false; + if (obj.test) + if (!ModuleFilenameHelpers.matchPart(str, obj.test)) return false; + if (obj.include) + if (!ModuleFilenameHelpers.matchPart(str, obj.include)) return false; + if (obj.exclude) + if (ModuleFilenameHelpers.matchPart(str, obj.exclude)) return false; return true; }; diff --git a/lib/ModuleParseError.js b/lib/ModuleParseError.js index f93fe9d2a..6d4144a1b 100644 --- a/lib/ModuleParseError.js +++ b/lib/ModuleParseError.js @@ -8,8 +8,8 @@ function ModuleParseError(module, source, err) { this.name = "ModuleParseError"; this.message = "Module parse failed: " + module.request + " " + err.message; this.message += "\nYou may need an appropriate loader to handle this file type."; - if(typeof err.lineNumber === "number") { - if(/[\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007]/.test(source)) { // binary file + if (typeof err.lineNumber === "number") { + if (/[\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007]/.test(source)) { // binary file this.message += "\n(Source code omitted for this binary file)"; } else { source = source.split("\n"); diff --git a/lib/ModuleParserHelpers.js b/lib/ModuleParserHelpers.js index 1232111d4..3127eb400 100644 --- a/lib/ModuleParserHelpers.js +++ b/lib/ModuleParserHelpers.js @@ -5,7 +5,7 @@ var ModuleParserHelpers = exports; ModuleParserHelpers.addParsedVariable = function(parser, name, expression) { - if(!parser.state.current.addVariable) return false; + if (!parser.state.current.addVariable) return false; var deps = []; parser.parse(expression, { current: { diff --git a/lib/MultiCompiler.js b/lib/MultiCompiler.js index 46aaab5ba..25662ee7d 100644 --- a/lib/MultiCompiler.js +++ b/lib/MultiCompiler.js @@ -24,7 +24,7 @@ MultiWatching.prototype.close = function(callback) { function MultiCompiler(compilers) { Tapable.call(this); - if(!Array.isArray(compilers)) { + if (!Array.isArray(compilers)) { compilers = Object.keys(compilers).map(function(name) { compilers[name].name = name; return compilers[name]; @@ -52,12 +52,12 @@ function MultiCompiler(compilers) { configurable: false, get: function() { var commonPath = compilers[0].outputPath; - for(var i = 1; i < compilers.length; i++) { - while(compilers[i].outputPath.indexOf(commonPath) !== 0 && /[\/\\]/.test(commonPath)) { + for (var i = 1; i < compilers.length; i++) { + while (compilers[i].outputPath.indexOf(commonPath) !== 0 && /[\/\\]/.test(commonPath)) { commonPath = commonPath.replace(/[\/\\][^\/\\]*$/, ""); } } - if(!commonPath && compilers[0].outputPath[0] === "/") return "/"; + if (!commonPath && compilers[0].outputPath[0] === "/") return "/"; return commonPath; } }); @@ -67,17 +67,17 @@ function MultiCompiler(compilers) { this.compilers.forEach(function(compiler, idx) { var compilerDone = false; compiler.plugin("done", function(stats) { - if(!compilerDone) { + if (!compilerDone) { compilerDone = true; doneCompilers++; } compilerStats[idx] = stats; - if(doneCompilers === this.compilers.length) { + if (doneCompilers === this.compilers.length) { this.applyPlugins("done", new MultiStats(compilerStats)); } }.bind(this)); compiler.plugin("invalid", function() { - if(compilerDone) { + if (compilerDone) { compilerDone = false; doneCompilers--; } @@ -100,14 +100,14 @@ MultiCompiler.prototype.run = function(callback) { async.map(this.compilers, function(compiler, callback) { compiler.run(callback); }, function(err, stats) { - if(err) return callback(err); + if (err) return callback(err); callback(null, new MultiStats(stats)); }); }; MultiCompiler.prototype.purgeInputFileSystem = function() { this.compilers.forEach(function(compiler) { - if(compiler.inputFileSystem && compiler.inputFileSystem.purge) + if (compiler.inputFileSystem && compiler.inputFileSystem.purge) compiler.inputFileSystem.purge(); }); }; @@ -122,13 +122,17 @@ function MultiStats(stats) { MultiStats.prototype.hasErrors = function() { return this.stats.map(function(stat) { return stat.hasErrors(); - }).reduce(function(a, b) { return a || b; }, false); + }).reduce(function(a, b) { + return a || b; + }, false); }; MultiStats.prototype.hasWarnings = function() { return this.stats.map(function(stat) { return stat.hasWarnings(); - }).reduce(function(a, b) { return a || b; }, false); + }).reduce(function(a, b) { + return a || b; + }, false); }; MultiStats.prototype.toJson = function(options, forToString) { @@ -149,11 +153,11 @@ MultiStats.prototype.toJson = function(options, forToString) { })); }, []) }; - if(!options || options.version !== false) + if (!options || options.version !== false) obj.version = require("../package.json").version; - if(!options || options.hash !== false) + if (!options || options.hash !== false) obj.hash = this.hash; - if(!options || options.children !== false) + if (!options || options.children !== false) obj.children = jsons; return obj; }; diff --git a/lib/MultiModule.js b/lib/MultiModule.js index 369d4bfa1..c3592eb23 100644 --- a/lib/MultiModule.js +++ b/lib/MultiModule.js @@ -38,11 +38,11 @@ MultiModule.prototype.build = function build(options, compilation, resolver, fs, MultiModule.prototype.source = function(dependencyTemplates, outputOptions) { var str = []; this.dependencies.forEach(function(dep, idx) { - if(dep.module) { - if(idx === this.dependencies.length - 1) + if (dep.module) { + if (idx === this.dependencies.length - 1) str.push("module.exports = "); str.push("__webpack_require__("); - if(outputOptions.pathinfo) + if (outputOptions.pathinfo) str.push("/*! " + dep.request + " */"); str.push("" + JSON.stringify(dep.module.id)); str.push(")"); diff --git a/lib/NamedModulesPlugin.js b/lib/NamedModulesPlugin.js index f3e47d8fa..f20ffa036 100644 --- a/lib/NamedModulesPlugin.js +++ b/lib/NamedModulesPlugin.js @@ -10,7 +10,7 @@ NamedModulesPlugin.prototype.apply = function(compiler) { compiler.plugin("compilation", function(compilation) { compilation.plugin("before-module-ids", function(modules) { modules.forEach(function(module) { - if(module.id === null && module.libIdent) { + if (module.id === null && module.libIdent) { module.id = module.libIdent({ context: this.options.context || compiler.options.context }); diff --git a/lib/NewWatchingPlugin.js b/lib/NewWatchingPlugin.js index be678046d..e2be25e3e 100644 --- a/lib/NewWatchingPlugin.js +++ b/lib/NewWatchingPlugin.js @@ -2,8 +2,7 @@ MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ -function NewWatchingPlugin() { -} +function NewWatchingPlugin() {} module.exports = NewWatchingPlugin; NewWatchingPlugin.prototype.apply = function(compiler) { diff --git a/lib/NoErrorsPlugin.js b/lib/NoErrorsPlugin.js index 81eeb3a80..3d95ac24e 100644 --- a/lib/NoErrorsPlugin.js +++ b/lib/NoErrorsPlugin.js @@ -2,17 +2,16 @@ MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ -function NoErrorsPlugin() { -} +function NoErrorsPlugin() {} module.exports = NoErrorsPlugin; NoErrorsPlugin.prototype.apply = function(compiler) { compiler.plugin("should-emit", function(compilation) { - if(compilation.errors.length > 0) + if (compilation.errors.length > 0) return false; }); compiler.plugin("compilation", function(compilation) { compilation.plugin("should-record", function() { - if(compilation.errors.length > 0) + if (compilation.errors.length > 0) return false; }); }); diff --git a/lib/NodeStuffPlugin.js b/lib/NodeStuffPlugin.js index 35e204fa2..bfe2605ad 100644 --- a/lib/NodeStuffPlugin.js +++ b/lib/NodeStuffPlugin.js @@ -19,13 +19,18 @@ NodeStuffPlugin.prototype.apply = function(compiler) { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); }); - function ignore() { return true; } + + function ignore() { + return true; + } + function setConstant(expressionName, value) { compiler.parser.plugin("expression " + expressionName, function() { this.state.current.addVariable(expressionName, JSON.stringify(value)); return true; }); } + function setModuleConstant(expressionName, fn) { compiler.parser.plugin("expression " + expressionName, function() { this.state.current.addVariable(expressionName, JSON.stringify(fn(this.state.module))); @@ -33,29 +38,29 @@ NodeStuffPlugin.prototype.apply = function(compiler) { }); } var context = compiler.context; - if(this.options.__filename === "mock") { + if (this.options.__filename === "mock") { setConstant("__filename", "/index.js"); - } else if(this.options.__filename) { + } else if (this.options.__filename) { setModuleConstant("__filename", function(module) { return path.relative(context, module.resource); }); } compiler.parser.plugin("evaluate Identifier __filename", function(expr) { - if(!this.state.module) return; + if (!this.state.module) return; var res = new BasicEvaluatedExpression(); res.setString(this.state.module.splitQuery(this.state.module.resource)[0]); res.setRange(expr.range); return res; }); - if(this.options.__dirname === "mock") { + if (this.options.__dirname === "mock") { setConstant("__dirname", "/"); - } else if(this.options.__dirname) { + } else if (this.options.__dirname) { setModuleConstant("__dirname", function(module) { return path.relative(context, module.context); }); } compiler.parser.plugin("evaluate Identifier __dirname", function(expr) { - if(!this.state.module) return; + if (!this.state.module) return; var res = new BasicEvaluatedExpression(); res.setString(this.state.module.context); res.setRange(expr.range); @@ -71,7 +76,7 @@ NodeStuffPlugin.prototype.apply = function(compiler) { var dep = new ConstDependency("(void 0)", expr.range); dep.loc = expr.loc; this.state.current.addDependency(dep); - if(!this.state.module) return; + if (!this.state.module) return; this.state.module.warnings.push(new UnsupportedFeatureWarning(this.state.module, "require.extensions is not supported by webpack. Use a loader instead.")); return true; }); diff --git a/lib/NormalModule.js b/lib/NormalModule.js index 2475588eb..baf74d304 100644 --- a/lib/NormalModule.js +++ b/lib/NormalModule.js @@ -42,9 +42,9 @@ NormalModule.prototype.readableIdentifier = function(requestShortener) { function contextify(options, request) { return request.split("!").map(function(r) { var rp = path.relative(options.context, r); - if(path.sep === "\\") + if (path.sep === "\\") rp = rp.replace(/\\/g, "/"); - if(rp.indexOf("../") !== 0) + if (rp.indexOf("../") !== 0) rp = "./" + rp; return rp; }).join("!"); @@ -58,9 +58,9 @@ NormalModule.prototype.fillLoaderContext = function fillLoaderContext(loaderCont loaderContext.webpack = true; loaderContext.sourceMap = !!this.useSourceMap; loaderContext.emitFile = function(name, content, sourceMap) { - if(typeof sourceMap === "string") { + if (typeof sourceMap === "string") { this.assets[name] = new OriginalSource(content, sourceMap); - } else if(sourceMap) { + } else if (sourceMap) { this.assets[name] = new SourceMapSource(content, name, sourceMap); } else { this.assets[name] = new RawSource(content); @@ -81,21 +81,21 @@ NormalModule.prototype.build = function build(options, compilation, resolver, fs this.buildTimestamp = new Date().getTime(); this.built = true; return this.doBuild(options, compilation, resolver, fs, function(err) { - if(err) return callback(err); + if (err) return callback(err); this.dependencies.length = 0; this.variables.length = 0; this.blocks.length = 0; this._cachedSource = null; - if(options.module && options.module.noParse) { - if(Array.isArray(options.module.noParse)) { - if(options.module.noParse.some(function(regExp) { - return typeof regExp === "string" ? - this.request.indexOf(regExp) === 0 : - regExp.test(this.request); - }, this)) return callback(); - } else if(typeof options.module.noParse === "string" ? - this.request.indexOf(options.module.noParse) === 0 : - options.module.noParse.test(this.request)) { + if (options.module && options.module.noParse) { + if (Array.isArray(options.module.noParse)) { + if (options.module.noParse.some(function(regExp) { + return typeof regExp === "string" ? + this.request.indexOf(regExp) === 0 : + regExp.test(this.request); + }, this)) return callback(); + } else if (typeof options.module.noParse === "string" ? + this.request.indexOf(options.module.noParse) === 0 : + options.module.noParse.test(this.request)) { return callback(); } } @@ -106,7 +106,7 @@ NormalModule.prototype.build = function build(options, compilation, resolver, fs compilation: compilation, options: options }); - } catch(e) { + } catch (e) { var source = this._source.source(); this._source = null; return callback(new ModuleParseError(this, source, e)); @@ -119,36 +119,46 @@ NormalModule.prototype.source = function(dependencyTemplates, outputOptions, req var hash = require("crypto").createHash("md5"); this.updateHash(hash); hash = hash.digest("hex"); - if(this._cachedSource && this._cachedSource.hash === hash) { + if (this._cachedSource && this._cachedSource.hash === hash) { return this._cachedSource.source; } var _source = this._source; - if(!_source) return new RawSource("throw new Error('No source available');"); + if (!_source) return new RawSource("throw new Error('No source available');"); var source = new ReplaceSource(_source); - this._cachedSource = { source: source, hash: hash }; + this._cachedSource = { + source: source, + hash: hash + }; var topLevelBlock = this; + function doDep(dep) { var template = dependencyTemplates.get(dep.Class); - if(!template) throw new Error("No template for dependency: " + dep.Class.name); + if (!template) throw new Error("No template for dependency: " + dep.Class.name); template.apply(dep, source, outputOptions, requestShortener, dependencyTemplates); } + function doVariable(vars, variable) { var name = variable.name; var expr = variable.expressionSource(dependencyTemplates, outputOptions, requestShortener); - vars.push({name: name, expression: expr}); + vars.push({ + name: name, + expression: expr + }); } + function doBlock(block) { block.dependencies.forEach(doDep); block.blocks.forEach(doBlock); - if(block.variables.length > 0) { + if (block.variables.length > 0) { var vars = []; block.variables.forEach(doVariable.bind(null, vars)); var varNames = []; var varExpressions = []; var varStartCode = ""; var varEndCode = ""; + function emitFunction() { - if(varNames.length === 0) return; + if (varNames.length === 0) return; varStartCode += "/* WEBPACK VAR INJECTION */(function(" + varNames.join(", ") + ") {"; // exports === this in the topLevelBlock, but exports do compress better... @@ -161,15 +171,15 @@ NormalModule.prototype.source = function(dependencyTemplates, outputOptions, req varExpressions.length = 0; } vars.forEach(function(v) { - if(varNames.indexOf(v.name) >= 0) emitFunction(); + if (varNames.indexOf(v.name) >= 0) emitFunction(); varNames.push(v.name); varExpressions.push(v.expression); }); emitFunction(); var start = block.range ? block.range[0] : 0; var end = block.range ? block.range[1] : _source.size(); - if(varStartCode) source.insert(start + 0.5, varStartCode); - if(varEndCode) source.insert(end + 0.5, "\n/* WEBPACK VAR INJECTION */" + varEndCode); + if (varStartCode) source.insert(start + 0.5, varStartCode); + if (varEndCode) source.insert(end + 0.5, "\n/* WEBPACK VAR INJECTION */" + varEndCode); } } doBlock(this); @@ -180,13 +190,13 @@ NormalModule.prototype.needRebuild = function needRebuild(fileTimestamps, contex var timestamp = 0; this.fileDependencies.forEach(function(file) { var ts = fileTimestamps[file]; - if(!ts) timestamp = Infinity; - if(ts > timestamp) timestamp = ts; + if (!ts) timestamp = Infinity; + if (ts > timestamp) timestamp = ts; }); this.contextDependencies.forEach(function(context) { var ts = contextTimestamps[context]; - if(!ts) timestamp = Infinity; - if(ts > timestamp) timestamp = ts; + if (!ts) timestamp = Infinity; + if (ts > timestamp) timestamp = ts; }); return timestamp >= this.buildTimestamp; }; @@ -196,7 +206,7 @@ NormalModule.prototype.size = function() { }; NormalModule.prototype.updateHash = function(hash) { - if(this._source) { + if (this._source) { hash.update("source"); this._source.updateHash(hash); } else @@ -207,7 +217,7 @@ NormalModule.prototype.updateHash = function(hash) { }; NormalModule.prototype.getSourceHash = function() { - if(!this._source) return ""; + if (!this._source) return ""; var hash = require("crypto").createHash("md5"); hash.update(this._source.source()); return hash.digest("hex"); @@ -215,13 +225,16 @@ NormalModule.prototype.getSourceHash = function() { NormalModule.prototype.getAllModuleDependencies = function() { var list = []; + function doDep(dep) { - if(dep.module && list.indexOf(dep.module) < 0) + if (dep.module && list.indexOf(dep.module) < 0) list.push(dep.module); } + function doVariable(variable) { variable.dependencies.forEach(doDep); } + function doBlock(block) { block.variables.forEach(doVariable); block.dependencies.forEach(doDep); @@ -235,8 +248,8 @@ NormalModule.prototype.createTemplate = function(keepModules, roots) { roots.sort(function(a, b) { var ia = a.identifier(); var ib = b.identifier(); - if(ia < ib) return -1; - if(ib < ia) return 1; + if (ia < ib) return -1; + if (ib < ia) return 1; return 0; }); var template = new NormalModule("", "", "", [], "", null); @@ -257,9 +270,10 @@ NormalModule.prototype.createTemplate = function(keepModules, roots) { return array.join("|"); }; var args = template.arguments = []; + function doDeps(deps) { return deps.map(function(dep) { - if(dep.module && keepModules.indexOf(dep.module) < 0) { + if (dep.module && keepModules.indexOf(dep.module) < 0) { var argName = "__webpack_module_template_argument_" + args.length + "__"; args.push(argName); return new TemplateArgumentDependency(argName, dep); @@ -268,6 +282,7 @@ NormalModule.prototype.createTemplate = function(keepModules, roots) { } }); } + function doBlock(block, newBlock) { block.variables.forEach(function(variable) { var newDependencies = doDeps(variable.dependencies); @@ -286,13 +301,16 @@ NormalModule.prototype.createTemplate = function(keepModules, roots) { NormalModule.prototype.getTemplateArguments = function(keepModules) { var list = []; + function doDep(dep) { - if(dep.module && keepModules.indexOf(dep.module) < 0) + if (dep.module && keepModules.indexOf(dep.module) < 0) list.push(dep.module); } + function doVariable(variable) { variable.dependencies.forEach(doDep); } + function doBlock(block) { block.variables.forEach(doVariable); block.dependencies.forEach(doDep); diff --git a/lib/NormalModuleFactory.js b/lib/NormalModuleFactory.js index b0f98e15b..f44402a2b 100644 --- a/lib/NormalModuleFactory.js +++ b/lib/NormalModuleFactory.js @@ -22,26 +22,26 @@ function NormalModuleFactory(context, resolvers, parser, options) { var resolver = this.applyPluginsWaterfall("resolver", null); // Ignored - if(!resolver) return callback(); + if (!resolver) return callback(); resolver(result, function onDoneResolving(err, data) { - if(err) return callback(err); + if (err) return callback(err); // Ignored - if(!data) return callback(); + if (!data) return callback(); // direct module - if(typeof data.source === "function") + if (typeof data.source === "function") return callback(null, data); this.applyPluginsAsyncWaterfall("after-resolve", data, function(err, result) { - if(err) return callback(err); + if (err) return callback(err); // Ignored - if(!result) return callback(); + if (!result) return callback(); var createdModule = this.applyPluginsBailResult("create-module", result); - if(!createdModule) { + if (!createdModule) { createdModule = new NormalModule( result.request, result.userRequest, @@ -75,16 +75,16 @@ function NormalModuleFactory(context, resolvers, parser, options) { this.resolveRequestArray(context, elements, this.resolvers.loader, callback); }.bind(this), function(callback) { - if(resource === "" || resource[0] === "?") + if (resource === "" || resource[0] === "?") return callback(null, resource); this.resolvers.normal.resolve(context, resource, callback); }.bind(this) ], function(err, results) { - if(err) return callback(err); + if (err) return callback(err); var loaders = results[0]; resource = results[1]; - if(resource === false) + if (resource === false) return callback(null, new RawModule("/* (ignored) */", "ignored " + context + " " + request, @@ -92,14 +92,14 @@ function NormalModuleFactory(context, resolvers, parser, options) { var userRequest = loaders.concat([resource]).join("!"); - if(noPrePostAutoLoaders) + if (noPrePostAutoLoaders) return onDoneResolving.call(this); - if(noAutoLoaders) { + if (noAutoLoaders) { async.parallel([ this.resolveRequestArray.bind(this, context, noPostAutoLoaders ? [] : this.postLoaders.match(resource), this.resolvers.loader), this.resolveRequestArray.bind(this, context, this.preLoaders.match(resource), this.resolvers.loader) ], function(err, results) { - if(err) return callback(err); + if (err) return callback(err); loaders = results[0].concat(loaders).concat(results[1]); onDoneResolving.call(this); }.bind(this)); @@ -109,11 +109,12 @@ function NormalModuleFactory(context, resolvers, parser, options) { this.resolveRequestArray.bind(this, context, this.loaders.match(resource), this.resolvers.loader), this.resolveRequestArray.bind(this, context, this.preLoaders.match(resource), this.resolvers.loader) ], function(err, results) { - if(err) return callback(err); + if (err) return callback(err); loaders = results[0].concat(loaders).concat(results[1]).concat(results[2]); onDoneResolving.call(this); }.bind(this)); } + function onDoneResolving() { callback(null, { context: context, @@ -140,15 +141,15 @@ NormalModuleFactory.prototype.create = function(context, dependency, callback) { request: request, dependency: dependency }, function(err, result) { - if(err) return callback(err); + if (err) return callback(err); // Ignored - if(!result) return callback(); + if (!result) return callback(); var factory = this.applyPluginsWaterfall("factory", null); // Ignored - if(!factory) return callback(); + if (!factory) return callback(); factory(result, callback); @@ -156,9 +157,9 @@ NormalModuleFactory.prototype.create = function(context, dependency, callback) { }; NormalModuleFactory.prototype.resolveRequestArray = function resolveRequestArray(context, array, resolver, callback) { - if(array.length === 0) return callback(null, []); + if (array.length === 0) return callback(null, []); async.map(array, function(item, callback) { - if(item === "" || item[0] === "?") + if (item === "" || item[0] === "?") return callback(null, item); resolver.resolve(context, item, callback); }, callback); diff --git a/lib/NormalModuleReplacementPlugin.js b/lib/NormalModuleReplacementPlugin.js index c0a3f96e2..24d354d80 100644 --- a/lib/NormalModuleReplacementPlugin.js +++ b/lib/NormalModuleReplacementPlugin.js @@ -4,6 +4,7 @@ */ var path = require("path"); + function NormalModuleReplacementPlugin(resourceRegExp, newResource) { this.resourceRegExp = resourceRegExp; this.newResource = newResource; @@ -14,8 +15,8 @@ NormalModuleReplacementPlugin.prototype.apply = function(compiler) { var newResource = this.newResource; compiler.plugin("normal-module-factory", function(nmf) { nmf.plugin("before-resolve", function(result, callback) { - if(!result) return callback(); - if(resourceRegExp.test(result.request)) { + if (!result) return callback(); + if (resourceRegExp.test(result.request)) { if (typeof newResource === "function") { newResource(result); } else { @@ -25,8 +26,8 @@ NormalModuleReplacementPlugin.prototype.apply = function(compiler) { return callback(null, result); }); nmf.plugin("after-resolve", function(result, callback) { - if(!result) return callback(); - if(resourceRegExp.test(result.resource)) { + if (!result) return callback(); + if (resourceRegExp.test(result.resource)) { if (typeof newResource === "function") { newResource(result); } else { diff --git a/lib/NullFactory.js b/lib/NullFactory.js index 541c44a87..46ff4c179 100644 --- a/lib/NullFactory.js +++ b/lib/NullFactory.js @@ -2,8 +2,7 @@ MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ -function NullFactory() { -} +function NullFactory() {} module.exports = NullFactory; NullFactory.prototype.create = function(context, dependency, callback) { diff --git a/lib/OldWatchingPlugin.js b/lib/OldWatchingPlugin.js index 5f1754e44..558a0f228 100644 --- a/lib/OldWatchingPlugin.js +++ b/lib/OldWatchingPlugin.js @@ -4,8 +4,7 @@ */ var OldNodeWatchFileSystem = require("./node/OldNodeWatchFileSystem"); -function OldWatchingPlugin() { -} +function OldWatchingPlugin() {} module.exports = OldWatchingPlugin; OldWatchingPlugin.prototype.apply = function(compiler) { diff --git a/lib/OptionsApply.js b/lib/OptionsApply.js index 8c1819f53..a7e408d7b 100644 --- a/lib/OptionsApply.js +++ b/lib/OptionsApply.js @@ -2,10 +2,9 @@ MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ -function OptionsApply() { -} +function OptionsApply() {} module.exports = OptionsApply; -OptionsApply.prototype.process = function(/* options, compiler */) { +OptionsApply.prototype.process = function( /* options, compiler */ ) { }; diff --git a/lib/Parser.js b/lib/Parser.js index 7fcdd071d..e9aa8ec6d 100644 --- a/lib/Parser.js +++ b/lib/Parser.js @@ -20,193 +20,193 @@ module.exports = Parser; Parser.prototype = Object.create(Tapable.prototype); Parser.prototype.initializeEvaluating = function() { function joinRanges(startRange, endRange) { - if(!endRange) return startRange; - if(!startRange) return endRange; + if (!endRange) return startRange; + if (!startRange) return endRange; return [startRange[0], endRange[1]]; } this.plugin("evaluate Literal", function(expr) { - switch(typeof expr.value) { - case "number": - return new BasicEvaluatedExpression().setNumber(expr.value).setRange(expr.range); - case "string": - return new BasicEvaluatedExpression().setString(expr.value).setRange(expr.range); - case "boolean": - return new BasicEvaluatedExpression().setBoolean(expr.value).setRange(expr.range); + switch (typeof expr.value) { + case "number": + return new BasicEvaluatedExpression().setNumber(expr.value).setRange(expr.range); + case "string": + return new BasicEvaluatedExpression().setString(expr.value).setRange(expr.range); + case "boolean": + return new BasicEvaluatedExpression().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.plugin("evaluate LogicalExpression", function(expr) { - if(expr.operator === "&&") { + if (expr.operator === "&&") { var left = this.evaluateExpression(expr.left); var leftAsBool = left && left.asBool(); - if(leftAsBool === false) return left.setRange(expr.range); - if(leftAsBool !== true) return; + if (leftAsBool === false) return left.setRange(expr.range); + if (leftAsBool !== true) return; var right = this.evaluateExpression(expr.right); return right.setRange(expr.range); - } else if(expr.operator === "||") { + } else if (expr.operator === "||") { var left = this.evaluateExpression(expr.left); var leftAsBool = left && left.asBool(); - if(leftAsBool === true) return left.setRange(expr.range); - if(leftAsBool !== false) return; + if (leftAsBool === true) return left.setRange(expr.range); + if (leftAsBool !== false) return; var right = this.evaluateExpression(expr.right); return right.setRange(expr.range); } }); this.plugin("evaluate BinaryExpression", function(expr) { - if(expr.operator === "+") { + if (expr.operator === "+") { var left = this.evaluateExpression(expr.left); var right = this.evaluateExpression(expr.right); - if(!left || !right) return; + if (!left || !right) return; var res = new BasicEvaluatedExpression(); - if(left.isString()) { - if(right.isString()) { + if (left.isString()) { + if (right.isString()) { res.setString(left.string + right.string); - } else if(right.isNumber()) { + } else if (right.isNumber()) { res.setString(left.string + right.number); - } else if(right.isWrapped() && right.prefix && right.prefix.isString()) { + } else if (right.isWrapped() && right.prefix && right.prefix.isString()) { res.setWrapped( new BasicEvaluatedExpression() - .setString(left.string + right.prefix.string) - .setRange(joinRanges(left.range, right.prefix.range)), + .setString(left.string + right.prefix.string) + .setRange(joinRanges(left.range, right.prefix.range)), right.postfix); } else { res.setWrapped(left, null); } - } else if(left.isNumber()) { - if(right.isString()) { + } else if (left.isNumber()) { + if (right.isString()) { res.setString(left.number + right.string); - } else if(right.isNumber()) { + } else if (right.isNumber()) { res.setNumber(left.number + right.number); } - } else if(left.isWrapped()) { - if(left.postfix && left.postfix.isString() && right.isString()) { + } else if (left.isWrapped()) { + if (left.postfix && left.postfix.isString() && right.isString()) { res.setWrapped(left.prefix, new BasicEvaluatedExpression() - .setString(left.postfix.string + right.string) - .setRange(joinRanges(left.postfix.range, right.range)) + .setString(left.postfix.string + right.string) + .setRange(joinRanges(left.postfix.range, right.range)) ); - } else if(left.postfix && left.postfix.isString() && right.isNumber()) { + } else if (left.postfix && left.postfix.isString() && right.isNumber()) { res.setWrapped(left.prefix, new BasicEvaluatedExpression() - .setString(left.postfix.string + right.number) - .setRange(joinRanges(left.postfix.range, right.range)) + .setString(left.postfix.string + right.number) + .setRange(joinRanges(left.postfix.range, right.range)) ); - } else if(right.isString()) { + } else if (right.isString()) { res.setWrapped(left.prefix, right); - } else if(right.isNumber()) { + } else if (right.isNumber()) { res.setWrapped(left.prefix, new BasicEvaluatedExpression() - .setString(right.number + "") - .setRange(right.range)); + .setString(right.number + "") + .setRange(right.range)); } else { res.setWrapped(left.prefix, new BasicEvaluatedExpression()); } } else { - if(right.isString()) { + if (right.isString()) { res.setWrapped(null, right); } } res.setRange(expr.range); return res; - } else if(expr.operator === "-") { + } else if (expr.operator === "-") { var left = this.evaluateExpression(expr.left); var right = this.evaluateExpression(expr.right); - if(!left || !right) return; - if(!left.isNumber() || !right.isNumber()) return; + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; var res = new BasicEvaluatedExpression(); res.setNumber(left.number - right.number); res.setRange(expr.range); return res; - } else if(expr.operator === "*") { + } else if (expr.operator === "*") { var left = this.evaluateExpression(expr.left); var right = this.evaluateExpression(expr.right); - if(!left || !right) return; - if(!left.isNumber() || !right.isNumber()) return; + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; var res = new BasicEvaluatedExpression(); res.setNumber(left.number * right.number); res.setRange(expr.range); return res; - } else if(expr.operator === "/") { + } else if (expr.operator === "/") { var left = this.evaluateExpression(expr.left); var right = this.evaluateExpression(expr.right); - if(!left || !right) return; - if(!left.isNumber() || !right.isNumber()) return; + if (!left || !right) return; + if (!left.isNumber() || !right.isNumber()) return; var res = new BasicEvaluatedExpression(); res.setNumber(left.number / right.number); res.setRange(expr.range); return res; - } else if(expr.operator === "==" || expr.operator === "===") { + } else if (expr.operator === "==" || expr.operator === "===") { var left = this.evaluateExpression(expr.left); var right = this.evaluateExpression(expr.right); - if(!left || !right) return; + if (!left || !right) return; var res = new BasicEvaluatedExpression(); res.setRange(expr.range); - if(left.isString() && right.isString()) { + if (left.isString() && right.isString()) { return res.setBoolean(left.string === right.string); - } else if(left.isNumber() && right.isNumber()) { + } else if (left.isNumber() && right.isNumber()) { return res.setBoolean(left.number === right.number); - } else if(left.isBoolean() && right.isBoolean()) { + } else if (left.isBoolean() && right.isBoolean()) { return res.setBoolean(left.bool === right.bool); } - } else if(expr.operator === "!=" || expr.operator === "!==") { + } else if (expr.operator === "!=" || expr.operator === "!==") { var left = this.evaluateExpression(expr.left); var right = this.evaluateExpression(expr.right); - if(!left || !right) return; + if (!left || !right) return; var res = new BasicEvaluatedExpression(); res.setRange(expr.range); - if(left.isString() && right.isString()) { + if (left.isString() && right.isString()) { return res.setBoolean(left.string !== right.string); - } else if(left.isNumber() && right.isNumber()) { + } else if (left.isNumber() && right.isNumber()) { return res.setBoolean(left.number !== right.number); - } else if(left.isBoolean() && right.isBoolean()) { + } else if (left.isBoolean() && right.isBoolean()) { return res.setBoolean(left.bool !== right.bool); } } }); this.plugin("evaluate UnaryExpression", function(expr) { - if(expr.operator === "typeof") { - if(expr.argument.type === "Identifier") { + if (expr.operator === "typeof") { + if (expr.argument.type === "Identifier") { var name = this.scope.renames["$" + expr.argument.name] || expr.argument.name; - if(this.scope.definitions.indexOf(name) === -1) { + if (this.scope.definitions.indexOf(name) === -1) { var res = this.applyPluginsBailResult("evaluate typeof " + name, expr); - if(res !== undefined) return res; + if (res !== undefined) return res; } } - if(expr.argument.type === "MemberExpression") { + if (expr.argument.type === "MemberExpression") { var expression = expr.argument; var exprName = []; - while(expression.type === "MemberExpression" && !expression.computed) { + while (expression.type === "MemberExpression" && !expression.computed) { exprName.unshift(this.scope.renames["$" + expression.property.name] || expression.property.name); expression = expression.object; } - if(expression.type === "Identifier") { + if (expression.type === "Identifier") { exprName.unshift(this.scope.renames["$" + expression.name] || expression.name); - if(this.scope.definitions.indexOf(name) === -1) { + if (this.scope.definitions.indexOf(name) === -1) { exprName = exprName.join("."); var res = this.applyPluginsBailResult("evaluate typeof " + exprName, expr); - if(res !== undefined) return res; + if (res !== undefined) return res; } } } - if(expr.argument.type === "FunctionExpression") { + if (expr.argument.type === "FunctionExpression") { return new BasicEvaluatedExpression().setString("function").setRange(expr.range); } var arg = this.evaluateExpression(expr.argument); - if(arg.isString() || arg.isWrapped()) return new BasicEvaluatedExpression().setString("string").setRange(expr.range); - else if(arg.isNumber()) return new BasicEvaluatedExpression().setString("number").setRange(expr.range); - else if(arg.isBoolean()) return new BasicEvaluatedExpression().setString("boolean").setRange(expr.range); - else if(arg.isArray() || arg.isConstArray() || arg.isRegExp()) return new BasicEvaluatedExpression().setString("object").setRange(expr.range); - } else if(expr.operator === "!") { + if (arg.isString() || arg.isWrapped()) return new BasicEvaluatedExpression().setString("string").setRange(expr.range); + else if (arg.isNumber()) return new BasicEvaluatedExpression().setString("number").setRange(expr.range); + else if (arg.isBoolean()) return new BasicEvaluatedExpression().setString("boolean").setRange(expr.range); + else if (arg.isArray() || arg.isConstArray() || arg.isRegExp()) return new BasicEvaluatedExpression().setString("object").setRange(expr.range); + } else if (expr.operator === "!") { var argument = this.evaluateExpression(expr.argument); - if(!argument) return; - if(argument.isBoolean()) { + if (!argument) return; + if (argument.isBoolean()) { return new BasicEvaluatedExpression().setBoolean(!argument.bool).setRange(expr.range); - } else if(argument.isString()) { + } else if (argument.isString()) { return new BasicEvaluatedExpression().setBoolean(!argument.string).setRange(expr.range); - } else if(argument.isNumber()) { + } else if (argument.isNumber()) { return new BasicEvaluatedExpression().setBoolean(!argument.number).setRange(expr.range); } } @@ -216,9 +216,9 @@ Parser.prototype.initializeEvaluating = function() { }); this.plugin("evaluate Identifier", function(expr) { var name = this.scope.renames["$" + expr.name] || expr.name; - if(this.scope.definitions.indexOf(expr.name) === -1) { + if (this.scope.definitions.indexOf(expr.name) === -1) { var result = this.applyPluginsBailResult("evaluate Identifier " + name, expr); - if(result) return result; + if (result) return result; return new BasicEvaluatedExpression().setIdentifier(name).setRange(expr.range); } else { return this.applyPluginsBailResult("evaluate defined Identifier " + name, expr); @@ -227,18 +227,18 @@ Parser.prototype.initializeEvaluating = function() { this.plugin("evaluate MemberExpression", function(expression) { var expr = expression; var exprName = []; - while(expr.type === "MemberExpression" && !expr.computed) { + while (expr.type === "MemberExpression" && !expr.computed) { exprName.unshift(expr.property.name); expr = expr.object; } - if(expr.type === "Identifier") { + if (expr.type === "Identifier") { var name = this.scope.renames["$" + expr.name] || expr.name; - if(this.scope.definitions.indexOf(name) === -1) { + if (this.scope.definitions.indexOf(name) === -1) { exprName.unshift(name); exprName = exprName.join("."); - if(this.scope.definitions.indexOf(expr.name) === -1) { + if (this.scope.definitions.indexOf(expr.name) === -1) { var result = this.applyPluginsBailResult("evaluate Identifier " + exprName, expression); - if(result) return result; + if (result) return result; return new BasicEvaluatedExpression().setIdentifier(exprName).setRange(expression.range); } else { return this.applyPluginsBailResult("evaluate defined Identifier " + exprName, expression); @@ -247,54 +247,54 @@ Parser.prototype.initializeEvaluating = function() { } }); this.plugin("evaluate CallExpression", function(expr) { - if(expr.callee.type !== "MemberExpression") return; - if(expr.callee.computed) return; + if (expr.callee.type !== "MemberExpression") return; + if (expr.callee.computed) return; var param = this.evaluateExpression(expr.callee.object); - if(!param) return; + if (!param) return; return this.applyPluginsBailResult("evaluate CallExpression ." + expr.callee.property.name, expr, param); }); this.plugin("evaluate CallExpression .replace", function(expr, param) { - if(!param.isString()) return; - if(expr.arguments.length !== 2) return; + if (!param.isString()) return; + if (expr.arguments.length !== 2) return; var arg1 = this.evaluateExpression(expr.arguments[0]); var arg2 = this.evaluateExpression(expr.arguments[1]); - if(!arg1.isString() && !arg1.isRegExp()) return; + if (!arg1.isString() && !arg1.isRegExp()) return; arg1 = arg1.regExp || arg1.string; - if(!arg2.isString()) return; + if (!arg2.isString()) return; arg2 = arg2.string; return new BasicEvaluatedExpression().setString(param.string.replace(arg1, arg2)).setRange(expr.range); }); ["substr", "substring"].forEach(function(fn) { this.plugin("evaluate CallExpression ." + fn, function(expr, param) { - if(!param.isString()) return; + if (!param.isString()) return; var result, str = param.string; - switch(expr.arguments.length) { - case 1: - var arg1 = this.evaluateExpression(expr.arguments[0]); - if(!arg1.isNumber()) return; - result = str[fn](arg1.number); - break; - case 2: - var arg1 = this.evaluateExpression(expr.arguments[0]); - var arg2 = this.evaluateExpression(expr.arguments[1]); - if(!arg1.isNumber()) return; - if(!arg2.isNumber()) return; - result = str[fn](arg1.number, arg2.number); - break; - default: - return; + switch (expr.arguments.length) { + case 1: + var arg1 = this.evaluateExpression(expr.arguments[0]); + if (!arg1.isNumber()) return; + result = str[fn](arg1.number); + break; + case 2: + var arg1 = this.evaluateExpression(expr.arguments[0]); + var arg2 = this.evaluateExpression(expr.arguments[1]); + if (!arg1.isNumber()) return; + if (!arg2.isNumber()) return; + result = str[fn](arg1.number, arg2.number); + break; + default: + return; } return new BasicEvaluatedExpression().setString(result).setRange(expr.range); }); }, this); this.plugin("evaluate CallExpression .split", function(expr, param) { - if(!param.isString()) return; - if(expr.arguments.length !== 1) return; + if (!param.isString()) return; + if (expr.arguments.length !== 1) return; var result; var arg = this.evaluateExpression(expr.arguments[0]); - if(arg.isString()) { + if (arg.isString()) { result = param.string.split(arg.string); - } else if(arg.isRegExp()) { + } else if (arg.isRegExp()) { result = param.string.split(arg.regExp); } else return; return new BasicEvaluatedExpression().setArray(result).setRange(expr.range); @@ -302,16 +302,16 @@ Parser.prototype.initializeEvaluating = function() { this.plugin("evaluate ConditionalExpression", function(expr) { var condition = this.evaluateExpression(expr.test); var conditionValue = condition.asBool(); - if(conditionValue === undefined) { + if (conditionValue === undefined) { var consequent = this.evaluateExpression(expr.consequent); var alternate = this.evaluateExpression(expr.alternate); - if(!consequent || !alternate) return; + if (!consequent || !alternate) return; var res = new BasicEvaluatedExpression(); - if(consequent.isConditional()) + if (consequent.isConditional()) res.setOptions(consequent.options); else res.setOptions([consequent]); - if(alternate.isConditional()) + if (alternate.isConditional()) res.addOptions(alternate.options); else res.addOptions([alternate]); @@ -325,15 +325,17 @@ Parser.prototype.initializeEvaluating = function() { var items = expr.elements.map(function(element) { return element !== null && this.evaluateExpression(element); }, this); - if(items.filter(function(i) { return !i; }).length > 0) return; + if (items.filter(function(i) { + return !i; + }).length > 0) return; return new BasicEvaluatedExpression().setItems(items).setRange(expr.range); }); }; Parser.prototype.getRenameIdentifier = function getRenameIdentifier(expr) { var result = this.evaluateExpression(expr); - if(!result) return; - if(result.isIdentifier()) return result.identifier; + if (!result) return; + if (result.isIdentifier()) return result.identifier; return; }; @@ -344,8 +346,8 @@ Parser.prototype.walkStatements = function walkStatements(statements) { }; Parser.prototype.walkStatement = function walkStatement(statement) { - if(this.applyPluginsBailResult("statement", statement) !== undefined) return; - if(this["walk" + statement.type]) + if (this.applyPluginsBailResult("statement", statement) !== undefined) return; + if (this["walk" + statement.type]) this["walk" + statement.type](statement); }; @@ -360,22 +362,22 @@ Parser.prototype.walkExpressionStatement = function walkExpressionStatement(stat Parser.prototype.walkIfStatement = function walkIfStatement(statement) { var result = this.applyPluginsBailResult("statement if", statement); - if(result === undefined) { + if (result === undefined) { this.walkExpression(statement.test); this.walkStatement(statement.consequent); - if(statement.alternate) + if (statement.alternate) this.walkStatement(statement.alternate); } else { - if(result) + if (result) this.walkStatement(statement.consequent); - else if(statement.alternate) + else if (statement.alternate) this.walkStatement(statement.alternate); } }; Parser.prototype.walkLabeledStatement = function walkLabeledStatement(statement) { var result = this.applyPluginsBailResult("label " + statement.label.name, statement); - if(result !== true) + if (result !== true) this.walkStatement(statement.body); }; @@ -390,13 +392,13 @@ Parser.prototype.walkSwitchStatement = function walkSwitchStatement(statement) { }; Parser.prototype.walkReturnStatement = -Parser.prototype.walkThrowStatement = function walkArgumentStatement(statement) { - if(statement.argument) - this.walkExpression(statement.argument); -}; + Parser.prototype.walkThrowStatement = function walkArgumentStatement(statement) { + if (statement.argument) + this.walkExpression(statement.argument); + }; Parser.prototype.walkTryStatement = function walkTryStatement(statement) { - if(this.scope.inTry) { + if (this.scope.inTry) { this.walkStatement(statement.block); } else { this.scope.inTry = true; @@ -404,32 +406,32 @@ Parser.prototype.walkTryStatement = function walkTryStatement(statement) { this.scope.inTry = false; } this.walkCatchClauses(statement.handlers); - if(statement.finalizer) + if (statement.finalizer) this.walkStatement(statement.finalizer); }; Parser.prototype.walkWhileStatement = -Parser.prototype.walkDoWhileStatement = function walkLoopStatement(statement) { - this.walkExpression(statement.test); - this.walkStatement(statement.body); -}; + Parser.prototype.walkDoWhileStatement = function walkLoopStatement(statement) { + this.walkExpression(statement.test); + this.walkStatement(statement.body); + }; Parser.prototype.walkForStatement = function walkForStatement(statement) { - if(statement.init) { - if(statement.init.type === "VariableDeclaration") + if (statement.init) { + if (statement.init.type === "VariableDeclaration") this.walkStatement(statement.init); else this.walkExpression(statement.init); } - if(statement.test) + if (statement.test) this.walkExpression(statement.test); - if(statement.update) + if (statement.update) this.walkExpression(statement.update); this.walkStatement(statement.body); }; Parser.prototype.walkForInStatement = function walkForInStatement(statement) { - if(statement.left.type === "VariableDeclaration") + if (statement.left.type === "VariableDeclaration") this.walkStatement(statement.left); else this.walkExpression(statement.left); @@ -442,7 +444,7 @@ Parser.prototype.walkFunctionDeclaration = function walkFunctionDeclaration(stat this.scope.renames["$" + statement.id.name] = undefined; this.scope.definitions.push(statement.id.name); this.inScope(statement.params, function() { - if(statement.body.type === "BlockStatement") + if (statement.body.type === "BlockStatement") this.walkStatement(statement.body); else this.walkExpression(statement.body); @@ -450,13 +452,13 @@ Parser.prototype.walkFunctionDeclaration = function walkFunctionDeclaration(stat }; Parser.prototype.walkVariableDeclaration = function walkVariableDeclaration(statement) { - if(statement.declarations) + if (statement.declarations) this.walkVariableDeclarators(statement.declarations); }; Parser.prototype.walkSwitchCases = function walkSwitchCases(switchCases) { switchCases.forEach(function(switchCase) { - if(switchCase.test) + if (switchCase.test) this.walkExpression(switchCase.test); this.walkStatements(switchCase.consequent); }, this); @@ -464,7 +466,7 @@ Parser.prototype.walkSwitchCases = function walkSwitchCases(switchCases) { Parser.prototype.walkCatchClauses = function walkCatchClauses(catchClauses) { catchClauses.forEach(function(catchClause) { - if(catchClause.guard) + if (catchClause.guard) this.walkExpression(catchClause.guard); this.inScope([catchClause.param], function() { this.walkStatement(catchClause.body); @@ -474,45 +476,45 @@ Parser.prototype.walkCatchClauses = function walkCatchClauses(catchClauses) { Parser.prototype.walkVariableDeclarators = function walkVariableDeclarators(declarators) { declarators.forEach(function(declarator) { - switch(declarator.type) { - case "VariableDeclarator": - var renameIdentifier = declarator.init && this.getRenameIdentifier(declarator.init); - if(renameIdentifier && declarator.id.type === "Identifier" && this.applyPluginsBailResult("can-rename " + renameIdentifier, declarator.init)) { - // renaming with "var a = b;" - if(!this.applyPluginsBailResult("rename " + renameIdentifier, declarator.init)) { - this.scope.renames["$" + declarator.id.name] = this.scope.renames["$" + renameIdentifier] || renameIdentifier; - var idx = this.scope.definitions.indexOf(declarator.id.name); - if(idx >= 0) this.scope.definitions.splice(idx, 1); + switch (declarator.type) { + case "VariableDeclarator": + var renameIdentifier = declarator.init && this.getRenameIdentifier(declarator.init); + if (renameIdentifier && declarator.id.type === "Identifier" && this.applyPluginsBailResult("can-rename " + renameIdentifier, declarator.init)) { + // renaming with "var a = b;" + if (!this.applyPluginsBailResult("rename " + renameIdentifier, declarator.init)) { + this.scope.renames["$" + declarator.id.name] = this.scope.renames["$" + renameIdentifier] || renameIdentifier; + var idx = this.scope.definitions.indexOf(declarator.id.name); + if (idx >= 0) this.scope.definitions.splice(idx, 1); + } + } else if (declarator.id.type === "Identifier" && !this.applyPluginsBailResult("var " + declarator.id.name, declarator)) { + this.scope.renames["$" + declarator.id.name] = undefined; + this.scope.definitions.push(declarator.id.name); + if (declarator.init) + this.walkExpression(declarator.init); + } else { + this.walkExpression(declarator.id); + if (declarator.init) + this.walkExpression(declarator.init); } - } else if(declarator.id.type === "Identifier" && !this.applyPluginsBailResult("var " + declarator.id.name, declarator)) { - this.scope.renames["$" + declarator.id.name] = undefined; - this.scope.definitions.push(declarator.id.name); - if(declarator.init) - this.walkExpression(declarator.init); - } else { - this.walkExpression(declarator.id); - if(declarator.init) - this.walkExpression(declarator.init); - } - break; + break; } }, this); }; Parser.prototype.walkExpressions = function walkExpressions(expressions) { expressions.forEach(function(expression) { - if(expression) + if (expression) this.walkExpression(expression); }, this); }; Parser.prototype.walkExpression = function walkExpression(expression) { - if(this["walk" + expression.type]) + if (this["walk" + expression.type]) return this["walk" + expression.type](expression); }; Parser.prototype.walkArrayExpression = function walkArrayExpression(expression) { - if(expression.elements) + if (expression.elements) this.walkExpressions(expression.elements); }; @@ -524,7 +526,7 @@ Parser.prototype.walkObjectExpression = function walkObjectExpression(expression Parser.prototype.walkFunctionExpression = function walkFunctionExpression(expression) { this.inScope(expression.params, function() { - if(expression.body.type === "BlockStatement") + if (expression.body.type === "BlockStatement") this.walkStatement(expression.body); else this.walkExpression(expression.body); @@ -532,7 +534,7 @@ Parser.prototype.walkFunctionExpression = function walkFunctionExpression(expres }; Parser.prototype.walkSequenceExpression = function walkSequenceExpression(expression) { - if(expression.expressions) + if (expression.expressions) this.walkExpressions(expression.expressions); }; @@ -541,18 +543,18 @@ Parser.prototype.walkUpdateExpression = function walkUpdateExpression(expression }; Parser.prototype.walkUnaryExpression = function walkUnaryExpression(expression) { - if(expression.operator === "typeof") { + if (expression.operator === "typeof") { var expr = expression.argument; var exprName = []; - while(expr.type === "MemberExpression" && !expr.computed) { + while (expr.type === "MemberExpression" && !expr.computed) { exprName.unshift(expr.property.name); expr = expr.object; } - if(expr.type === "Identifier" && this.scope.definitions.indexOf(expr.name) === -1) { + if (expr.type === "Identifier" && this.scope.definitions.indexOf(expr.name) === -1) { exprName.unshift(this.scope.renames["$" + expr.name] || expr.name); exprName = exprName.join("."); var result = this.applyPluginsBailResult("typeof " + exprName, expression); - if(result === true) + if (result === true) return; } } @@ -560,26 +562,26 @@ Parser.prototype.walkUnaryExpression = function walkUnaryExpression(expression) }; Parser.prototype.walkBinaryExpression = -Parser.prototype.walkLogicalExpression = function walkLeftRightExpression(expression) { - this.walkExpression(expression.left); - this.walkExpression(expression.right); -}; + Parser.prototype.walkLogicalExpression = function walkLeftRightExpression(expression) { + this.walkExpression(expression.left); + this.walkExpression(expression.right); + }; Parser.prototype.walkAssignmentExpression = function walkAssignmentExpression(expression) { var renameIdentifier = this.getRenameIdentifier(expression.right); - if(expression.left.type === "Identifier" && renameIdentifier && this.applyPluginsBailResult("can-rename " + renameIdentifier, expression.right)) { + if (expression.left.type === "Identifier" && renameIdentifier && this.applyPluginsBailResult("can-rename " + renameIdentifier, expression.right)) { // renaming "a = b;" - if(!this.applyPluginsBailResult("rename " + renameIdentifier, expression.right)) { + if (!this.applyPluginsBailResult("rename " + renameIdentifier, expression.right)) { this.scope.renames["$" + expression.left.name] = renameIdentifier; var idx = this.scope.definitions.indexOf(expression.left.name); - if(idx >= 0) this.scope.definitions.splice(idx, 1); + if (idx >= 0) this.scope.definitions.splice(idx, 1); } - } else if(expression.left.type === "Identifier") { - if(!this.applyPluginsBailResult("assigned " + expression.left.name, expression)) { + } else if (expression.left.type === "Identifier") { + if (!this.applyPluginsBailResult("assigned " + expression.left.name, expression)) { this.walkExpression(expression.right); } this.scope.renames["$" + expression.left.name] = undefined; - if(!this.applyPluginsBailResult("assign " + expression.left.name, expression)) { + if (!this.applyPluginsBailResult("assign " + expression.left.name, expression)) { this.walkExpression(expression.left); } } else { @@ -591,22 +593,22 @@ Parser.prototype.walkAssignmentExpression = function walkAssignmentExpression(ex Parser.prototype.walkConditionalExpression = function walkConditionalExpression(expression) { var result = this.applyPluginsBailResult("expression ?:", expression); - if(result === undefined) { + if (result === undefined) { this.walkExpression(expression.test); this.walkExpression(expression.consequent); - if(expression.alternate) + if (expression.alternate) this.walkExpression(expression.alternate); } else { - if(result) + if (result) this.walkExpression(expression.consequent); - else if(expression.alternate) + else if (expression.alternate) this.walkExpression(expression.alternate); } }; Parser.prototype.walkNewExpression = function walkNewExpression(expression) { this.walkExpression(expression.callee); - if(expression.arguments) + if (expression.arguments) this.walkExpressions(expression.arguments); }; @@ -615,8 +617,8 @@ Parser.prototype.walkCallExpression = function walkCallExpression(expression) { var params = functionExpression.params; var args = args.map(function(arg) { var renameIdentifier = this.getRenameIdentifier(arg); - if(renameIdentifier && this.applyPluginsBailResult("can-rename " + renameIdentifier, arg)) { - if(!this.applyPluginsBailResult("rename " + renameIdentifier, arg)) + if (renameIdentifier && this.applyPluginsBailResult("can-rename " + renameIdentifier, arg)) { + if (!this.applyPluginsBailResult("rename " + renameIdentifier, arg)) return renameIdentifier; } this.walkExpression(arg); @@ -625,35 +627,35 @@ Parser.prototype.walkCallExpression = function walkCallExpression(expression) { return !args[idx]; }), function() { args.forEach(function(arg, idx) { - if(!arg) return; - if(!params[idx] || params[idx].type !== "Identifier") return; + if (!arg) return; + if (!params[idx] || params[idx].type !== "Identifier") return; this.scope.renames["$" + params[idx].name] = arg; }, this); - if(functionExpression.body.type === "BlockStatement") + if (functionExpression.body.type === "BlockStatement") this.walkStatement(functionExpression.body); else this.walkExpression(functionExpression.body); }.bind(this)); } - if(expression.callee.type === "MemberExpression" && expression.callee.object.type === "FunctionExpression" && !expression.callee.computed && ["call", "bind"].indexOf(expression.callee.property.name) >= 0 && expression.arguments && expression.arguments.length > 1) { + if (expression.callee.type === "MemberExpression" && expression.callee.object.type === "FunctionExpression" && !expression.callee.computed && ["call", "bind"].indexOf(expression.callee.property.name) >= 0 && expression.arguments && expression.arguments.length > 1) { // (function(...) { }.call/bind(?, ...)) walkIIFE.call(this, expression.callee.object, expression.arguments.slice(1)); this.walkExpression(expression.arguments[0]); - } else if(expression.callee.type === "FunctionExpression" && expression.arguments) { + } else if (expression.callee.type === "FunctionExpression" && expression.arguments) { // (function(...) { }(...)) walkIIFE.call(this, expression.callee, expression.arguments); } else { var callee = this.evaluateExpression(expression.callee); - if(callee.isIdentifier()) { + if (callee.isIdentifier()) { var result = this.applyPluginsBailResult("call " + callee.identifier, expression); - if(result === true) + if (result === true) return; } - if(expression.callee) + if (expression.callee) this.walkExpression(expression.callee); - if(expression.arguments) + if (expression.arguments) this.walkExpressions(expression.arguments); } }; @@ -661,26 +663,26 @@ Parser.prototype.walkCallExpression = function walkCallExpression(expression) { Parser.prototype.walkMemberExpression = function walkMemberExpression(expression) { var expr = expression; var exprName = []; - while(expr.type === "MemberExpression" && !expr.computed) { + while (expr.type === "MemberExpression" && !expr.computed) { exprName.unshift(expr.property.name); expr = expr.object; } - if(expr.type === "Identifier" && this.scope.definitions.indexOf(expr.name) === -1) { + if (expr.type === "Identifier" && this.scope.definitions.indexOf(expr.name) === -1) { exprName.unshift(this.scope.renames["$" + expr.name] || expr.name); exprName = exprName.join("."); var result = this.applyPluginsBailResult("expression " + exprName, expression); - if(result === true) + if (result === true) return; } this.walkExpression(expression.object); - if(expression.computed === true) + if (expression.computed === true) this.walkExpression(expression.property); }; Parser.prototype.walkIdentifier = function walkIdentifier(expression) { - if(this.scope.definitions.indexOf(expression.name) === -1) { + if (this.scope.definitions.indexOf(expression.name) === -1) { var result = this.applyPluginsBailResult("expression " + (this.scope.renames["$" + expression.name] || expression.name), expression); - if(result === true) + if (result === true) return; } }; @@ -693,8 +695,8 @@ Parser.prototype.inScope = function inScope(params, fn) { renames: Object.create(oldScope.renames) }; params.forEach(function(param) { - if(typeof param !== "string") { - if(param.type !== "Identifier") + if (typeof param !== "string") { + if (param.type !== "Identifier") return; param = param.name; } @@ -707,77 +709,102 @@ Parser.prototype.inScope = function inScope(params, fn) { Parser.prototype.evaluateExpression = function evaluateExpression(expression) { var result = this.applyPluginsBailResult("evaluate " + expression.type, expression); - if(result !== undefined) + if (result !== undefined) return result; return new BasicEvaluatedExpression().setRange(expression.range); }; Parser.prototype.parseString = function parseString(expression) { - switch(expression.type) { - case "BinaryExpression": - if(expression.operator === "+") - return this.parseString(expression.left) + this.parseString(expression.right); - break; - case "Literal": - return expression.value + ""; + switch (expression.type) { + case "BinaryExpression": + if (expression.operator === "+") + return this.parseString(expression.left) + this.parseString(expression.right); + break; + case "Literal": + return expression.value + ""; } throw new Error(expression.type + " is not supported as parameter for require"); }; Parser.prototype.parseCalculatedString = function parseCalculatedString(expression) { - switch(expression.type) { - case "BinaryExpression": - if(expression.operator === "+") { - var left = this.parseCalculatedString(expression.left); - var right = this.parseCalculatedString(expression.right); - if(left.code) { - return {range: left.range, value: left.value, code: true}; - } else if(right.code) { - return {range: [left.range[0], right.range ? right.range[1] : left.range[1]], value: left.value + right.value, code: true}; - } else { - return {range: [left.range[0], right.range[1]], value: left.value + right.value}; + switch (expression.type) { + case "BinaryExpression": + if (expression.operator === "+") { + var left = this.parseCalculatedString(expression.left); + var right = this.parseCalculatedString(expression.right); + if (left.code) { + return { + range: left.range, + value: left.value, + code: true + }; + } else if (right.code) { + return { + range: [left.range[0], right.range ? right.range[1] : left.range[1]], + value: left.value + right.value, + code: true + }; + } else { + return { + range: [left.range[0], right.range[1]], + value: left.value + right.value + }; + } } - } - break; - case "ConditionalExpression": - var consequent = this.parseCalculatedString(expression.consequent); - var alternate = this.parseCalculatedString(expression.alternate); - var items = []; - if(consequent.conditional) - Array.prototype.push.apply(items, consequent.conditional); - else if(!consequent.code) - items.push(consequent); - else break; - if(alternate.conditional) - Array.prototype.push.apply(items, alternate.conditional); - else if(!alternate.code) - items.push(alternate); - else break; - return {value: "", code: true, conditional: items}; - case "Literal": - return {range: expression.range, value: expression.value + ""}; + break; + case "ConditionalExpression": + var consequent = this.parseCalculatedString(expression.consequent); + var alternate = this.parseCalculatedString(expression.alternate); + var items = []; + if (consequent.conditional) + Array.prototype.push.apply(items, consequent.conditional); + else if (!consequent.code) + items.push(consequent); + else break; + if (alternate.conditional) + Array.prototype.push.apply(items, alternate.conditional); + else if (!alternate.code) + items.push(alternate); + else break; + return { + value: "", + code: true, + conditional: items + }; + case "Literal": + return { + range: expression.range, + value: expression.value + "" + }; } - return {value: "", code: true}; + return { + value: "", + code: true + }; }; ["parseString", "parseCalculatedString"].forEach(function(fn) { Parser.prototype[fn + "Array"] = function parseXXXArray(expression) { - switch(expression.type) { - case "ArrayExpression": - var arr = []; - if(expression.elements) - expression.elements.forEach(function(expr) { - arr.push(this[fn](expr)); - }, this); - return arr; + switch (expression.type) { + case "ArrayExpression": + var arr = []; + if (expression.elements) + expression.elements.forEach(function(expr) { + arr.push(this[fn](expr)); + }, this); + return arr; } return [this[fn](expression)]; }; }); Parser.prototype.parse = function parse(source, initialState) { - var ast = esprima.parse(source, {range: true, loc: true, raw: true}); - if(!ast || typeof ast !== "object") + var ast = esprima.parse(source, { + range: true, + loc: true, + raw: true + }); + if (!ast || typeof ast !== "object") throw new Error("Source couldn't be parsed"); var oldScope = this.scope; var oldState = this.state; @@ -787,7 +814,7 @@ Parser.prototype.parse = function parse(source, initialState) { renames: {} }; var state = this.state = initialState || {}; - if(this.applyPluginsBailResult("program", ast) === undefined) + if (this.applyPluginsBailResult("program", ast) === undefined) this.walkStatements(ast.body); this.scope = oldScope; this.state = oldState; @@ -795,10 +822,14 @@ Parser.prototype.parse = function parse(source, initialState) { }; Parser.prototype.evaluate = function evaluate(source) { - var ast = esprima.parse("(" + source + ")", {range: true, loc: true, raw: true}); - if(!ast || typeof ast !== "object" || ast.type !== "Program") + var ast = esprima.parse("(" + source + ")", { + range: true, + loc: true, + raw: true + }); + if (!ast || typeof ast !== "object" || ast.type !== "Program") throw new Error("evaluate: Source couldn't be parsed"); - 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); }; diff --git a/lib/PrefetchPlugin.js b/lib/PrefetchPlugin.js index da54ac881..22735453b 100644 --- a/lib/PrefetchPlugin.js +++ b/lib/PrefetchPlugin.js @@ -5,7 +5,7 @@ var PrefetchDependency = require("./dependencies/PrefetchDependency"); function PrefetchPlugin(context, request) { - if(!request) { + if (!request) { this.request = context; } else { this.context = context; diff --git a/lib/ProgressPlugin.js b/lib/ProgressPlugin.js index ebf40e06c..1b660f229 100644 --- a/lib/ProgressPlugin.js +++ b/lib/ProgressPlugin.js @@ -9,7 +9,7 @@ module.exports = ProgressPlugin; ProgressPlugin.prototype.apply = function(compiler) { var handler = this.handler; - if(compiler.compilers) { + if (compiler.compilers) { var states = new Array(compiler.compilers.length); compiler.compilers.forEach(function(compiler, idx) { compiler.apply(new ProgressPlugin(function(p, msg) { @@ -27,11 +27,12 @@ ProgressPlugin.prototype.apply = function(compiler) { var lastModulesCount = 0; var moduleCount = 1; var doneModules = 0; + function update() { handler(0.1 + (doneModules / Math.max(lastModulesCount, moduleCount)) * 0.6, doneModules + "/" + moduleCount + " build modules"); } compiler.plugin("compilation", function(compilation) { - if(compilation.compiler.isChild()) return; + if (compilation.compiler.isChild()) return; lastModulesCount = moduleCount; moduleCount = 0; doneModules = 0; diff --git a/lib/ProvidePlugin.js b/lib/ProvidePlugin.js index 78232bb5f..500611473 100644 --- a/lib/ProvidePlugin.js +++ b/lib/ProvidePlugin.js @@ -19,22 +19,24 @@ ProvidePlugin.prototype.apply = function(compiler) { Object.keys(this.definitions).forEach(function(name) { var request = this.definitions[name]; var splittedName = name.split("."); - if(splittedName.length > 0) { + if (splittedName.length > 0) { splittedName.slice(1).forEach(function(_, i) { var name = splittedName.slice(0, i + 1).join("."); - compiler.parser.plugin("can-rename " + name, function() { return true; }); + compiler.parser.plugin("can-rename " + name, function() { + return true; + }); }); } compiler.parser.plugin("expression " + name, function(expr) { var nameIdentifier = name; var scopedName = name.indexOf(".") >= 0; - if(scopedName) { + if (scopedName) { nameIdentifier = "__webpack_provided_" + name.replace(/\./g, "_dot_"); } - if(!ModuleParserHelpers.addParsedVariable(this, nameIdentifier, "require(" + JSON.stringify(request) + ")")) { + if (!ModuleParserHelpers.addParsedVariable(this, nameIdentifier, "require(" + JSON.stringify(request) + ")")) { return false; } - if(scopedName) { + if (scopedName) { nameIdentifier = "__webpack_provided_" + name.replace(/\./g, "_dot_"); var dep = new ConstDependency(nameIdentifier, expr.range); dep.loc = expr.loc; diff --git a/lib/RawModule.js b/lib/RawModule.js index d30c86b51..109ac72da 100644 --- a/lib/RawModule.js +++ b/lib/RawModule.js @@ -36,7 +36,7 @@ RawModule.prototype.build = function(options, compilation, resolver, fs, callbac }; RawModule.prototype.source = function() { - if(this.useSourceMap) + if (this.useSourceMap) return new OriginalSource(this.sourceStr, this.identifier()); else return new RawSource(this.sourceStr); diff --git a/lib/RecordIdsPlugin.js b/lib/RecordIdsPlugin.js index 421371261..fcbf9e4da 100644 --- a/lib/RecordIdsPlugin.js +++ b/lib/RecordIdsPlugin.js @@ -4,8 +4,7 @@ */ var path = require("path"); -function RecordIdsPlugin() { -} +function RecordIdsPlugin() {} module.exports = RecordIdsPlugin; function makeRelative(compiler, identifier) { @@ -19,24 +18,26 @@ RecordIdsPlugin.prototype.apply = function(compiler) { compiler.plugin("compilation", function(compilation) { compilation.plugin("record-modules", function(modules, records) { records.nextFreeModuleId = compilation.nextFreeModuleId; - if(!records.modules) records.modules = {}; - if(!records.modules.byIdentifier) records.modules.byIdentifier = {}; + if (!records.modules) records.modules = {}; + if (!records.modules.byIdentifier) records.modules.byIdentifier = {}; modules.forEach(function(module) { var identifier = makeRelative(compiler, module.identifier()); records.modules.byIdentifier[identifier] = module.id; }); }); compilation.plugin("revive-modules", function(modules, records) { - if(records.nextFreeModuleId) + if (records.nextFreeModuleId) compilation.nextFreeModuleId = records.nextFreeModuleId; - if(!records.modules || !records.modules.byIdentifier) return; - var usedIds = {0: true}; + if (!records.modules || !records.modules.byIdentifier) return; + var usedIds = { + 0: true + }; modules.forEach(function(module) { - if(module.id !== null) return; + if (module.id !== null) return; var identifier = makeRelative(compiler, module.identifier()); var id = records.modules.byIdentifier[identifier]; - if(id === undefined) return; - if(usedIds[id]) return; + if (id === undefined) return; + if (usedIds[id]) return; usedIds[id] = true; module.id = id; }); @@ -44,50 +45,50 @@ RecordIdsPlugin.prototype.apply = function(compiler) { function getDepBlockIdent(chunk, block) { var ident = []; - if(block.chunks.length > 1) + if (block.chunks.length > 1) ident.push(block.chunks.indexOf(chunk)); - while(block.parent) { + while (block.parent) { var p = block.parent; var idx = p.blocks.indexOf(block); var l = p.blocks.length - 1; ident.unshift(idx + "/" + l); block = block.parent; } - if(!block.identifier) return null; + if (!block.identifier) return null; ident.unshift(makeRelative(compiler, block.identifier())); return ident.join(":"); } compilation.plugin("record-chunks", function(chunks, records) { records.nextFreeChunkId = compilation.nextFreeChunkId; - if(!records.chunks) records.chunks = {}; - if(!records.chunks.byName) records.chunks.byName = {}; - if(!records.chunks.byBlocks) records.chunks.byBlocks = {}; + if (!records.chunks) records.chunks = {}; + if (!records.chunks.byName) records.chunks.byName = {}; + if (!records.chunks.byBlocks) records.chunks.byBlocks = {}; chunks.forEach(function(chunk) { var name = chunk.name; var blockIdents = chunk.blocks.map(getDepBlockIdent.bind(null, chunk)).filter(Boolean); - if(name) records.chunks.byName[name] = chunk.id; + if (name) records.chunks.byName[name] = chunk.id; blockIdents.forEach(function(blockIdent) { records.chunks.byBlocks[blockIdent] = chunk.id; }); }); }); compilation.plugin("revive-chunks", function(chunks, records) { - if(records.nextFreeChunkId) + if (records.nextFreeChunkId) compilation.nextFreeChunkId = records.nextFreeChunkId; - if(!records.chunks) return; + if (!records.chunks) return; var usedIds = {}; - if(records.chunks.byName) { + if (records.chunks.byName) { chunks.forEach(function(chunk) { - if(chunk.id !== null) return; - if(!chunk.name) return; + if (chunk.id !== null) return; + if (!chunk.name) return; var id = records.chunks.byName[chunk.name]; - if(id === undefined) return; - if(usedIds[id]) return; + if (id === undefined) return; + if (usedIds[id]) return; usedIds[id] = true; chunk.id = id; }); } - if(records.chunks.byBlocks) { + if (records.chunks.byBlocks) { var argumentedChunks = chunks.filter(function(chunk) { return chunk.id === null; }).map(function(chunk) { @@ -102,7 +103,7 @@ RecordIdsPlugin.prototype.apply = function(compiler) { argumentedChunks.forEach(function(arg, idx) { arg.blockIdents.forEach(function(blockIdent) { var id = records.chunks.byBlocks[blockIdent]; - if(typeof id !== "number") return; + if (typeof id !== "number") return; var accessor = id + ":" + idx; blockIdentsCount[accessor] = (blockIdentsCount[accessor] || 0) + 1; }); @@ -114,10 +115,10 @@ RecordIdsPlugin.prototype.apply = function(compiler) { }); blockIdentsCount.forEach(function(arg) { var id = arg[1]; - if(usedIds[id]) return; + if (usedIds[id]) return; var idx = arg[2]; var chunk = argumentedChunks[idx].chunk; - if(chunk.id !== null) return; + if (chunk.id !== null) return; usedIds[id] = true; chunk.id = id; }); diff --git a/lib/RequestShortener.js b/lib/RequestShortener.js index 34bba0de5..88e44eb60 100644 --- a/lib/RequestShortener.js +++ b/lib/RequestShortener.js @@ -6,23 +6,23 @@ var path = require("path"); function RequestShortener(directory) { var parentDirectory = path.dirname(directory); - if(/[\/\\]$/.test(directory)) directory = directory.substr(0, directory.length - 1); - if(directory) { + if (/[\/\\]$/.test(directory)) directory = directory.substr(0, directory.length - 1); + if (directory) { var currentDirectoryRegExp = directory.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); currentDirectoryRegExp = new RegExp("^" + currentDirectoryRegExp + "|(!)" + currentDirectoryRegExp, "g"); this.currentDirectoryRegExp = currentDirectoryRegExp; } - if(/[\/\\]$/.test(parentDirectory)) parentDirectory = parentDirectory.substr(0, parentDirectory.length - 1); - if(parentDirectory && parentDirectory !== directory) { + if (/[\/\\]$/.test(parentDirectory)) parentDirectory = parentDirectory.substr(0, parentDirectory.length - 1); + if (parentDirectory && parentDirectory !== directory) { var parentDirectoryRegExp = parentDirectory.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); parentDirectoryRegExp = new RegExp("^" + parentDirectoryRegExp + "|(!)" + parentDirectoryRegExp, "g"); this.parentDirectoryRegExp = parentDirectoryRegExp; } - if(__dirname.length >= 2) { + if (__dirname.length >= 2) { var buildins = path.join(__dirname, ".."); var buildinsAsModule = currentDirectoryRegExp && currentDirectoryRegExp.test(buildins); var buildinsRegExp = buildins.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); @@ -38,15 +38,15 @@ function RequestShortener(directory) { module.exports = RequestShortener; RequestShortener.prototype.shorten = function(request) { - if(!request) + if (!request) return request; - if(this.buildinsAsModule && this.buildinsRegExp) + if (this.buildinsAsModule && this.buildinsRegExp) request = request.replace(this.buildinsRegExp, "!(webpack)"); - if(this.currentDirectoryRegExp) + if (this.currentDirectoryRegExp) request = request.replace(this.currentDirectoryRegExp, "!."); - if(this.parentDirectoryRegExp) + if (this.parentDirectoryRegExp) request = request.replace(this.parentDirectoryRegExp, "!.."); - if(!this.buildinsAsModule && this.buildinsRegExp) + if (!this.buildinsAsModule && this.buildinsRegExp) request = request.replace(this.buildinsRegExp, "!(webpack)"); request = request.replace(/\\/g, "/"); request = request.replace(this.nodeModulesRegExp, "/~/"); diff --git a/lib/RequireJsStuffPlugin.js b/lib/RequireJsStuffPlugin.js index c07939dcf..186f99b95 100644 --- a/lib/RequireJsStuffPlugin.js +++ b/lib/RequireJsStuffPlugin.js @@ -6,14 +6,14 @@ var ConstDependency = require("./dependencies/ConstDependency"); var NullFactory = require("./NullFactory"); -function RequireJsStuffPlugin() { -} +function RequireJsStuffPlugin() {} module.exports = RequireJsStuffPlugin; RequireJsStuffPlugin.prototype.apply = function(compiler) { compiler.plugin("compilation", function(compilation) { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); }); + function remove(expr) { var dep = new ConstDependency(";", expr.range); dep.loc = expr.loc; diff --git a/lib/ResolverPlugin.js b/lib/ResolverPlugin.js index b5382c9ec..4fe261d04 100644 --- a/lib/ResolverPlugin.js +++ b/lib/ResolverPlugin.js @@ -3,9 +3,9 @@ Author Tobias Koppers @sokra */ function ResolverPlugin(plugins, types) { - if(!Array.isArray(plugins)) plugins = [plugins]; - if(!types) types = ["normal"]; - else if(!Array.isArray(types)) types = [types]; + if (!Array.isArray(plugins)) plugins = [plugins]; + if (!types) types = ["normal"]; + else if (!Array.isArray(types)) types = [types]; this.plugins = plugins; this.types = types; diff --git a/lib/SetVarMainTemplatePlugin.js b/lib/SetVarMainTemplatePlugin.js index 2f052b9d8..c4ae378b7 100644 --- a/lib/SetVarMainTemplatePlugin.js +++ b/lib/SetVarMainTemplatePlugin.js @@ -16,7 +16,7 @@ SetVarMainTemplatePlugin.prototype.apply = function(compilation) { hash: hash, chunk: chunk }); - if(this.copyObject) { + if (this.copyObject) { return new ConcatSource("(function(e, a) { for(var i in a) e[i] = a[i]; }(" + varExpression + ", ", source, "))"); } else { @@ -25,7 +25,7 @@ SetVarMainTemplatePlugin.prototype.apply = function(compilation) { } }.bind(this)); mainTemplate.plugin("global-hash-paths", function(paths) { - if(this.varExpression) paths.push(this.varExpression); + if (this.varExpression) paths.push(this.varExpression); return paths; }); mainTemplate.plugin("hash", function(hash) { @@ -34,4 +34,3 @@ SetVarMainTemplatePlugin.prototype.apply = function(compilation) { hash.update(this.copyObject + ""); }.bind(this)); }; - diff --git a/lib/Source.js b/lib/Source.js index e407766d7..05a82ade7 100644 --- a/lib/Source.js +++ b/lib/Source.js @@ -3,4 +3,3 @@ Author Tobias Koppers @sokra */ module.exports = require("webpack-core/lib/Source"); - diff --git a/lib/SourceMapDevToolModuleOptionsPlugin.js b/lib/SourceMapDevToolModuleOptionsPlugin.js index ba7b50cff..c2b2bbb52 100644 --- a/lib/SourceMapDevToolModuleOptionsPlugin.js +++ b/lib/SourceMapDevToolModuleOptionsPlugin.js @@ -12,21 +12,21 @@ module.exports = SourceMapDevToolModuleOptionsPlugin; SourceMapDevToolModuleOptionsPlugin.prototype.apply = function(compilation) { var options = this.options; - if(options.module !== false) { + if (options.module !== false) { compilation.plugin("build-module", function(module) { module.useSourceMap = true; }); } - if(options.lineToLine === true) { + if (options.lineToLine === true) { compilation.plugin("build-module", function(module) { module.lineToLine = true; }); - } else if(options.lineToLine) { + } else if (options.lineToLine) { compilation.plugin("build-module", function(module) { - if(!module.resource) return; + if (!module.resource) return; var resourcePath = module.resource; var idx = resourcePath.indexOf("?"); - if(idx >= 0) resourcePath = resourcePath.substr(0, idx); + if (idx >= 0) resourcePath = resourcePath.substr(0, idx); module.lineToLine = ModuleFilenameHelpers.matchObject(options.lineToLine, resourcePath); }); } diff --git a/lib/SourceMapDevToolPlugin.js b/lib/SourceMapDevToolPlugin.js index c41cc7c04..6b02c2c93 100644 --- a/lib/SourceMapDevToolPlugin.js +++ b/lib/SourceMapDevToolPlugin.js @@ -10,7 +10,7 @@ var ModuleFilenameHelpers = require("./ModuleFilenameHelpers"); var SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin"); function SourceMapDevToolPlugin(options, sourceMappingURLComment, moduleFilenameTemplate, fallbackModuleFilenameTemplate) { - if(!options || typeof options !== "object") { + if (!options || typeof options !== "object") { this.sourceMapFilename = options; this.sourceMappingURLComment = sourceMappingURLComment === false ? false : sourceMappingURLComment || "\n//# sourceMappingURL=[url]"; this.moduleFilenameTemplate = moduleFilenameTemplate || "webpack:///[resourcePath]"; @@ -42,16 +42,16 @@ SourceMapDevToolPlugin.prototype.apply = function(compiler) { chunks.forEach(function(chunk) { chunk.files.filter(ModuleFilenameHelpers.matchObject.bind(undefined, options)).map(function(file) { var asset = this.assets[file]; - if(asset.__SourceMapDevToolData) { + if (asset.__SourceMapDevToolData) { var data = asset.__SourceMapDevToolData; - for(var cachedFile in data) { + for (var cachedFile in data) { this.assets[cachedFile] = data[cachedFile]; - if(cachedFile !== file) + if (cachedFile !== file) chunk.files.push(cachedFile); } return; } - if(asset.sourceAndMap) { + if (asset.sourceAndMap) { var sourceAndMap = asset.sourceAndMap(options); var sourceMap = sourceAndMap.map; var source = sourceAndMap.source; @@ -59,7 +59,7 @@ SourceMapDevToolPlugin.prototype.apply = function(compiler) { var sourceMap = asset.map(options); var source = asset.source(); } - if(sourceMap) { + if (sourceMap) { return { chunk: chunk, file: file, @@ -95,7 +95,7 @@ SourceMapDevToolPlugin.prototype.apply = function(compiler) { return a.length - b.length; }); allModuleFilenames = ModuleFilenameHelpers.replaceDuplicates(allModuleFilenames, function(filename, i, n) { - for(var j = 0; j < n; j++) + for (var j = 0; j < n; j++) filename += "*"; return filename; }); @@ -112,7 +112,7 @@ SourceMapDevToolPlugin.prototype.apply = function(compiler) { var moduleFilenames = task.moduleFilenames; var modules = task.modules; sourceMap.sources = moduleFilenames; - if(sourceMap.sourcesContent) { + if (sourceMap.sourcesContent) { sourceMap.sourcesContent = sourceMap.sourcesContent.map(function(content, i) { return content + "\n\n\n" + ModuleFilenameHelpers.createFooter(modules[i], requestShortener); }); @@ -123,13 +123,14 @@ SourceMapDevToolPlugin.prototype.apply = function(compiler) { sourceMap.file = file; asset.__SourceMapDevToolData = {}; var currentSourceMappingURLComment = sourceMappingURLComment; - if(currentSourceMappingURLComment !== false && /\.css($|\?)/i.test(file)) { + if (currentSourceMappingURLComment !== false && /\.css($|\?)/i.test(file)) { currentSourceMappingURLComment = currentSourceMappingURLComment.replace(/^\n\/\/(.*)$/, "\n/*$1*/"); } - if(sourceMapFilename) { - var filename = file, query = ""; + if (sourceMapFilename) { + var filename = file, + query = ""; var idx = filename.indexOf("?"); - if(idx >= 0) { + if (idx >= 0) { query = filename.substr(idx); filename = filename.substr(0, idx); } @@ -140,7 +141,7 @@ SourceMapDevToolPlugin.prototype.apply = function(compiler) { basename: basename(filename) }); var sourceMapUrl = path.relative(path.dirname(file), sourceMapFile).replace(/\\/g, "/"); - if(currentSourceMappingURLComment !== false) { + if (currentSourceMappingURLComment !== false) { asset.__SourceMapDevToolData[file] = this.assets[file] = new ConcatSource(new RawSource(source), currentSourceMappingURLComment.replace(/\[url\]/g, sourceMapUrl)); } asset.__SourceMapDevToolData[sourceMapFile] = this.assets[sourceMapFile] = new RawSource(JSON.stringify(sourceMap)); @@ -162,7 +163,6 @@ SourceMapDevToolPlugin.prototype.apply = function(compiler) { }; function basename(name) { - if(name.indexOf("/") < 0) return name; + if (name.indexOf("/") < 0) return name; return name.substr(name.lastIndexOf("/") + 1); } - diff --git a/lib/SourceMapSource.js b/lib/SourceMapSource.js index 9dab2e027..e54cdb91e 100644 --- a/lib/SourceMapSource.js +++ b/lib/SourceMapSource.js @@ -3,4 +3,3 @@ Author Tobias Koppers @sokra */ module.exports = require("webpack-core/lib/SourceMapSource"); - diff --git a/lib/Stats.js b/lib/Stats.js index dbdf30fb3..0cf2d416f 100644 --- a/lib/Stats.js +++ b/lib/Stats.js @@ -19,8 +19,11 @@ Stats.prototype.hasErrors = function() { }; Stats.prototype.toJson = function toJson(options, forToString) { - if(!options) options = {}; - function d(v, def) { return v === undefined ? def : v; } + if (!options) options = {}; + + function d(v, def) { + return v === undefined ? def : v; + } var compilation = this.compilation; var requestShortener = new RequestShortener(d(options.context, process.cwd())); var showHash = d(options.hash, true); @@ -39,7 +42,7 @@ Stats.prototype.toJson = function toJson(options, forToString) { var showErrorDetails = d(options.errorDetails, !forToString); var showPublicPath = d(options.publicPath, !forToString); var excludeModules = [].concat(d(options.exclude, [])).map(function(str) { - if(typeof str !== "string") return str; + if (typeof str !== "string") return str; return new RegExp("[\\\\/]" + str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + "([\\\\/]|$|!|\\?)"); }); var sortModules = d(options.modulesSort, "id"); @@ -47,10 +50,10 @@ Stats.prototype.toJson = function toJson(options, forToString) { var sortAssets = d(options.assetsSort, ""); function moduleFilter(module) { - if(!showCachedModules && !module.built) { + if (!showCachedModules && !module.built) { return false; } - if(excludeModules.length === 0) + if (excludeModules.length === 0) return true; var ident = module.identifier(); return !excludeModules.some(function(regExp) { @@ -59,45 +62,50 @@ Stats.prototype.toJson = function toJson(options, forToString) { } function sortByField(field) { - if(!field) return function() { return 0; }; - if(field[0] === "!") { + if (!field) return function() { + return 0; + }; + if (field[0] === "!") { field = field.substr(1); return function(a, b) { - if(a[field] === b[field]) return 0; + if (a[field] === b[field]) return 0; return (a[field] < b[field]) ? 1 : -1; }; } return function(a, b) { - if(a[field] === b[field]) return 0; + if (a[field] === b[field]) return 0; return (a[field] < b[field]) ? -1 : 1; }; } + function formatError(e) { var text = ""; - if(typeof e === "string") - e = {message: e}; - if(e.chunk) { + if (typeof e === "string") + e = { + message: e + }; + if (e.chunk) { text += "chunk " + (e.chunk.name || e.chunk.id) + (e.chunk.entry ? " [entry]" : e.chunk.initial ? " [initial]" : "") + "\n"; } - if(e.file) { + if (e.file) { text += e.file + "\n"; } - if(e.module && e.module.readableIdentifier && typeof e.module.readableIdentifier === "function") { + if (e.module && e.module.readableIdentifier && typeof e.module.readableIdentifier === "function") { text += e.module.readableIdentifier(requestShortener) + "\n"; } text += e.message; - if(showErrorDetails && e.details) text += "\n" + e.details; - if(showErrorDetails && e.missing) text += e.missing.map(function(item) { + if (showErrorDetails && e.details) text += "\n" + e.details; + if (showErrorDetails && e.missing) text += e.missing.map(function(item) { return "\n[" + item + "]"; }).join(""); - if(e.dependencies && e.origin) { + if (e.dependencies && e.origin) { text += "\n @ " + e.origin.readableIdentifier(requestShortener); e.dependencies.forEach(function(dep) { - if(!dep.loc) return; - if(typeof dep.loc === "string") return; - if(!dep.loc.start) return; - if(!dep.loc.end) return; + if (!dep.loc) return; + if (typeof dep.loc === "string") return; + if (!dep.loc.start) return; + if (!dep.loc.end) return; text += " " + dep.loc.start.line + ":" + dep.loc.start.column + "-" + (dep.loc.start.line !== dep.loc.end.line ? dep.loc.end.line + ":" : "") + dep.loc.end.column; }); @@ -109,20 +117,20 @@ Stats.prototype.toJson = function toJson(options, forToString) { warnings: compilation.warnings.map(formatError) }; - if(showVersion) { + if (showVersion) { obj.version = require("../package.json").version; } - if(showHash) obj.hash = this.hash; - if(showTimings && this.startTime && this.endTime) { + if (showHash) obj.hash = this.hash; + if (showTimings && this.startTime && this.endTime) { obj.time = this.endTime - this.startTime; } - if(showPublicPath) { + if (showPublicPath) { obj.publicPath = this.compilation.mainTemplate.getPublicPath({ hash: this.compilation.hash }); } - if(showAssets) { + if (showAssets) { var assetsByFile = {}; obj.assetsByChunkName = {}; obj.assets = Object.keys(compilation.assets).map(function(asset) { @@ -140,13 +148,13 @@ Stats.prototype.toJson = function toJson(options, forToString) { }); compilation.chunks.forEach(function(chunk) { chunk.files.forEach(function(asset) { - if(assetsByFile[asset]) { + if (assetsByFile[asset]) { chunk.ids.forEach(function(id) { assetsByFile[asset].chunks.push(id); }); - if(chunk.name) { + 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; @@ -156,6 +164,7 @@ Stats.prototype.toJson = function toJson(options, forToString) { }); obj.assets.sort(sortByField(sortAssets)); } + function fnModule(module) { var obj = { id: module.id, @@ -176,7 +185,7 @@ Stats.prototype.toJson = function toJson(options, forToString) { errors: module.errors && module.dependenciesErrors && (module.errors.length + module.dependenciesErrors.length), warnings: module.errors && module.dependenciesErrors && (module.warnings.length + module.dependenciesWarnings.length) }; - if(showReasons) { + if (showReasons) { obj.reasons = module.reasons.filter(function(reason) { return reason.dependency && reason.module; }).map(function(reason) { @@ -189,20 +198,22 @@ Stats.prototype.toJson = function toJson(options, forToString) { userRequest: reason.dependency.userRequest }; var dep = reason.dependency; - if(dep.templateModules) obj.templateModules = dep.templateModules.map(function(module) { return module.id; }); - if(typeof dep.loc === "object") obj.loc = dep.loc.start.line + ":" + dep.loc.start.column + "-" + + if (dep.templateModules) obj.templateModules = dep.templateModules.map(function(module) { + return module.id; + }); + if (typeof dep.loc === "object") obj.loc = dep.loc.start.line + ":" + dep.loc.start.column + "-" + (dep.loc.start.line !== dep.loc.end.line ? dep.loc.end.line + ":" : "") + dep.loc.end.column; return obj; }).sort(function(a, b) { return a.moduleId - b.moduleId; }); } - if(showSource && module._source) { + if (showSource && module._source) { obj.source = module._source.source(); } return obj; } - if(showChunks) { + if (showChunks) { obj.chunks = compilation.chunks.map(function(chunk) { var obj = { id: chunk.id, @@ -210,7 +221,9 @@ Stats.prototype.toJson = function toJson(options, forToString) { initial: !!chunk.initial, entry: !!chunk.entry, extraAsync: !!chunk.extraAsync, - size: chunk.modules.reduce(function(size, module) { return size + module.size(); }, 0), + size: chunk.modules.reduce(function(size, module) { + return size + module.size(); + }, 0), names: chunk.name ? [chunk.name] : [], files: chunk.files.slice(), hash: chunk.renderedHash, @@ -218,12 +231,12 @@ Stats.prototype.toJson = function toJson(options, forToString) { return c.id; }) }; - if(showChunkModules) { + if (showChunkModules) { obj.modules = chunk.modules.filter(moduleFilter).map(fnModule); obj.filteredModules = chunk.modules.length - obj.modules.length; obj.modules.sort(sortByField(sortModules)); } - if(showChunkOrigins) { + if (showChunkOrigins) { obj.origins = chunk.origins.map(function(origin) { return { moduleId: origin.module ? origin.module.id : undefined, @@ -241,12 +254,12 @@ Stats.prototype.toJson = function toJson(options, forToString) { }); obj.chunks.sort(sortByField(sortChunks)); } - if(showModules) { + if (showModules) { obj.modules = compilation.modules.filter(moduleFilter).map(fnModule); obj.filteredModules = compilation.modules.length - obj.modules.length; obj.modules.sort(sortByField(sortModules)); } - if(showChildren) { + if (showChildren) { obj.children = compilation.children.map(function(child) { var obj = new Stats(child).toJson(options, forToString); delete obj.hash; @@ -259,8 +272,11 @@ Stats.prototype.toJson = function toJson(options, forToString) { }; Stats.prototype.toString = function toString(options) { - if(!options) options = {}; - function d(v, def) { return v === undefined ? def : v; } + if (!options) options = {}; + + function d(v, def) { + return v === undefined ? def : v; + } var useColors = d(options.colors, false); var obj = this.toJson(options, true); @@ -270,91 +286,102 @@ Stats.prototype.toString = function toString(options) { Stats.jsonToString = function jsonToString(obj, useColors) { var buf = []; + function normal(str) { buf.push(str); } + function bold(str) { - if(useColors) buf.push("\u001b[1m"); + if (useColors) buf.push("\u001b[1m"); buf.push(str); - if(useColors) buf.push("\u001b[22m"); + if (useColors) buf.push("\u001b[22m"); } + function yellow(str) { - if(useColors) buf.push("\u001b[1m\u001b[33m"); + if (useColors) buf.push("\u001b[1m\u001b[33m"); buf.push(str); - if(useColors) buf.push("\u001b[39m\u001b[22m"); + if (useColors) buf.push("\u001b[39m\u001b[22m"); } + function red(str) { - if(useColors) buf.push("\u001b[1m\u001b[31m"); + if (useColors) buf.push("\u001b[1m\u001b[31m"); buf.push(str); - if(useColors) buf.push("\u001b[39m\u001b[22m"); + if (useColors) buf.push("\u001b[39m\u001b[22m"); } + function green(str) { - if(useColors) buf.push("\u001b[1m\u001b[32m"); + if (useColors) buf.push("\u001b[1m\u001b[32m"); buf.push(str); - if(useColors) buf.push("\u001b[39m\u001b[22m"); + if (useColors) buf.push("\u001b[39m\u001b[22m"); } + function cyan(str) { - if(useColors) buf.push("\u001b[1m\u001b[36m"); + if (useColors) buf.push("\u001b[1m\u001b[36m"); buf.push(str); - if(useColors) buf.push("\u001b[39m\u001b[22m"); + if (useColors) buf.push("\u001b[39m\u001b[22m"); } + function magenta(str) { - if(useColors) buf.push("\u001b[1m\u001b[35m"); + if (useColors) buf.push("\u001b[1m\u001b[35m"); buf.push(str); - if(useColors) buf.push("\u001b[39m\u001b[22m"); + if (useColors) buf.push("\u001b[39m\u001b[22m"); } + function coloredTime(time) { var times = [800, 400, 200, 100]; - if(obj.time) { + if (obj.time) { times = [obj.time / 2, obj.time / 4, obj.time / 8, obj.time / 16]; } - if(time < times[3]) + if (time < times[3]) normal(time + "ms"); - else if(time < times[2]) + else if (time < times[2]) bold(time + "ms"); - else if(time < times[1]) + else if (time < times[1]) green(time + "ms"); - else if(time < times[0]) + else if (time < times[0]) yellow(time + "ms"); else red(time + "ms"); } + function newline() { buf.push("\n"); } + function table(array, formats, align, splitter) { var rows = array.length; var cols = array[0].length; var colSizes = new Array(cols); - for(var col = 0; col < cols; col++) + for (var col = 0; col < cols; col++) colSizes[col] = 3; - for(var row = 0; row < rows; row++) { - for(var col = 0; col < cols; col++) { + for (var row = 0; row < rows; row++) { + for (var col = 0; col < cols; col++) { var value = array[row][col] + ""; - if(value.length > colSizes[col]) { + if (value.length > colSizes[col]) { colSizes[col] = value.length; } } } - for(var row = 0; row < rows; row++) { - for(var col = 0; col < cols; col++) { + for (var row = 0; row < rows; row++) { + for (var col = 0; col < cols; col++) { var format = row === 0 ? bold : formats[col]; var value = array[row][col] + ""; var l = value.length; - if(align[col] === "l") + if (align[col] === "l") format(value); - for(; l < colSizes[col] && col !== cols - 1; l++) + for (; l < colSizes[col] && col !== cols - 1; l++) normal(" "); - if(align[col] === "r") + if (align[col] === "r") format(value); - if(col + 1 < cols) + if (col + 1 < cols) normal(splitter || " "); } newline(); } } + function formatSize(size) { - if(size <= 0) return "0 bytes"; + if (size <= 0) return "0 bytes"; var abbreviations = ["bytes", "kB", "MB", "GB"]; var index = Math.floor(Math.log(size) / Math.log(1000)); @@ -363,29 +390,31 @@ Stats.jsonToString = function jsonToString(obj, useColors) { .toPrecision(3) + " " + abbreviations[index]; } - if(obj.hash) { + if (obj.hash) { normal("Hash: "); bold(obj.hash); newline(); } - if(obj.version) { + if (obj.version) { normal("Version: webpack "); bold(obj.version); newline(); } - if(typeof obj.time === "number") { + if (typeof obj.time === "number") { normal("Time: "); bold(obj.time); normal("ms"); newline(); } - if(obj.publicPath) { + if (obj.publicPath) { normal("PublicPath: "); bold(obj.publicPath); newline(); } - if(obj.assets && obj.assets.length > 0) { - var t = [["Asset", "Size", "Chunks", "", "Chunk Names"]]; + if (obj.assets && obj.assets.length > 0) { + var t = [ + ["Asset", "Size", "Chunks", "", "Chunk Names"] + ]; obj.assets.forEach(function(asset) { t.push([ asset.name, @@ -398,27 +427,29 @@ Stats.jsonToString = function jsonToString(obj, useColors) { table(t, [green, normal, bold, green, normal], "rrrll"); } var modulesByIdentifier = {}; - if(obj.modules) { + if (obj.modules) { obj.modules.forEach(function(module) { modulesByIdentifier["$" + module.identifier] = module; }); - } else if(obj.chunks) { + } else if (obj.chunks) { obj.chunks.forEach(function(chunk) { - if(chunk.modules) { + if (chunk.modules) { chunk.modules.forEach(function(module) { modulesByIdentifier["$" + module.identifier] = module; }); } }); } + function processProfile(module) { - if(module.profile) { + if (module.profile) { normal(" "); - var sum = 0, allowSum = true; + var sum = 0, + allowSum = true; var path = []; var current = module; - while(current.issuer) { - if(!modulesByIdentifier["$" + current.issuer]) { + while (current.issuer) { + if (!modulesByIdentifier["$" + current.issuer]) { normal(" ... ->"); allowSum = false; break; @@ -429,7 +460,7 @@ Stats.jsonToString = function jsonToString(obj, useColors) { normal(" ["); normal(module.id); normal("] "); - if(module.profile) { + if (module.profile) { var time = (module.profile.factory || 0) + (module.profile.building || 0); coloredTime(time); sum += time; @@ -443,53 +474,54 @@ Stats.jsonToString = function jsonToString(obj, useColors) { coloredTime(time); sum += time; }); - if(allowSum) { + if (allowSum) { normal(" = "); coloredTime(sum); } newline(); } } + function processModuleAttributes(module) { normal(" "); normal(formatSize(module.size)); - if(module.chunks) { + if (module.chunks) { module.chunks.forEach(function(chunk) { normal(" {"); yellow(chunk); normal("}"); }); } - if(!module.cacheable) { + if (!module.cacheable) { red(" [not cacheable]"); } - if(module.optional) { + if (module.optional) { yellow(" [optional]"); } - if(module.built) { + if (module.built) { green(" [built]"); } - if(module.prefetched) { + if (module.prefetched) { magenta(" [prefetched]"); } - if(module.failed) + if (module.failed) red(" [failed]"); - if(module.warnings) + if (module.warnings) yellow(" [" + module.warnings + " warning" + (module.warnings === 1 ? "" : "s") + "]"); - if(module.errors) + if (module.errors) red(" [" + module.errors + " error" + (module.errors === 1 ? "" : "s") + "]"); } - if(obj.chunks) { + if (obj.chunks) { obj.chunks.forEach(function(chunk) { normal("chunk "); - if(chunk.id < 1000) normal(" "); - if(chunk.id < 100) normal(" "); - if(chunk.id < 10) normal(" "); + if (chunk.id < 1000) normal(" "); + if (chunk.id < 100) normal(" "); + if (chunk.id < 10) normal(" "); normal("{"); yellow(chunk.id); normal("} "); green(chunk.files.join(", ")); - if(chunk.names && chunk.names.length > 0) { + if (chunk.names && chunk.names.length > 0) { normal(" ("); normal(chunk.names.join(", ")); normal(")"); @@ -501,61 +533,61 @@ Stats.jsonToString = function jsonToString(obj, useColors) { yellow(id); normal("}"); }); - if(chunk.rendered) { + if (chunk.rendered) { green(" [rendered]"); } newline(); - if(chunk.origins) { + if (chunk.origins) { chunk.origins.forEach(function(origin) { normal(" > "); - if(origin.reasons && origin.reasons.length) { + if (origin.reasons && origin.reasons.length) { yellow(origin.reasons.join(" ")); normal(" "); } - if(origin.name) { + if (origin.name) { normal(origin.name); normal(" "); } - if(origin.module) { + if (origin.module) { normal("["); normal(origin.moduleId); normal("] "); var module = modulesByIdentifier["$" + origin.module]; - if(module) { + if (module) { bold(module.name); normal(" "); } - if(origin.loc) { + if (origin.loc) { normal(origin.loc); } } newline(); }); } - if(chunk.modules) { + if (chunk.modules) { chunk.modules.forEach(function(module) { normal(" "); - if(module.id < 1000) normal(" "); - if(module.id < 100) normal(" "); - if(module.id < 10) normal(" "); + if (module.id < 1000) normal(" "); + if (module.id < 100) normal(" "); + if (module.id < 10) normal(" "); normal("["); normal(module.id); normal("] "); bold(module.name); processModuleAttributes(module); newline(); - if(module.reasons) { + if (module.reasons) { module.reasons.forEach(function(reason) { normal(" "); normal(reason.type); normal(" "); cyan(reason.userRequest); - if(reason.templateModules) cyan(reason.templateModules.join(" ")); + if (reason.templateModules) cyan(reason.templateModules.join(" ")); normal(" ["); normal(reason.moduleId); normal("] "); magenta(reason.module); - if(reason.loc) { + if (reason.loc) { normal(" "); normal(reason.loc); } @@ -564,36 +596,36 @@ Stats.jsonToString = function jsonToString(obj, useColors) { } processProfile(module); }); - if(chunk.filteredModules > 0) { + if (chunk.filteredModules > 0) { normal(" + " + chunk.filteredModules + " hidden modules"); newline(); } } }); } - if(obj.modules) { + if (obj.modules) { obj.modules.forEach(function(module) { - if(module.id < 1000) normal(" "); - if(module.id < 100) normal(" "); - if(module.id < 10) normal(" "); + if (module.id < 1000) normal(" "); + if (module.id < 100) normal(" "); + if (module.id < 10) normal(" "); normal("["); normal(module.id); normal("] "); bold(module.name || module.identifier); processModuleAttributes(module); newline(); - if(module.reasons) { + if (module.reasons) { module.reasons.forEach(function(reason) { normal(" "); normal(reason.type); normal(" "); cyan(reason.userRequest); - if(reason.templateModules) cyan(reason.templateModules.join(" ")); + if (reason.templateModules) cyan(reason.templateModules.join(" ")); normal(" ["); normal(reason.moduleId); normal("] "); magenta(reason.module); - if(reason.loc) { + if (reason.loc) { normal(" "); normal(reason.loc); } @@ -602,28 +634,28 @@ Stats.jsonToString = function jsonToString(obj, useColors) { } processProfile(module); }); - if(obj.filteredModules > 0) { + if (obj.filteredModules > 0) { normal(" + " + obj.filteredModules + " hidden modules"); newline(); } } - if(obj.warnings) { + if (obj.warnings) { obj.warnings.forEach(function(warning) { newline(); yellow("WARNING in " + warning); newline(); }); } - if(obj.errors) { + if (obj.errors) { obj.errors.forEach(function(error) { newline(); red("ERROR in " + error); newline(); }); } - if(obj.children) { + if (obj.children) { obj.children.forEach(function(child) { - if(child.name) { + if (child.name) { normal("Child "); bold(child.name); normal(":"); @@ -637,6 +669,6 @@ Stats.jsonToString = function jsonToString(obj, useColors) { }); } - while(buf[buf.length - 1] === "\n") buf.pop(); + while (buf[buf.length - 1] === "\n") buf.pop(); return buf.join(""); }; diff --git a/lib/Template.js b/lib/Template.js index da7e82a09..2c541a372 100644 --- a/lib/Template.js +++ b/lib/Template.js @@ -16,94 +16,96 @@ Template.getFunctionContent = function(fn) { }; Template.toIdentifier = function(str) { - if(typeof str !== "string") return ""; + if (typeof str !== "string") return ""; return str.replace(/^[^a-zA-Z$_]/, "_").replace(/[^a-zA-Z0-9$_]/g, "_"); }; Template.prototype = Object.create(Tapable.prototype); Template.prototype.indent = function indent(str) { - if(Array.isArray(str)) { + if (Array.isArray(str)) { return str.map(indent).join("\n"); } else { str = str.trimRight(); - if(!str) return ""; + if (!str) return ""; return (str[0] === "\n" ? "" : "\t") + str.replace(/\n([^\n])/g, "\n\t$1"); } }; Template.prototype.prefix = function(str, prefix) { - if(Array.isArray(str)) { + if (Array.isArray(str)) { str = str.join("\n"); } str = str.trim(); - if(!str) return ""; + if (!str) return ""; return (str[0] === "\n" ? "" : prefix) + str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); }; Template.prototype.asString = function(str) { - if(Array.isArray(str)) { + if (Array.isArray(str)) { return str.join("\n"); } return str; }; Template.prototype.getModulesArrayBounds = function(modules) { - if(modules.some(function(module) { - return typeof module.id !== "number"; - })) + if (modules.some(function(module) { + return typeof module.id !== "number"; + })) return false; var maxId = -Infinity; var minId = Infinity; modules.forEach(function(module) { - if(maxId < module.id) maxId = module.id; - if(minId > module.id) minId = module.id; + if (maxId < module.id) maxId = module.id; + if (minId > module.id) minId = module.id; }); - if(minId < 16 + ("" + minId).length) { + if (minId < 16 + ("" + minId).length) { // add minId x ',' instead of 'Array(minId).concat(...)' minId = 0; } var objectOverhead = modules.map(function(module) { return (module.id + "").length + 2; - }).reduce(function(a, b) { return a + b; }, -1); + }).reduce(function(a, b) { + return a + b; + }, -1); var arrayOverhead = minId === 0 ? maxId : 16 + ("" + minId).length + maxId; return arrayOverhead < objectOverhead ? [minId, maxId] : false; }; Template.prototype.renderChunkModules = function(chunk, moduleTemplate, dependencyTemplates, prefix) { - if(!prefix) prefix = ""; + if (!prefix) prefix = ""; var source = new ConcatSource(); - if(chunk.modules.length === 0) { + if (chunk.modules.length === 0) { source.add("[]"); return source; } var bounds = this.getModulesArrayBounds(chunk.modules); - if(bounds) { + if (bounds) { // Render a spare array var minId = bounds[0]; var maxId = bounds[1]; - if(minId !== 0) source.add("Array(" + minId + ").concat("); + if (minId !== 0) source.add("Array(" + minId + ").concat("); source.add("[\n"); var modules = {}; chunk.modules.forEach(function(module) { modules[module.id] = module; }); - for(var idx = minId; idx <= maxId; idx++) { + for (var idx = minId; idx <= maxId; idx++) { var module = modules[idx]; - if(idx !== minId) source.add(",\n"); + if (idx !== minId) source.add(",\n"); source.add("/* " + idx + " */"); - if(module) { + if (module) { source.add("\n"); source.add(moduleTemplate.render(module, dependencyTemplates, chunk)); } } source.add("\n" + prefix + "]"); - if(minId !== 0) source.add(")"); + if (minId !== 0) source.add(")"); } else { // Render an object source.add("{\n"); chunk.modules.forEach(function(module, idx) { - if(idx !== 0) source.add(",\n"); + if (idx !== 0) source.add(",\n"); source.add("\n/***/ " + JSON.stringify(module.id) + ":\n"); source.add(moduleTemplate.render(module, dependencyTemplates, chunk)); }); diff --git a/lib/TemplatedPathPlugin.js b/lib/TemplatedPathPlugin.js index 5c27752a5..84f92fe72 100644 --- a/lib/TemplatedPathPlugin.js +++ b/lib/TemplatedPathPlugin.js @@ -34,7 +34,7 @@ module.exports = TemplatedPathPlugin; function withHashLength(replacer, handlerFn) { return function(_, hashLength) { var length = hashLength && parseInt(hashLength, 10); - if(length && handlerFn) { + if (length && handlerFn) { return handlerFn(length); } var hash = replacer.apply(this, arguments); @@ -46,8 +46,8 @@ function getReplacer(value, allowEmpty) { return function(match) { // last argument in replacer is the entire input string var input = arguments[arguments.length - 1]; - if(value == null) { - if(!allowEmpty) throw new Error("Path variable " + match + " not implemented in this context: " + input); + if (value == null) { + if (!allowEmpty) throw new Error("Path variable " + match + " not implemented in this context: " + input); return ""; } else { return "" + value; @@ -62,7 +62,7 @@ function replacePathVariables(path, data) { var chunkHash = chunk && (chunk.renderedHash || chunk.hash); var chunkHashWithLength = chunk && chunk.hashWithLength; - if(data.noChunkHash && REGEXP_CHUNKHASH_FOR_TEST.test(path)) { + if (data.noChunkHash && REGEXP_CHUNKHASH_FOR_TEST.test(path)) { throw new Error("Cannot use [chunkhash] for chunk in '" + path + "' (use [hash] instead)"); } @@ -89,24 +89,23 @@ TemplatedPathPlugin.prototype.apply = function(compiler) { var publicPath = outputOptions.publicPath || ""; var filename = outputOptions.filename || ""; var chunkFilename = outputOptions.chunkFilename || ""; - if(REGEXP_HASH_FOR_TEST.test(publicPath) || REGEXP_CHUNKHASH_FOR_TEST.test(publicPath) || REGEXP_NAME_FOR_TEST.test(publicPath)) + if (REGEXP_HASH_FOR_TEST.test(publicPath) || REGEXP_CHUNKHASH_FOR_TEST.test(publicPath) || REGEXP_NAME_FOR_TEST.test(publicPath)) return true; - if(REGEXP_HASH_FOR_TEST.test(filename)) + if (REGEXP_HASH_FOR_TEST.test(filename)) return true; - if(REGEXP_HASH_FOR_TEST.test(chunkFilename)) + if (REGEXP_HASH_FOR_TEST.test(chunkFilename)) return true; - if(REGEXP_HASH_FOR_TEST.test(paths.join("|"))) + if (REGEXP_HASH_FOR_TEST.test(paths.join("|"))) return true; }); mainTemplate.plugin("hash-for-chunk", function(hash, chunk) { var outputOptions = this.outputOptions; var chunkFilename = outputOptions.chunkFilename || ""; - if(REGEXP_CHUNKHASH_FOR_TEST.test(chunkFilename)) + if (REGEXP_CHUNKHASH_FOR_TEST.test(chunkFilename)) hash.update(JSON.stringify(chunk.getChunkMaps(true).hash)); - if(REGEXP_NAME_FOR_TEST.test(chunkFilename)) + if (REGEXP_NAME_FOR_TEST.test(chunkFilename)) hash.update(JSON.stringify(chunk.getChunkMaps(true).name)); }); }); }; - diff --git a/lib/UmdMainTemplatePlugin.js b/lib/UmdMainTemplatePlugin.js index 949aa098f..93f4294fe 100644 --- a/lib/UmdMainTemplatePlugin.js +++ b/lib/UmdMainTemplatePlugin.js @@ -15,7 +15,7 @@ function accessorAccess(base, accessor) { accessor = [].concat(accessor); return accessor.map(function(a, idx) { a = base + accessorToObjectAccess(accessor.slice(0, idx + 1)); - if(idx === accessor.length - 1) return a; + if (idx === accessor.length - 1) return a; return a + " = " + a + " || {}"; }).join(", "); } @@ -31,10 +31,11 @@ UmdMainTemplatePlugin.prototype.apply = function(compilation) { var externals = chunk.modules.filter(function(m) { return m.external; }); - var optionalExternals = [], requiredExternals = []; - if(this.optionalAmdExternalAsGlobal) { + var optionalExternals = [], + requiredExternals = []; + if (this.optionalAmdExternalAsGlobal) { externals.forEach(function(m) { - if(m.optional) { + if (m.optional) { optionalExternals.push(m); } else { requiredExternals.push(m); @@ -51,45 +52,49 @@ UmdMainTemplatePlugin.prototype.apply = function(compilation) { chunk: chunk }); } + function externalsDepsArray(modules) { return "[" + replaceKeys(modules.map(function(m) { return JSON.stringify(typeof m.request === "object" ? m.request.amd : m.request); }).join(", ")) + "]"; } + function externalsRootArray(modules) { return replaceKeys(modules.map(function(m) { var request = m.request; - if(typeof request === "object") request = request.root; + if (typeof request === "object") request = request.root; return "root" + accessorToObjectAccess([].concat(request)); }).join(", ")); } + function externalsRequireArray(type) { return replaceKeys(externals.map(function(m) { var request = m.request; - if(typeof request === "object") request = request[type]; - if(Array.isArray(request)) { + if (typeof request === "object") request = request[type]; + if (Array.isArray(request)) { var expr = "require(" + JSON.stringify(request[0]) + ")" + accessorToObjectAccess(request.slice(1)); } else var expr = "require(" + JSON.stringify(request) + ")"; - if(m.optional) { + if (m.optional) { expr = "(function webpackLoadOptionalExternalModule() { try { return " + expr + "; } catch(e) {} }())"; } return expr; }).join(", ")); } + function externalsArguments(modules) { return modules.map(function(m) { return "__WEBPACK_EXTERNAL_MODULE_" + m.id + "__"; }).join(", "); } - if(optionalExternals.length > 0) { + if (optionalExternals.length > 0) { var amdFactory = "function webpackLoadOptionalExternalModuleAmd(" + externalsArguments(requiredExternals) + ") {\n" + - " return factory(" + ( - requiredExternals.length > 0 ? + " return factory(" + ( + requiredExternals.length > 0 ? externalsArguments(requiredExternals) + ", " + externalsRootArray(optionalExternals) : externalsRootArray(optionalExternals) - ) + ");\n" + - " }"; + ) + ");\n" + + " }"; } else { var amdFactory = "factory"; } @@ -99,24 +104,21 @@ UmdMainTemplatePlugin.prototype.apply = function(compilation) { " module.exports = factory(" + externalsRequireArray("commonjs2") + ");\n" + " else if(typeof define === 'function' && define.amd)\n" + (requiredExternals.length > 0 ? - " define(" + externalsDepsArray(requiredExternals) + ", " + amdFactory + ");\n" - : - " define(" + amdFactory + ");\n" + " define(" + externalsDepsArray(requiredExternals) + ", " + amdFactory + ");\n" : + " define(" + amdFactory + ");\n" ) + (this.name ? - " else if(typeof exports === 'object')\n" + - " exports[" + JSON.stringify(replaceKeys([].concat(this.name).pop())) + "] = factory(" + externalsRequireArray("commonjs") + ");\n" + - " else\n" + - " " + replaceKeys(accessorAccess("root", this.name)) + " = factory(" + externalsRootArray(externals) + ");\n" - : - " else {\n" + - (externals.length > 0 ? - " var a = typeof exports === 'object' ? factory(" + externalsRequireArray("commonjs") + ") : factory(" + externalsRootArray(externals) + ");\n" - : - " var a = factory();\n" - ) + - " for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" + - " }\n" + " else if(typeof exports === 'object')\n" + + " exports[" + JSON.stringify(replaceKeys([].concat(this.name).pop())) + "] = factory(" + externalsRequireArray("commonjs") + ");\n" + + " else\n" + + " " + replaceKeys(accessorAccess("root", this.name)) + " = factory(" + externalsRootArray(externals) + ");\n" : + " else {\n" + + (externals.length > 0 ? + " var a = typeof exports === 'object' ? factory(" + externalsRequireArray("commonjs") + ") : factory(" + externalsRootArray(externals) + ");\n" : + " var a = factory();\n" + ) + + " for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" + + " }\n" ) + "})(this, function(" + externalsArguments(externals) + ") {\nreturn ", "webpack/universalModuleDefinition"), source, "\n});\n"); }.bind(this)); diff --git a/lib/WarnCaseSensitiveModulesPlugin.js b/lib/WarnCaseSensitiveModulesPlugin.js index 97c450c12..8b38d5d19 100644 --- a/lib/WarnCaseSensitiveModulesPlugin.js +++ b/lib/WarnCaseSensitiveModulesPlugin.js @@ -13,8 +13,8 @@ WarnCaseSensitiveModulesPlugin.prototype.apply = function(compiler) { var moduleWithoutCase = {}; this.modules.forEach(function(module) { var ident = module.identifier().toLowerCase(); - if(moduleWithoutCase["$" + ident]) { - if(moduleWithoutCase["$" + ident] !== true) + if (moduleWithoutCase["$" + ident]) { + if (moduleWithoutCase["$" + ident] !== true) this.warnings.push(new CaseSensitiveModulesWarning(moduleWithoutCase["$" + ident])); this.warnings.push(new CaseSensitiveModulesWarning(module)); moduleWithoutCase["$" + ident] = true; @@ -25,4 +25,3 @@ WarnCaseSensitiveModulesPlugin.prototype.apply = function(compiler) { }); }); }; - diff --git a/lib/WatchIgnorePlugin.js b/lib/WatchIgnorePlugin.js index 647ee833a..30948e570 100644 --- a/lib/WatchIgnorePlugin.js +++ b/lib/WatchIgnorePlugin.js @@ -29,7 +29,7 @@ IgnoringWatchFileSystem.prototype.watch = function(files, dirs, missing, startTi var ignoredDirs = dirs.filter(ignored); this.wfs.watch(files.filter(notIgnored), dirs.filter(notIgnored), missing, startTime, delay, function(err, filesModified, dirsModified, fileTimestamps, dirTimestamps) { - if(err) return callback(err); + if (err) return callback(err); ignoredFiles.forEach(function(path) { fileTimestamps[path] = 1; @@ -42,4 +42,3 @@ IgnoringWatchFileSystem.prototype.watch = function(files, dirs, missing, startTi callback(err, filesModified, dirsModified, fileTimestamps, dirTimestamps); }, callbackUndelayed); }; - diff --git a/lib/WebpackOptionsApply.js b/lib/WebpackOptionsApply.js index 20a958b5a..7f1bb6122 100644 --- a/lib/WebpackOptionsApply.js +++ b/lib/WebpackOptionsApply.js @@ -59,114 +59,114 @@ module.exports = WebpackOptionsApply; WebpackOptionsApply.prototype = Object.create(OptionsApply.prototype); WebpackOptionsApply.prototype.process = function(options, compiler) { compiler.context = options.context; - if(options.plugins && Array.isArray(options.plugins)) { + if (options.plugins && Array.isArray(options.plugins)) { compiler.apply.apply(compiler, options.plugins); } compiler.outputPath = options.output.path; compiler.recordsInputPath = options.recordsInputPath || options.recordsPath; compiler.recordsOutputPath = options.recordsOutputPath || options.recordsPath; compiler.name = options.name; - if(typeof options.target === "string") { - switch(options.target) { - case "web": - var JsonpTemplatePlugin = require("./JsonpTemplatePlugin"); - var NodeSourcePlugin = require("./node/NodeSourcePlugin"); - compiler.apply( - new JsonpTemplatePlugin(options.output), - new FunctionModulePlugin(options.output), - new NodeSourcePlugin(options.node), - new LoaderTargetPlugin("web") - ); - break; - case "webworker": - var WebWorkerTemplatePlugin = require("./webworker/WebWorkerTemplatePlugin"); - var NodeSourcePlugin = require("./node/NodeSourcePlugin"); - compiler.apply( - new WebWorkerTemplatePlugin(options.output), - new FunctionModulePlugin(options.output), - new NodeSourcePlugin(options.node), - new LoaderTargetPlugin("webworker") - ); - break; - case "node": - case "async-node": - var NodeTemplatePlugin = require("./node/NodeTemplatePlugin"); - var NodeTargetPlugin = require("./node/NodeTargetPlugin"); - compiler.apply( - new NodeTemplatePlugin(options.output, options.target === "async-node"), - new FunctionModulePlugin(options.output), - new NodeTargetPlugin(), - new LoaderTargetPlugin("node") - ); - break; - case "node-webkit": - var JsonpTemplatePlugin = require("./JsonpTemplatePlugin"); - var NodeTargetPlugin = require("./node/NodeTargetPlugin"); - var ExternalsPlugin = require("./ExternalsPlugin"); - compiler.apply( - new JsonpTemplatePlugin(options.output), - new FunctionModulePlugin(options.output), - new NodeTargetPlugin(), - new ExternalsPlugin("commonjs", "nw.gui"), - new LoaderTargetPlugin("node-webkit") - ); - break; - case "atom": - case "electron": - var NodeTemplatePlugin = require("./node/NodeTemplatePlugin"); - var NodeTargetPlugin = require("./node/NodeTargetPlugin"); - var ExternalsPlugin = require("./ExternalsPlugin"); - compiler.apply( - new NodeTemplatePlugin(options.output, true), - new FunctionModulePlugin(options.output), - new NodeTargetPlugin(), - new ExternalsPlugin("commonjs", [ - "app", - "auto-updater", - "browser-window", - "content-tracing", - "dialog", - "global-shortcut", - "ipc", - "menu", - "menu-item", - "power-monitor", - "protocol", - "tray", - "remote", - "web-view", - "clipboard", - "crash-reporter", - "screen", - "shell" - ]), - new LoaderTargetPlugin(options.target) - ); - break; - default: - throw new Error("Unsupported target '" + options.target + "'."); + if (typeof options.target === "string") { + switch (options.target) { + case "web": + var JsonpTemplatePlugin = require("./JsonpTemplatePlugin"); + var NodeSourcePlugin = require("./node/NodeSourcePlugin"); + compiler.apply( + new JsonpTemplatePlugin(options.output), + new FunctionModulePlugin(options.output), + new NodeSourcePlugin(options.node), + new LoaderTargetPlugin("web") + ); + break; + case "webworker": + var WebWorkerTemplatePlugin = require("./webworker/WebWorkerTemplatePlugin"); + var NodeSourcePlugin = require("./node/NodeSourcePlugin"); + compiler.apply( + new WebWorkerTemplatePlugin(options.output), + new FunctionModulePlugin(options.output), + new NodeSourcePlugin(options.node), + new LoaderTargetPlugin("webworker") + ); + break; + case "node": + case "async-node": + var NodeTemplatePlugin = require("./node/NodeTemplatePlugin"); + var NodeTargetPlugin = require("./node/NodeTargetPlugin"); + compiler.apply( + new NodeTemplatePlugin(options.output, options.target === "async-node"), + new FunctionModulePlugin(options.output), + new NodeTargetPlugin(), + new LoaderTargetPlugin("node") + ); + break; + case "node-webkit": + var JsonpTemplatePlugin = require("./JsonpTemplatePlugin"); + var NodeTargetPlugin = require("./node/NodeTargetPlugin"); + var ExternalsPlugin = require("./ExternalsPlugin"); + compiler.apply( + new JsonpTemplatePlugin(options.output), + new FunctionModulePlugin(options.output), + new NodeTargetPlugin(), + new ExternalsPlugin("commonjs", "nw.gui"), + new LoaderTargetPlugin("node-webkit") + ); + break; + case "atom": + case "electron": + var NodeTemplatePlugin = require("./node/NodeTemplatePlugin"); + var NodeTargetPlugin = require("./node/NodeTargetPlugin"); + var ExternalsPlugin = require("./ExternalsPlugin"); + compiler.apply( + new NodeTemplatePlugin(options.output, true), + new FunctionModulePlugin(options.output), + new NodeTargetPlugin(), + new ExternalsPlugin("commonjs", [ + "app", + "auto-updater", + "browser-window", + "content-tracing", + "dialog", + "global-shortcut", + "ipc", + "menu", + "menu-item", + "power-monitor", + "protocol", + "tray", + "remote", + "web-view", + "clipboard", + "crash-reporter", + "screen", + "shell" + ]), + new LoaderTargetPlugin(options.target) + ); + break; + default: + throw new Error("Unsupported target '" + options.target + "'."); } - } else if(options.target !== false) { + } else if (options.target !== false) { options.target(compiler); } else { throw new Error("Unsupported target '" + options.target + "'."); } - if(options.output.library || options.output.libraryTarget !== "var") { + if (options.output.library || options.output.libraryTarget !== "var") { var LibraryTemplatePlugin = require("./LibraryTemplatePlugin"); compiler.apply(new LibraryTemplatePlugin(options.output.library, options.output.libraryTarget)); } - if(options.externals) { + if (options.externals) { var ExternalsPlugin = require("./ExternalsPlugin"); compiler.apply(new ExternalsPlugin(options.output.libraryTarget, options.externals)); } - if(options.hot) { + if (options.hot) { compiler.apply(new MovedToPluginWarningPlugin("hot", "HotModuleReplacementPlugin")); var HotModuleReplacementPlugin = require("./HotModuleReplacementPlugin"); compiler.apply(new HotModuleReplacementPlugin(options.output)); } - if(options.devtool && (options.devtool.indexOf("sourcemap") >= 0 || options.devtool.indexOf("source-map") >= 0)) { + if (options.devtool && (options.devtool.indexOf("sourcemap") >= 0 || options.devtool.indexOf("source-map") >= 0)) { var hidden = options.devtool.indexOf("hidden") >= 0; var inline = options.devtool.indexOf("inline") >= 0; var evalWrapped = options.devtool.indexOf("eval") >= 0; @@ -178,7 +178,8 @@ WebpackOptionsApply.prototype.process = function(options, compiler) { legacy ? "\n/*\n//@ sourceMappingURL=[url]\n*/" : modern ? "\n//# sourceMappingURL=[url]" : null; - compiler.apply(new (evalWrapped ? EvalSourceMapDevToolPlugin : SourceMapDevToolPlugin)({ + var Plugin = evalWrapped ? EvalSourceMapDevToolPlugin : SourceMapDevToolPlugin; + compiler.apply(new Plugin({ filename: inline ? null : options.output.sourceMapFilename, moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, fallbackModuleFilenameTemplate: options.output.devtoolFallbackModuleFilenameTemplate, @@ -187,7 +188,7 @@ WebpackOptionsApply.prototype.process = function(options, compiler) { columns: cheap ? false : true, lineToLine: options.output.devtoolLineToLine })); - } else if(options.devtool && options.devtool.indexOf("eval") >= 0) { + } else if (options.devtool && options.devtool.indexOf("eval") >= 0) { var legacy = options.devtool.indexOf("@") >= 0; var modern = options.devtool.indexOf("#") >= 0; var comment = legacy && modern ? "//@ sourceURL=[url]\n//# sourceURL=[url]" : @@ -200,7 +201,7 @@ WebpackOptionsApply.prototype.process = function(options, compiler) { compiler.apply(new EntryOptionPlugin()); compiler.applyPluginsBailResult("entry-option", options.context, options.entry); - if(options.prefetch) { + if (options.prefetch) { compiler.apply(new MovedToPluginWarningPlugin("prefetch", "PrefetchPlugin")); var PrefetchPlugin = require("./PrefetchPlugin"); options.prefetch.map(function(request) { @@ -234,56 +235,58 @@ WebpackOptionsApply.prototype.process = function(options, compiler) { compiler.apply(new WarnCaseSensitiveModulesPlugin()); - if(options.optimize && options.optimize.occurenceOrder) { + if (options.optimize && options.optimize.occurenceOrder) { compiler.apply(new MovedToPluginWarningPlugin("optimize.occurenceOrder", "optimize.OccurrenceOrderPlugin")); var OccurrenceOrderPlugin = require("./optimize/OccurrenceOrderPlugin"); compiler.apply(new OccurrenceOrderPlugin(options.optimize.occurenceOrderPreferEntry)); } - if(options.optimize && options.optimize.minChunkSize) { + if (options.optimize && options.optimize.minChunkSize) { compiler.apply(new MovedToPluginWarningPlugin("optimize.minChunkSize", "optimize.MinChunkSizePlugin")); var MinChunkSizePlugin = require("./optimize/MinChunkSizePlugin"); compiler.apply(new MinChunkSizePlugin(options.optimize)); } - if(options.optimize && options.optimize.maxChunks) { + if (options.optimize && options.optimize.maxChunks) { compiler.apply(new MovedToPluginWarningPlugin("optimize.maxChunks", "optimize.LimitChunkCountPlugin")); var LimitChunkCountPlugin = require("./optimize/LimitChunkCountPlugin"); compiler.apply(new LimitChunkCountPlugin(options.optimize)); } - if(options.optimize.minimize) { + if (options.optimize.minimize) { compiler.apply(new MovedToPluginWarningPlugin("optimize.minimize", "optimize.UglifyJsPlugin")); var UglifyJsPlugin = require("./optimize/UglifyJsPlugin"); - if(options.optimize.minimize === true) + if (options.optimize.minimize === true) compiler.apply(new UglifyJsPlugin()); else compiler.apply(new UglifyJsPlugin(options.optimize.minimize)); } - if(options.cache === undefined ? options.watch : options.cache) { + if (options.cache === undefined ? options.watch : options.cache) { var CachePlugin = require("./CachePlugin"); compiler.apply(new CachePlugin(typeof options.cache === "object" ? options.cache : null)); } - if(typeof options.provide === "object") { + if (typeof options.provide === "object") { compiler.apply(new MovedToPluginWarningPlugin("provide", "ProvidePlugin")); var ProvidePlugin = require("./ProvidePlugin"); compiler.apply(new ProvidePlugin(options.provide)); } - if(options.define) { + if (options.define) { compiler.apply(new MovedToPluginWarningPlugin("define", "DefinePlugin")); var defineObject = {}; - if(typeof options.define === "object") { + if (typeof options.define === "object") { Object.keys(options.define).forEach(function(key) { defineObject[key] = options.define[key]; }); } compiler.apply(new DefinePlugin(defineObject)); } - if(options.defineDebug !== false) - compiler.apply(new DefinePlugin({ DEBUG: !!options.debug })); + if (options.defineDebug !== false) + compiler.apply(new DefinePlugin({ + DEBUG: !!options.debug + })); compiler.applyPlugins("after-plugins", compiler); compiler.resolvers.normal.apply( @@ -330,9 +333,9 @@ WebpackOptionsApply.prototype.process = function(options, compiler) { }; function makeRootPlugin(name, root) { - if(typeof root === "string") + if (typeof root === "string") return new ModulesInRootPlugin(name, root); - else if(Array.isArray(root)) { + else if (Array.isArray(root)) { return function() { root.forEach(function(root) { this.apply(new ModulesInRootPlugin(name, root)); diff --git a/lib/WebpackOptionsDefaulter.js b/lib/WebpackOptionsDefaulter.js index 0039c7e6c..47d64b46e 100644 --- a/lib/WebpackOptionsDefaulter.js +++ b/lib/WebpackOptionsDefaulter.js @@ -67,42 +67,33 @@ WebpackOptionsDefaulter.prototype.constructor = WebpackOptionsDefaulter; WebpackOptionsDefaulter.prototype.process = function(options) { OptionsDefaulter.prototype.process.call(this, options); - if(options.resolve.packageAlias === undefined) { - if(options.target === "web" || options.target === "webworker") + if (options.resolve.packageAlias === undefined) { + if (options.target === "web" || options.target === "webworker") options.resolve.packageAlias = "browser"; } function defaultByTarget(value, web, webworker, node, nodeWebkit, def) { - if(value !== undefined) return value; - switch(options.target) { - case "web": return web; - case "webworker": return webworker; - case "node": case "async-node": return node; - case "node-webkit": return nodeWebkit; - default: return def; + if (value !== undefined) return value; + switch (options.target) { + case "web": + return web; + case "webworker": + return webworker; + case "node": + case "async-node": + return node; + case "node-webkit": + return nodeWebkit; + default: + return def; } } - options.resolve.modulesDirectories = defaultByTarget(options.resolve.modulesDirectories, - ["web_modules", "node_modules"], - ["webworker_modules", "web_modules", "node_modules"], - ["node_modules"], - ["node_modules", "web_modules"], - ["node_modules"]); + options.resolve.modulesDirectories = defaultByTarget(options.resolve.modulesDirectories, ["web_modules", "node_modules"], ["webworker_modules", "web_modules", "node_modules"], ["node_modules"], ["node_modules", "web_modules"], ["node_modules"]); - options.resolveLoader.modulesDirectories = defaultByTarget(options.resolveLoader.modulesDirectories, - ["web_loaders", "web_modules", "node_loaders", "node_modules"], - ["webworker_loaders", "web_loaders", "web_modules", "node_loaders", "node_modules"], - ["node_loaders", "node_modules"], - ["node_loaders", "web_loaders", "node_modules", "web_modules"], - ["node_modules"]); + options.resolveLoader.modulesDirectories = defaultByTarget(options.resolveLoader.modulesDirectories, ["web_loaders", "web_modules", "node_loaders", "node_modules"], ["webworker_loaders", "web_loaders", "web_modules", "node_loaders", "node_modules"], ["node_loaders", "node_modules"], ["node_loaders", "web_loaders", "node_modules", "web_modules"], ["node_modules"]); - options.resolve.packageMains = defaultByTarget(options.resolve.packageMains, - ["webpack", "browser", "web", "browserify", ["jam", "main"], "main"], - ["webpackWorker", "webworker", "webpack", "browser", "web", "browserify", ["jam", "main"], "main"], - ["webpackNode", "node", "main"], - ["webpackNodeWebkit", "webpackNode", "node", "main", "web"], - ["main"]); + options.resolve.packageMains = defaultByTarget(options.resolve.packageMains, ["webpack", "browser", "web", "browserify", ["jam", "main"], "main"], ["webpackWorker", "webworker", "webpack", "browser", "web", "browserify", ["jam", "main"], "main"], ["webpackNode", "node", "main"], ["webpackNodeWebkit", "webpackNode", "node", "main", "web"], ["main"]); options.resolve.packageAlias = defaultByTarget(options.resolve.packageAlias, "browser", @@ -111,31 +102,11 @@ WebpackOptionsDefaulter.prototype.process = function(options) { "node-webkit", false); - options.resolveLoader.packageMains = defaultByTarget(options.resolveLoader.packageMains, - ["webpackLoader", "webLoader", "loader", "main"], - ["webpackWorkerLoader", "webworkerLoader", "webLoader", "loader", "main"], - ["webpackNodeLoader", "nodeLoader", "loader", "main"], - ["webpackNodeWebkitLoader", "webpackNodeLoader", "nodeLoader", "loader", "webLoader", "main"], - ["loader", "main"]); + options.resolveLoader.packageMains = defaultByTarget(options.resolveLoader.packageMains, ["webpackLoader", "webLoader", "loader", "main"], ["webpackWorkerLoader", "webworkerLoader", "webLoader", "loader", "main"], ["webpackNodeLoader", "nodeLoader", "loader", "main"], ["webpackNodeWebkitLoader", "webpackNodeLoader", "nodeLoader", "loader", "webLoader", "main"], ["loader", "main"]); - options.resolve.extensions = defaultByTarget(options.resolve.extensions, - ["", ".webpack.js", ".web.js", ".js", ".json"], - ["", ".webpack-worker.js", ".webworker.js", ".web.js", ".js", ".json"], - ["", ".webpack-node.js", ".js", ".json", ".node"], - ["", ".webpack-node-webkit.js", ".webpack-node.js", ".js", ".json", ".node", ".web.js"], - ["", ".js", ".json"]); + options.resolve.extensions = defaultByTarget(options.resolve.extensions, ["", ".webpack.js", ".web.js", ".js", ".json"], ["", ".webpack-worker.js", ".webworker.js", ".web.js", ".js", ".json"], ["", ".webpack-node.js", ".js", ".json", ".node"], ["", ".webpack-node-webkit.js", ".webpack-node.js", ".js", ".json", ".node", ".web.js"], ["", ".js", ".json"]); - options.resolveLoader.extensions = defaultByTarget(options.resolveLoader.extensions, - ["", ".webpack-loader.js", ".web-loader.js", ".loader.js", ".js"], - ["", ".webpack-worker-loader.js", ".webpack-loader.js", ".webworker-loader.js", ".web-loader.js", ".loader.js", ".js"], - ["", ".webpack-node-loader.js", ".loader.js", ".js"], - ["", ".webpack-node-webkit-loader.js", ".webpack-node-loader.js", ".loader.js", ".web-loader.js", ".js"], - ["", ".js"]); + options.resolveLoader.extensions = defaultByTarget(options.resolveLoader.extensions, ["", ".webpack-loader.js", ".web-loader.js", ".loader.js", ".js"], ["", ".webpack-worker-loader.js", ".webpack-loader.js", ".webworker-loader.js", ".web-loader.js", ".loader.js", ".js"], ["", ".webpack-node-loader.js", ".loader.js", ".js"], ["", ".webpack-node-webkit-loader.js", ".webpack-node-loader.js", ".loader.js", ".web-loader.js", ".js"], ["", ".js"]); - options.resolveLoader.moduleTemplates = defaultByTarget(options.resolveLoader.moduleTemplates, - ["*-webpack-loader", "*-web-loader", "*-loader", "*"], - ["*-webpack-worker-loader", "*-webworker-loader", "*-web-loader", "*-loader", "*"], - ["*-webpack-node-loader", "*-node-loader", "*-loader", "*"], - ["*-webpack-node-webkit-loader", "*-webpack-node-loader", "*-node-loader", "*-loader", "*-web-loader", "*"], - ["*-loader", "*"]); + options.resolveLoader.moduleTemplates = defaultByTarget(options.resolveLoader.moduleTemplates, ["*-webpack-loader", "*-web-loader", "*-loader", "*"], ["*-webpack-worker-loader", "*-webworker-loader", "*-web-loader", "*-loader", "*"], ["*-webpack-node-loader", "*-node-loader", "*-loader", "*"], ["*-webpack-node-webkit-loader", "*-webpack-node-loader", "*-node-loader", "*-loader", "*-web-loader", "*"], ["*-loader", "*"]); }; diff --git a/lib/dependencies/AMDDefineDependency.js b/lib/dependencies/AMDDefineDependency.js index 6ccbcca8e..e5f4fac18 100644 --- a/lib/dependencies/AMDDefineDependency.js +++ b/lib/dependencies/AMDDefineDependency.js @@ -22,26 +22,27 @@ AMDDefineDependency.Template = function AMDRequireDependencyTemplate() {}; AMDDefineDependency.Template.prototype.apply = function(dep, source) { var localModuleVar = dep.localModule && dep.localModule.used && dep.localModule.variableName(); + function replace(def, text) { - if(localModuleVar) text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); - if(localModuleVar) def = def.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); + if (localModuleVar) text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); + if (localModuleVar) def = def.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); var texts = text.split("#"); - if(def) + if (def) source.insert(0, def); var current = dep.range[0]; - if(dep.arrayRange) { + if (dep.arrayRange) { source.replace(current, dep.arrayRange[0] - 1, texts.shift()); current = dep.arrayRange[1]; } - if(dep.objectRange) { + if (dep.objectRange) { source.replace(current, dep.objectRange[0] - 1, texts.shift()); current = dep.objectRange[1]; - } else if(dep.functionRange) { + } else if (dep.functionRange) { source.replace(current, dep.functionRange[0] - 1, texts.shift()); current = dep.functionRange[1]; } source.replace(current, dep.range[1] - 1, texts.shift()); - if(texts.length > 0) + if (texts.length > 0) throw new Error("Implementation error"); } var branch = (localModuleVar ? "l" : "") + (dep.arrayRange ? "a" : "") + (dep.objectRange ? "o" : "") + (dep.functionRange ? "f" : ""); diff --git a/lib/dependencies/AMDDefineDependencyParserPlugin.js b/lib/dependencies/AMDDefineDependencyParserPlugin.js index 19ceaf910..004fe9edb 100644 --- a/lib/dependencies/AMDDefineDependencyParserPlugin.js +++ b/lib/dependencies/AMDDefineDependencyParserPlugin.js @@ -12,12 +12,12 @@ var ContextDependencyHelpers = require("./ContextDependencyHelpers"); var LocalModulesHelpers = require("./LocalModulesHelpers"); function isBoundFunctionExpression(expr) { - if(expr.type !== "CallExpression") return false; - if(expr.callee.type !== "MemberExpression") return false; - if(expr.callee.computed) return false; - if(expr.callee.object.type !== "FunctionExpression") return false; - if(expr.callee.property.type !== "Identifier") return false; - if(expr.callee.property.name !== "bind") return false; + if (expr.type !== "CallExpression") return false; + if (expr.callee.type !== "MemberExpression") return false; + if (expr.callee.computed) return false; + if (expr.callee.object.type !== "FunctionExpression") return false; + if (expr.callee.property.type !== "Identifier") return false; + if (expr.callee.property.name !== "bind") return false; return true; } @@ -30,87 +30,88 @@ AMDDefineDependencyParserPlugin.prototype.apply = function(parser) { var options = this.options; parser.plugin("call define", function(expr) { var array, fn, obj, namedModule; - switch(expr.arguments.length) { - case 1: - if(expr.arguments[0].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[0])) { - // define(f() {...}) - fn = expr.arguments[0]; - } else if(expr.arguments[0].type === "ObjectExpression") { - // define({...}) - obj = expr.arguments[0]; - } else { - // define(expr) - // unclear if function or object - obj = fn = expr.arguments[0]; - } - break; - case 2: - if(expr.arguments[0].type === "Literal") { + switch (expr.arguments.length) { + case 1: + if (expr.arguments[0].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[0])) { + // define(f() {...}) + fn = expr.arguments[0]; + } else if (expr.arguments[0].type === "ObjectExpression") { + // define({...}) + obj = expr.arguments[0]; + } else { + // define(expr) + // unclear if function or object + obj = fn = expr.arguments[0]; + } + break; + case 2: + if (expr.arguments[0].type === "Literal") { + namedModule = expr.arguments[0].value; + // define("...", ...) + if (expr.arguments[1].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[1])) { + // define("...", f() {...}) + fn = expr.arguments[1]; + } else if (expr.arguments[1].type === "ObjectExpression") { + // define("...", {...}) + obj = expr.arguments[1]; + } else { + // define("...", expr) + // unclear if function or object + obj = fn = expr.arguments[1]; + } + } else { + array = expr.arguments[0]; + if (expr.arguments[1].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[1])) { + // define([...], f() {}) + fn = expr.arguments[1]; + } else if (expr.arguments[1].type === "ObjectExpression") { + // define([...], {...}) + obj = expr.arguments[1]; + } else { + // define([...], expr) + // unclear if function or object + obj = fn = expr.arguments[1]; + } + } + break; + case 3: + // define("...", [...], f() {...}) namedModule = expr.arguments[0].value; - // define("...", ...) - if(expr.arguments[1].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[1])) { - // define("...", f() {...}) - fn = expr.arguments[1]; - } else if(expr.arguments[1].type === "ObjectExpression") { - // define("...", {...}) - obj = expr.arguments[1]; + array = expr.arguments[1]; + if (expr.arguments[2].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[2])) { + // define("...", [...], f() {}) + fn = expr.arguments[2]; + } else if (expr.arguments[2].type === "ObjectExpression") { + // define("...", [...], {...}) + obj = expr.arguments[2]; } else { - // define("...", expr) + // define("...", [...], expr) // unclear if function or object - obj = fn = expr.arguments[1]; + obj = fn = expr.arguments[2]; } - } else { - array = expr.arguments[0]; - if(expr.arguments[1].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[1])) { - // define([...], f() {}) - fn = expr.arguments[1]; - } else if(expr.arguments[1].type === "ObjectExpression") { - // define([...], {...}) - obj = expr.arguments[1]; - } else { - // define([...], expr) - // unclear if function or object - obj = fn = expr.arguments[1]; - } - } - break; - case 3: - // define("...", [...], f() {...}) - namedModule = expr.arguments[0].value; - array = expr.arguments[1]; - if(expr.arguments[2].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[2])) { - // define("...", [...], f() {}) - fn = expr.arguments[2]; - } else if(expr.arguments[2].type === "ObjectExpression") { - // define("...", [...], {...}) - obj = expr.arguments[2]; - } else { - // define("...", [...], expr) - // unclear if function or object - obj = fn = expr.arguments[2]; - } - break; - default: return; + break; + default: + return; } var fnParams = null; var fnParamsOffset = 0; - if(fn) { - if(fn.type === "FunctionExpression") fnParams = fn.params; - else if(isBoundFunctionExpression(fn)) { + if (fn) { + if (fn.type === "FunctionExpression") 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; } } var fnRenames = Object.create(this.scope.renames); var identifiers; - if(array) { + if (array) { identifiers = {}; var param = this.evaluateExpression(array); var result = this.applyPluginsBailResult("call define:amd:array", expr, param, identifiers, namedModule); - if(!result) return; - if(fnParams) fnParams = fnParams.slice(fnParamsOffset).filter(function(param, idx) { - if(identifiers[idx]) { + if (!result) return; + if (fnParams) fnParams = fnParams.slice(fnParamsOffset).filter(function(param, idx) { + if (identifiers[idx]) { fnRenames["$" + param.name] = identifiers[idx]; return false; } @@ -118,8 +119,8 @@ AMDDefineDependencyParserPlugin.prototype.apply = function(parser) { }); } else { identifiers = ["require", "exports", "module"]; - if(fnParams) fnParams = fnParams.slice(fnParamsOffset).filter(function(param, idx) { - if(identifiers[idx]) { + if (fnParams) fnParams = fnParams.slice(fnParamsOffset).filter(function(param, idx) { + if (identifiers[idx]) { fnRenames["$" + param.name] = identifiers[idx]; return false; } @@ -127,63 +128,63 @@ AMDDefineDependencyParserPlugin.prototype.apply = function(parser) { }); } var inTry; - if(fn && fn.type === "FunctionExpression") { + if (fn && fn.type === "FunctionExpression") { inTry = this.scope.inTry; this.inScope(fnParams, function() { this.scope.renames = fnRenames; this.scope.inTry = inTry; - if(fn.body.type === "BlockStatement") + if (fn.body.type === "BlockStatement") this.walkStatement(fn.body); else this.walkExpression(fn.body); }.bind(this)); - } else if(fn && isBoundFunctionExpression(fn)) { + } else if (fn && isBoundFunctionExpression(fn)) { inTry = this.scope.inTry; this.inScope(fn.callee.object.params.filter(function(i) { return ["require", "module", "exports"].indexOf(i.name) < 0; }), function() { this.scope.renames = fnRenames; this.scope.inTry = inTry; - if(fn.callee.object.body.type === "BlockStatement") + if (fn.callee.object.body.type === "BlockStatement") this.walkStatement(fn.callee.object.body); else this.walkExpression(fn.callee.object.body); }.bind(this)); - if(fn.arguments) + if (fn.arguments) this.walkExpressions(fn.arguments); - } else if(fn || obj) { + } else if (fn || obj) { this.walkExpression(fn || obj); } var dep = new AMDDefineDependency(expr.range, array ? array.range : null, fn ? fn.range : null, obj ? obj.range : null); dep.loc = expr.loc; - if(namedModule) { + if (namedModule) { dep.localModule = LocalModulesHelpers.addLocalModule(this.state, namedModule); } this.state.current.addDependency(dep); return true; }); parser.plugin("call define:amd:array", function(expr, param, identifiers, namedModule) { - if(param.isArray()) { + if (param.isArray()) { param.items.forEach(function(param, idx) { - if(param.isString() && ["require", "module", "exports"].indexOf(param.string) >= 0) + if (param.isString() && ["require", "module", "exports"].indexOf(param.string) >= 0) identifiers[idx] = param.string; var result = this.applyPluginsBailResult("call define:amd:item", expr, param, namedModule); - if(result === undefined) { + if (result === undefined) { this.applyPluginsBailResult("call define:amd:context", expr, param); } }, this); return true; - } else if(param.isConstArray()) { + } else if (param.isConstArray()) { var deps = []; param.array.forEach(function(request, idx) { var dep, localModule; - if(request === "require") { + if (request === "require") { identifiers[idx] = request; dep = "__webpack_require__"; - } else if(["exports", "module"].indexOf(request) >= 0) { + } else if (["exports", "module"].indexOf(request) >= 0) { identifiers[idx] = request; dep = request; - } else if(localModule = LocalModulesHelpers.getLocalModule(this.state, request)) { // eslint-disable-line no-cond-assign + } else if (localModule = LocalModulesHelpers.getLocalModule(this.state, request)) { // eslint-disable-line no-cond-assign dep = new LocalModuleDependency(localModule); dep.loc = expr.loc; this.state.current.addDependency(dep); @@ -203,21 +204,21 @@ AMDDefineDependencyParserPlugin.prototype.apply = function(parser) { } }); parser.plugin("call define:amd:item", function(expr, param, namedModule) { - if(param.isConditional()) { + if (param.isConditional()) { param.options.forEach(function(param) { var result = this.applyPluginsBailResult("call define:amd:item", expr, param); - if(result === undefined) { + if (result === undefined) { this.applyPluginsBailResult("call define:amd:context", expr, param); } }, this); return true; - } else if(param.isString()) { + } else if (param.isString()) { var dep, localModule; - if(param.string === "require") { + if (param.string === "require") { dep = new ConstDependency("__webpack_require__", param.range); - } else if(["require", "exports", "module"].indexOf(param.string) >= 0) { + } else if (["require", "exports", "module"].indexOf(param.string) >= 0) { dep = new ConstDependency(param.string, param.range); - } else if(localModule = LocalModulesHelpers.getLocalModule(this.state, param.string, namedModule)) { // eslint-disable-line no-cond-assign + } else if (localModule = LocalModulesHelpers.getLocalModule(this.state, param.string, namedModule)) { // eslint-disable-line no-cond-assign dep = new LocalModuleDependency(localModule, param.range); } else { dep = new AMDRequireItemDependency(param.string, param.range); @@ -230,11 +231,10 @@ AMDDefineDependencyParserPlugin.prototype.apply = function(parser) { }); parser.plugin("call define:amd:context", function(expr, param) { var dep = ContextDependencyHelpers.create(AMDRequireContextDependency, param.range, param, expr, options); - if(!dep) return; + if (!dep) return; dep.loc = expr.loc; dep.optional = !!this.scope.inTry; this.state.current.addDependency(dep); return true; }); }; - diff --git a/lib/dependencies/AMDPlugin.js b/lib/dependencies/AMDPlugin.js index d9b97bd80..82ea2c255 100644 --- a/lib/dependencies/AMDPlugin.js +++ b/lib/dependencies/AMDPlugin.js @@ -38,6 +38,7 @@ AMDPlugin.prototype.apply = function(compiler) { return true; }); } + function setExpressionToModule(expr, module) { compiler.parser.plugin("expression " + expr, function(expr) { var dep = new AMDRequireItemDependency(module, expr.range); diff --git a/lib/dependencies/AMDRequireArrayDependency.js b/lib/dependencies/AMDRequireArrayDependency.js index 2909bb9f7..ef8570f59 100644 --- a/lib/dependencies/AMDRequireArrayDependency.js +++ b/lib/dependencies/AMDRequireArrayDependency.js @@ -20,12 +20,12 @@ AMDRequireArrayDependency.Template = function AMDRequireArrayDependencyTemplate( AMDRequireArrayDependency.Template.prototype.apply = function(dep, source, outputOptions, requestShortener) { var content = "[" + dep.depsArray.map(function(dep) { - if(typeof dep === "string") { + if (typeof dep === "string") { return dep; } else { var comment = ""; - if(outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ "; - if(dep.module) + if (outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ "; + if (dep.module) return "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")"; else return require("./WebpackMissingModule").module(dep.request); diff --git a/lib/dependencies/AMDRequireDependenciesBlock.js b/lib/dependencies/AMDRequireDependenciesBlock.js index 97f997191..e145b2d83 100644 --- a/lib/dependencies/AMDRequireDependenciesBlock.js +++ b/lib/dependencies/AMDRequireDependenciesBlock.js @@ -22,4 +22,3 @@ function AMDRequireDependenciesBlock(expr, arrayRange, functionRange, module, lo module.exports = AMDRequireDependenciesBlock; AMDRequireDependenciesBlock.prototype = Object.create(AsyncDependenciesBlock.prototype); - diff --git a/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js b/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js index 6370ef53f..f95ac26b7 100644 --- a/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js +++ b/lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js @@ -20,67 +20,67 @@ module.exports = AMDRequireDependenciesBlockParserPlugin; AMDRequireDependenciesBlockParserPlugin.prototype.apply = function(parser) { var options = this.options; parser.plugin("call require", function(expr) { - switch(expr.arguments.length) { - case 1: - var param = this.evaluateExpression(expr.arguments[0]); - var result; - var dep = new AMDRequireDependenciesBlock(expr, param.range, null, this.state.module, expr.loc); - var old = this.state.current; - this.state.current = dep; - this.inScope([], function() { - result = this.applyPluginsBailResult("call require:amd:array", expr, param); - }.bind(this)); - this.state.current = old; - if(!result) return; - this.state.current.addBlock(dep); - return true; - case 2: - var param = this.evaluateExpression(expr.arguments[0]); - var dep = new AMDRequireDependenciesBlock(expr, param.range, expr.arguments[1].range, this.state.module, expr.loc); - dep.loc = expr.loc; - var old = this.state.current; - this.state.current = dep; - try { + switch (expr.arguments.length) { + case 1: + var param = this.evaluateExpression(expr.arguments[0]); var result; + var dep = new AMDRequireDependenciesBlock(expr, param.range, null, this.state.module, expr.loc); + var old = this.state.current; + this.state.current = dep; this.inScope([], function() { result = this.applyPluginsBailResult("call require:amd:array", expr, param); }.bind(this)); - if(!result) return; - if(expr.arguments[1].type === "FunctionExpression") { - this.inScope(expr.arguments[1].params.filter(function(i) { - return ["require", "module", "exports"].indexOf(i.name) < 0; - }), function() { - if(expr.arguments[1].body.type === "BlockStatement") - this.walkStatement(expr.arguments[1].body); - else - this.walkExpression(expr.arguments[1].body); - }.bind(this)); - } - } finally { this.state.current = old; + if (!result) return; this.state.current.addBlock(dep); - } - return true; + return true; + case 2: + var param = this.evaluateExpression(expr.arguments[0]); + var dep = new AMDRequireDependenciesBlock(expr, param.range, expr.arguments[1].range, this.state.module, expr.loc); + dep.loc = expr.loc; + var old = this.state.current; + this.state.current = dep; + try { + var result; + this.inScope([], function() { + result = this.applyPluginsBailResult("call require:amd:array", expr, param); + }.bind(this)); + if (!result) return; + if (expr.arguments[1].type === "FunctionExpression") { + this.inScope(expr.arguments[1].params.filter(function(i) { + return ["require", "module", "exports"].indexOf(i.name) < 0; + }), function() { + if (expr.arguments[1].body.type === "BlockStatement") + this.walkStatement(expr.arguments[1].body); + else + this.walkExpression(expr.arguments[1].body); + }.bind(this)); + } + } finally { + this.state.current = old; + this.state.current.addBlock(dep); + } + return true; } }); parser.plugin("call require:amd:array", function(expr, param) { - if(param.isArray()) { + if (param.isArray()) { param.items.forEach(function(param) { var result = this.applyPluginsBailResult("call require:amd:item", expr, param); - if(result === undefined) { + if (result === undefined) { this.applyPluginsBailResult("call require:amd:context", expr, param); } }, this); return true; - } else if(param.isConstArray()) { + } else if (param.isConstArray()) { var deps = []; param.array.forEach(function(request) { var dep, localModule; - if(request === "require") { + if (request === "require") { dep = "__webpack_require__"; - } else if(["exports", "module"].indexOf(request) >= 0) { + } else if (["exports", "module"].indexOf(request) >= 0) { dep = request; - } else if(localModule = LocalModulesHelpers.getLocalModule(this.state, request)) { // eslint-disable-line no-cond-assign + } else if (localModule = LocalModulesHelpers.getLocalModule(this.state, request)) { // eslint-disable-line no-cond-assign dep = new LocalModuleDependency(localModule); dep.loc = expr.loc; this.state.current.addDependency(dep); @@ -100,21 +100,21 @@ AMDRequireDependenciesBlockParserPlugin.prototype.apply = function(parser) { } }); parser.plugin("call require:amd:item", function(expr, param) { - if(param.isConditional()) { + if (param.isConditional()) { param.options.forEach(function(param) { var result = this.applyPluginsBailResult("call require:amd:item", expr, param); - if(result === undefined) { + if (result === undefined) { this.applyPluginsBailResult("call require:amd:context", expr, param); } }, this); return true; - } else if(param.isString()) { + } else if (param.isString()) { var dep, localModule; - if(param.string === "require") { + if (param.string === "require") { dep = new ConstDependency("__webpack_require__", param.string); - } else if(["exports", "module"].indexOf(param.string) >= 0) { + } else if (["exports", "module"].indexOf(param.string) >= 0) { dep = new ConstDependency(param.string, param.range); - } else if(localModule = LocalModulesHelpers.getLocalModule(this.state, param.string)) { // eslint-disable-line no-cond-assign + } else if (localModule = LocalModulesHelpers.getLocalModule(this.state, param.string)) { // eslint-disable-line no-cond-assign dep = new LocalModuleDependency(localModule, param.range); } else { dep = new AMDRequireItemDependency(param.string, param.range); @@ -127,11 +127,10 @@ AMDRequireDependenciesBlockParserPlugin.prototype.apply = function(parser) { }); parser.plugin("call require:amd:context", function(expr, param) { var dep = ContextDependencyHelpers.create(AMDRequireContextDependency, param.range, param, expr, options); - if(!dep) return; + if (!dep) return; dep.loc = expr.loc; dep.optional = !!this.scope.inTry; this.state.current.addDependency(dep); return true; }); }; - diff --git a/lib/dependencies/AMDRequireDependency.js b/lib/dependencies/AMDRequireDependency.js index 1f183e138..cdd1c1e91 100644 --- a/lib/dependencies/AMDRequireDependency.js +++ b/lib/dependencies/AMDRequireDependency.js @@ -20,8 +20,8 @@ AMDRequireDependency.Template = function AMDRequireDependencyTemplate() {}; AMDRequireDependency.Template.prototype.apply = function(dep, source, outputOptions, requestShortener) { var depBlock = dep.block; var wrapper = DepBlockHelpers.getLoadDepBlockWrapper(depBlock, outputOptions, requestShortener, "require"); - if(depBlock.arrayRange && !depBlock.functionRange) { - if(wrapper) { + if (depBlock.arrayRange && !depBlock.functionRange) { + if (wrapper) { source.replace(depBlock.outerRange[0], depBlock.arrayRange[0] - 1, wrapper[0] + "function() {"); source.replace(depBlock.arrayRange[1], depBlock.outerRange[1] - 1, ";}" + wrapper[1]); @@ -30,8 +30,8 @@ AMDRequireDependency.Template.prototype.apply = function(dep, source, outputOpti "!/* require */(" + asComment(depBlock.chunkReason)); source.replace(depBlock.arrayRange[1], depBlock.outerRange[1] - 1, ")"); } - } else if(!depBlock.arrayRange && depBlock.functionRange) { - if(wrapper) { + } else if (!depBlock.arrayRange && depBlock.functionRange) { + if (wrapper) { source.replace(depBlock.outerRange[0], depBlock.functionRange[0] - 1, wrapper[0] + "function(__webpack_require__) {("); source.replace(depBlock.functionRange[1], depBlock.outerRange[1] - 1, ".call(exports, __webpack_require__, exports, module));}" + wrapper[1]); @@ -40,8 +40,8 @@ AMDRequireDependency.Template.prototype.apply = function(dep, source, outputOpti "!/* require */(" + asComment(depBlock.chunkReason)); source.replace(depBlock.functionRange[1], depBlock.outerRange[1] - 1, ".call(exports, __webpack_require__, exports, module))"); } - } else if(depBlock.arrayRange && depBlock.functionRange) { - if(wrapper) { + } else if (depBlock.arrayRange && depBlock.functionRange) { + if (wrapper) { source.replace(depBlock.outerRange[0], depBlock.arrayRange[0] - 1, wrapper[0] + "function(__webpack_require__) { "); source.insert(depBlock.arrayRange[0] + 0.9, "var __WEBPACK_AMD_REQUIRE_ARRAY__ = "); @@ -60,6 +60,6 @@ AMDRequireDependency.Template.prototype.apply = function(dep, source, outputOpti }; function asComment(str) { - if(!str) return ""; + if (!str) return ""; return "/* " + str + " */"; } diff --git a/lib/dependencies/CommonJsRequireDependencyParserPlugin.js b/lib/dependencies/CommonJsRequireDependencyParserPlugin.js index 91d3a30ac..e78704820 100644 --- a/lib/dependencies/CommonJsRequireDependencyParserPlugin.js +++ b/lib/dependencies/CommonJsRequireDependencyParserPlugin.js @@ -33,10 +33,10 @@ CommonJsRequireDependencyParserPlugin.prototype.apply = function(parser) { return true; }); parser.plugin("call require", function(expr) { - if(expr.arguments.length !== 1) return; + if (expr.arguments.length !== 1) return; var localModule, dep; var param = this.evaluateExpression(expr.arguments[0]); - if(param.isConditional()) { + if (param.isConditional()) { var isExpression = false; var prevLength = this.state.current.dependencies.length; dep = new RequireHeaderDependency(expr.callee.range); @@ -44,24 +44,24 @@ CommonJsRequireDependencyParserPlugin.prototype.apply = function(parser) { this.state.current.addDependency(dep); param.options.forEach(function(param) { var result = this.applyPluginsBailResult("call require:commonjs:item", expr, param); - if(result === undefined) { + if (result === undefined) { isExpression = true; } }, this); - if(isExpression) { + if (isExpression) { this.state.current.dependencies.length = prevLength; } else { return true; } } - if(param.isString() && (localModule = LocalModulesHelpers.getLocalModule(this.state, param.string))) { + if (param.isString() && (localModule = LocalModulesHelpers.getLocalModule(this.state, param.string))) { dep = new LocalModuleDependency(localModule, expr.range); dep.loc = expr.loc; this.state.current.addDependency(dep); return true; } else { var result = this.applyPluginsBailResult("call require:commonjs:item", expr, param); - if(result === undefined) { + if (result === undefined) { this.applyPluginsBailResult("call require:commonjs:context", expr, param); } else { dep = new RequireHeaderDependency(expr.callee.range); @@ -72,7 +72,7 @@ CommonJsRequireDependencyParserPlugin.prototype.apply = function(parser) { } }); parser.plugin("call require:commonjs:item", function(expr, param) { - if(param.isString()) { + if (param.isString()) { var dep = new CommonJsRequireDependency(param.string, param.range); dep.loc = expr.loc; dep.optional = !!this.scope.inTry; @@ -82,11 +82,10 @@ CommonJsRequireDependencyParserPlugin.prototype.apply = function(parser) { }); parser.plugin("call require:commonjs:context", function(expr, param) { var dep = ContextDependencyHelpers.create(CommonJsRequireContextDependency, expr.range, param, expr, options); - if(!dep) return; + if (!dep) return; dep.loc = expr.loc; dep.optional = !!this.scope.inTry; this.state.current.addDependency(dep); return true; }); }; - diff --git a/lib/dependencies/ConstDependency.js b/lib/dependencies/ConstDependency.js index f93cf035d..775e4a031 100644 --- a/lib/dependencies/ConstDependency.js +++ b/lib/dependencies/ConstDependency.js @@ -18,7 +18,7 @@ ConstDependency.prototype.constructor = ConstDependency; ConstDependency.Template = function ConstDependencyTemplate() {}; ConstDependency.Template.prototype.apply = function(dep, source) { - if(typeof dep.range === "number") + if (typeof dep.range === "number") source.insert(dep.range, dep.expression); else source.replace(dep.range[0], dep.range[1] - 1, dep.expression); diff --git a/lib/dependencies/ContextDependency.js b/lib/dependencies/ContextDependency.js index 0e865a641..455330dc8 100644 --- a/lib/dependencies/ContextDependency.js +++ b/lib/dependencies/ContextDependency.js @@ -17,7 +17,7 @@ module.exports = ContextDependency; ContextDependency.prototype = Object.create(Dependency.prototype); ContextDependency.prototype.constructor = ContextDependency; ContextDependency.prototype.isEqualResource = function(other) { - if(!(other instanceof ContextDependency)) + if (!(other instanceof ContextDependency)) return false; return this.request === other.request && this.recursive === other.recursive && diff --git a/lib/dependencies/ContextDependencyHelpers.js b/lib/dependencies/ContextDependencyHelpers.js index 7a15cec75..2f84872a3 100644 --- a/lib/dependencies/ContextDependencyHelpers.js +++ b/lib/dependencies/ContextDependencyHelpers.js @@ -5,14 +5,14 @@ var ContextDependencyHelpers = exports; ContextDependencyHelpers.create = function(Dep, range, param, expr, options) { - if(param.isWrapped() && (param.prefix && param.prefix.isString() || param.postfix && param.postfix.isString())) { + if (param.isWrapped() && (param.prefix && param.prefix.isString() || param.postfix && param.postfix.isString())) { var prefix = param.prefix && param.prefix.isString() ? param.prefix.string : ""; var postfix = param.postfix && param.postfix.isString() ? param.postfix.string : ""; var prefixRange = param.prefix && param.prefix.isString() ? param.prefix.range : null; var valueRange = [prefixRange ? prefixRange[1] : param.range[0], param.range[1]]; var idx = prefix.lastIndexOf("/"); var context = "."; - if(idx >= 0) { + if (idx >= 0) { context = prefix.substr(0, idx); prefix = "." + prefix.substr(idx); } diff --git a/lib/dependencies/ContextDependencyTemplateAsId.js b/lib/dependencies/ContextDependencyTemplateAsId.js index 38820ca37..ef35fe807 100644 --- a/lib/dependencies/ContextDependencyTemplateAsId.js +++ b/lib/dependencies/ContextDependencyTemplateAsId.js @@ -7,9 +7,9 @@ module.exports = ContextDependencyTemplateAsId; ContextDependencyTemplateAsId.prototype.apply = function(dep, source, outputOptions, requestShortener) { var comment = ""; - if(outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ "; - if(dep.module && dep.module.dependencies && dep.module.dependencies.length > 0) { - if(dep.valueRange) { + if (outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ "; + if (dep.module && dep.module.dependencies && dep.module.dependencies.length > 0) { + if (dep.valueRange) { source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); source.replace(dep.range[0], dep.valueRange[0] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ").resolve(" + (typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "") + ""); } else { diff --git a/lib/dependencies/ContextDependencyTemplateAsRequireCall.js b/lib/dependencies/ContextDependencyTemplateAsRequireCall.js index d1bfea04f..e670e2cd7 100644 --- a/lib/dependencies/ContextDependencyTemplateAsRequireCall.js +++ b/lib/dependencies/ContextDependencyTemplateAsRequireCall.js @@ -7,9 +7,9 @@ module.exports = ContextDependencyTemplateAsRequireCall; ContextDependencyTemplateAsRequireCall.prototype.apply = function(dep, source, outputOptions, requestShortener) { var comment = ""; - if(outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ "; - if(dep.module && dep.module.dependencies && dep.module.dependencies.length > 0) { - if(dep.valueRange) { + if (outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ "; + if (dep.module && dep.module.dependencies && dep.module.dependencies.length > 0) { + if (dep.valueRange) { source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); source.replace(dep.range[0], dep.valueRange[0] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")(" + (typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "") + ""); } else { @@ -22,7 +22,7 @@ ContextDependencyTemplateAsRequireCall.prototype.apply = function(dep, source, o }; ContextDependencyTemplateAsRequireCall.prototype.applyAsTemplateArgument = function(name, dep, source) { - if(dep.valueRange) { + if (dep.valueRange) { source.replace(dep.valueRange[1], dep.range[1] - 1, ")"); source.replace(dep.range[0], dep.valueRange[0] - 1, "__webpack_require__(" + name + ")(" + (typeof dep.prepend === "string" ? JSON.stringify(dep.prepend) : "") + ""); } else { diff --git a/lib/dependencies/DepBlockHelpers.js b/lib/dependencies/DepBlockHelpers.js index 371f5aa7a..34ff72aa3 100644 --- a/lib/dependencies/DepBlockHelpers.js +++ b/lib/dependencies/DepBlockHelpers.js @@ -5,11 +5,11 @@ var DepBlockHelpers = exports; DepBlockHelpers.getLoadDepBlockWrapper = function(depBlock, outputOptions, requestShortener, name) { - if(depBlock.chunks) { + if (depBlock.chunks) { var chunks = depBlock.chunks.filter(function(chunk) { return !chunk.entry && typeof chunk.id === "number"; }); - if(chunks.length === 1) { + if (chunks.length === 1) { var chunk = chunks[0]; return [ "__webpack_require__.e" + asComment(name) + "(" + chunk.id + "" + @@ -17,7 +17,7 @@ DepBlockHelpers.getLoadDepBlockWrapper = function(depBlock, outputOptions, reque asComment(depBlock.chunkReason) + ", ", ")" ]; - } else if(chunks.length > 0) { + } else if (chunks.length > 0) { return [ "(function(" + asComment(name) + ") {" + "var __WEBPACK_REMAINING_CHUNKS__ = " + chunks.length + ";" + @@ -36,6 +36,6 @@ DepBlockHelpers.getLoadDepBlockWrapper = function(depBlock, outputOptions, reque }; function asComment(str) { - if(!str) return ""; + if (!str) return ""; return "/* " + str + " */"; } diff --git a/lib/dependencies/LabeledModuleDependency.js b/lib/dependencies/LabeledModuleDependency.js index d0b4727c1..70581a0d1 100644 --- a/lib/dependencies/LabeledModuleDependency.js +++ b/lib/dependencies/LabeledModuleDependency.js @@ -19,15 +19,16 @@ LabeledModuleDependency.prototype.type = "labeled require"; LabeledModuleDependency.Template = function LabeledModuleDependencyTemplate() {}; LabeledModuleDependency.Template.prototype.apply = function(dep, source, outputOptions, requestShortener) { - var comment = "", content; - if(outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ "; - if(dep.module && dep.module.meta && dep.module.meta.exports) { + var comment = "", + content; + if (outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ "; + if (dep.module && dep.module.meta && dep.module.meta.exports) { content = "var __WEBPACK_LABELED_MODULE__" + Template.toIdentifier(dep.module.id) + " = __webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")"; dep.module.meta.exports.forEach(function(e) { content += ", " + e + " = __WEBPACK_LABELED_MODULE__" + Template.toIdentifier(dep.module.id) + "." + e; }); content += ";"; - } else if(dep.module) { + } else if (dep.module) { content = require("./WebpackMissingModule").moduleMetaInfo(dep.request); } else { content = require("./WebpackMissingModule").module(dep.request); diff --git a/lib/dependencies/LabeledModuleDependencyParserPlugin.js b/lib/dependencies/LabeledModuleDependencyParserPlugin.js index d055cdb42..ec541cae8 100644 --- a/lib/dependencies/LabeledModuleDependencyParserPlugin.js +++ b/lib/dependencies/LabeledModuleDependencyParserPlugin.js @@ -8,21 +8,21 @@ var LabeledExportsDependency = require("./LabeledExportsDependency"); module.exports = AbstractPlugin.create({ "label require": function(stmt) { - if(stmt.body.type !== "ExpressionStatement") return; - switch(stmt.body.expression.type) { - case "Literal": - var param = this.evaluateExpression(stmt.body.expression); - return this.applyPluginsBailResult("label require:item", stmt, param); - case "SequenceExpression": - stmt.body.expression.expressions.forEach(function(expression) { - var param = this.evaluateExpression(expression); + if (stmt.body.type !== "ExpressionStatement") return; + switch (stmt.body.expression.type) { + case "Literal": + var param = this.evaluateExpression(stmt.body.expression); return this.applyPluginsBailResult("label require:item", stmt, param); - }, this); - return true; + case "SequenceExpression": + stmt.body.expression.expressions.forEach(function(expression) { + var param = this.evaluateExpression(expression); + return this.applyPluginsBailResult("label require:item", stmt, param); + }, this); + return true; } }, "label require:item": function(stmt, param) { - if(param.isString()) { + if (param.isString()) { var dep = new LabeledModuleDependency(param.string, stmt.range); dep.loc = stmt.loc; dep.optional = !!this.scope.inTry; @@ -31,47 +31,46 @@ module.exports = AbstractPlugin.create({ } }, "label exports": function(stmt) { - switch(stmt.body.type) { - case "VariableDeclaration": - stmt.body.declarations.forEach(function(decl) { - if(!decl.init) return; - var dep = new LabeledExportsDependency(decl.id.name, decl.init.range[0]); - dep.loc = stmt.loc; - this.state.current.addDependency(dep); - if(!this.state.module.meta.exports) this.state.module.meta.exports = []; - this.state.module.meta.exports.push(decl.id.name); - }, this); - return true; - case "FunctionDeclaration": - var name = stmt.body.id.name; - var dep = new LabeledExportsDependency(name, stmt.body.range[0]); - dep.loc = stmt.loc; - this.state.current.addDependency(dep); - if(!this.state.module.meta.exports) this.state.module.meta.exports = []; - this.state.module.meta.exports.push(name); - return true; - case "ExpressionStatement": - if(stmt.body.expression.type === "Identifier") { - var name = stmt.body.expression.name; - var dep = new LabeledExportsDependency(name, stmt.body.expression.range[0]); - dep.loc = stmt.loc; - this.state.current.addDependency(dep); - if(!this.state.module.meta.exports) this.state.module.meta.exports = []; - this.state.module.meta.exports.push(name); - return true; - } else if(stmt.body.expression.type === "SequenceExpression") { - stmt.body.expression.expressions.forEach(function(e) { - if(e.type !== "Identifier") return; - var name = e.name; - var dep = new LabeledExportsDependency(name, e.range[0]); + switch (stmt.body.type) { + case "VariableDeclaration": + stmt.body.declarations.forEach(function(decl) { + if (!decl.init) return; + var dep = new LabeledExportsDependency(decl.id.name, decl.init.range[0]); dep.loc = stmt.loc; this.state.current.addDependency(dep); - if(!this.state.module.meta.exports) this.state.module.meta.exports = []; - this.state.module.meta.exports.push(name); + if (!this.state.module.meta.exports) this.state.module.meta.exports = []; + this.state.module.meta.exports.push(decl.id.name); }, this); return true; - } + case "FunctionDeclaration": + var name = stmt.body.id.name; + var dep = new LabeledExportsDependency(name, stmt.body.range[0]); + dep.loc = stmt.loc; + this.state.current.addDependency(dep); + if (!this.state.module.meta.exports) this.state.module.meta.exports = []; + this.state.module.meta.exports.push(name); + return true; + case "ExpressionStatement": + if (stmt.body.expression.type === "Identifier") { + var name = stmt.body.expression.name; + var dep = new LabeledExportsDependency(name, stmt.body.expression.range[0]); + dep.loc = stmt.loc; + this.state.current.addDependency(dep); + if (!this.state.module.meta.exports) this.state.module.meta.exports = []; + this.state.module.meta.exports.push(name); + return true; + } else if (stmt.body.expression.type === "SequenceExpression") { + stmt.body.expression.expressions.forEach(function(e) { + if (e.type !== "Identifier") return; + var name = e.name; + var dep = new LabeledExportsDependency(name, e.range[0]); + dep.loc = stmt.loc; + this.state.current.addDependency(dep); + if (!this.state.module.meta.exports) this.state.module.meta.exports = []; + this.state.module.meta.exports.push(name); + }, this); + return true; + } } } }); - diff --git a/lib/dependencies/LabeledModulesPlugin.js b/lib/dependencies/LabeledModulesPlugin.js index d92155384..db76de486 100644 --- a/lib/dependencies/LabeledModulesPlugin.js +++ b/lib/dependencies/LabeledModulesPlugin.js @@ -9,8 +9,7 @@ var NullFactory = require("../NullFactory"); var LabeledModuleDependencyParserPlugin = require("./LabeledModuleDependencyParserPlugin"); -function LabeledModulesPlugin() { -} +function LabeledModulesPlugin() {} module.exports = LabeledModulesPlugin; LabeledModulesPlugin.prototype.apply = function(compiler) { diff --git a/lib/dependencies/LoaderPlugin.js b/lib/dependencies/LoaderPlugin.js index ffc1ced7d..9aa1c4d77 100644 --- a/lib/dependencies/LoaderPlugin.js +++ b/lib/dependencies/LoaderPlugin.js @@ -4,8 +4,7 @@ */ var LoaderDependency = require("./LoaderDependency"); -function LoaderPlugin() { -} +function LoaderPlugin() {} module.exports = LoaderPlugin; LoaderPlugin.prototype.apply = function(compiler) { @@ -19,22 +18,24 @@ LoaderPlugin.prototype.apply = function(compiler) { loaderContext.loadModule = function loadModule(request, callback) { var dep = new LoaderDependency(request); dep.loc = request; - compilation.addModuleDependencies(module, [[dep]], true, "lm", false, function(err) { - if(err) return callback(err); + compilation.addModuleDependencies(module, [ + [dep] + ], true, "lm", false, function(err) { + if (err) return callback(err); module = dep.module; - if(!module) return callback(new Error("Cannot load the module")); - if(module.building) module.building.push(next); + if (!module) return callback(new Error("Cannot load the module")); + if (module.building) module.building.push(next); else next(); function next(err) { - if(err) return callback(err); + if (err) return callback(err); - 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"); + 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"); var source, map; var moduleSource = dep.module._source; - if(moduleSource.sourceAndMap) { + if (moduleSource.sourceAndMap) { var sourceAndMap = moduleSource.sourceAndMap(); map = sourceAndMap.map; source = sourceAndMap.source; @@ -42,12 +43,12 @@ LoaderPlugin.prototype.apply = function(compiler) { map = moduleSource.map(); source = moduleSource.source(); } - if(dep.module.fileDependencies) { + if (dep.module.fileDependencies) { dep.module.fileDependencies.forEach(function(dep) { loaderContext.addDependency(dep); }); } - if(dep.module.contextDependencies) { + if (dep.module.contextDependencies) { dep.module.contextDependencies.forEach(function(dep) { loaderContext.addContextDependency(dep); }); diff --git a/lib/dependencies/LocalModuleDependency.js b/lib/dependencies/LocalModuleDependency.js index 0b4b002fe..f7e05ffab 100644 --- a/lib/dependencies/LocalModuleDependency.js +++ b/lib/dependencies/LocalModuleDependency.js @@ -19,6 +19,6 @@ LocalModuleDependency.prototype.constructor = LocalModuleDependency; LocalModuleDependency.Template = function LocalModuleDependencyTemplate() {}; LocalModuleDependency.Template.prototype.apply = function(dep, source) { - if(!dep.range) return; + if (!dep.range) return; source.replace(dep.range[0], dep.range[1] - 1, dep.localModule.variableName()); }; diff --git a/lib/dependencies/LocalModulesHelpers.js b/lib/dependencies/LocalModulesHelpers.js index d39b3fb96..021f2d6c6 100644 --- a/lib/dependencies/LocalModulesHelpers.js +++ b/lib/dependencies/LocalModulesHelpers.js @@ -7,20 +7,20 @@ var LocalModule = require("./LocalModule"); var LocalModulesHelpers = exports; LocalModulesHelpers.addLocalModule = function(state, name) { - if(!state.localModules) state.localModules = []; + if (!state.localModules) state.localModules = []; var m = new LocalModule(state.module, name, state.localModules.length); state.localModules.push(m); return m; }; LocalModulesHelpers.getLocalModule = function(state, name, namedModule) { - if(!state.localModules) return null; - if(namedModule) { + if (!state.localModules) return null; + if (namedModule) { // resolve dependency name relative to the defining named module name = lookup(namedModule, name); } - for(var i = 0; i < state.localModules.length; i++) { - if(state.localModules[i].name === name) + for (var i = 0; i < state.localModules.length; i++) { + if (state.localModules[i].name === name) return state.localModules[i]; } return null; @@ -29,8 +29,8 @@ LocalModulesHelpers.getLocalModule = function(state, name, namedModule) { function lookup(parent, mod) { if (mod.charAt(0) !== ".") return mod; - var path = parent.split("/") - , segs = mod.split("/"); + var path = parent.split("/"), + segs = mod.split("/"); path.pop(); for (var i = 0; i < segs.length; i++) { @@ -41,4 +41,3 @@ function lookup(parent, mod) { return path.join("/"); } - diff --git a/lib/dependencies/ModuleDependency.js b/lib/dependencies/ModuleDependency.js index 63548001a..035eadf7e 100644 --- a/lib/dependencies/ModuleDependency.js +++ b/lib/dependencies/ModuleDependency.js @@ -15,7 +15,7 @@ module.exports = ModuleDependency; ModuleDependency.prototype = Object.create(Dependency.prototype); ModuleDependency.prototype.constructor = ModuleDependency; ModuleDependency.prototype.isEqualResource = function isEqualResource(other) { - if(!(other instanceof ModuleDependency)) + if (!(other instanceof ModuleDependency)) return false; return this.request === other.request; }; diff --git a/lib/dependencies/ModuleDependencyTemplateAsId.js b/lib/dependencies/ModuleDependencyTemplateAsId.js index b947ccfed..08006f2ce 100644 --- a/lib/dependencies/ModuleDependencyTemplateAsId.js +++ b/lib/dependencies/ModuleDependencyTemplateAsId.js @@ -6,10 +6,10 @@ function ModuleDependencyTemplateAsId() {} module.exports = ModuleDependencyTemplateAsId; ModuleDependencyTemplateAsId.prototype.apply = function(dep, source, outputOptions, requestShortener) { - if(!dep.range) return; + if (!dep.range) return; var comment = ""; - if(outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ "; - if(dep.module) + if (outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ "; + if (dep.module) var content = comment + JSON.stringify(dep.module.id); else var content = require("./WebpackMissingModule").module(dep.request); @@ -17,6 +17,6 @@ ModuleDependencyTemplateAsId.prototype.apply = function(dep, source, outputOptio }; ModuleDependencyTemplateAsId.prototype.applyAsTemplateArgument = function(name, dep, source) { - if(!dep.range) return; + if (!dep.range) return; source.replace(dep.range[0], dep.range[1] - 1, name); }; diff --git a/lib/dependencies/ModuleDependencyTemplateAsRequireId.js b/lib/dependencies/ModuleDependencyTemplateAsRequireId.js index 93b7ecb56..0f487cffc 100644 --- a/lib/dependencies/ModuleDependencyTemplateAsRequireId.js +++ b/lib/dependencies/ModuleDependencyTemplateAsRequireId.js @@ -6,10 +6,10 @@ function ModuleDependencyTemplateAsRequireId() {} module.exports = ModuleDependencyTemplateAsRequireId; ModuleDependencyTemplateAsRequireId.prototype.apply = function(dep, source, outputOptions, requestShortener) { - if(!dep.range) return; + if (!dep.range) return; var comment = ""; - if(outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ "; - if(dep.module) + if (outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ "; + if (dep.module) var content = "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")"; else var content = require("./WebpackMissingModule").module(dep.request); @@ -17,6 +17,6 @@ ModuleDependencyTemplateAsRequireId.prototype.apply = function(dep, source, outp }; ModuleDependencyTemplateAsRequireId.prototype.applyAsTemplateArgument = function(name, dep, source) { - if(!dep.range) return; + if (!dep.range) return; source.replace(dep.range[0], dep.range[1] - 1, "(__webpack_require__(" + name + "))"); }; diff --git a/lib/dependencies/RequireContextDependencyParserPlugin.js b/lib/dependencies/RequireContextDependencyParserPlugin.js index e38739b35..1db2da189 100644 --- a/lib/dependencies/RequireContextDependencyParserPlugin.js +++ b/lib/dependencies/RequireContextDependencyParserPlugin.js @@ -9,26 +9,25 @@ module.exports = AbstractPlugin.create({ "call require.context": function(expr) { var regExp = /^\.\/.*$/; var recursive = true; - switch(expr.arguments.length) { - case 3: - var regExpExpr = this.evaluateExpression(expr.arguments[2]); - if(!regExpExpr.isRegExp()) return; - regExp = regExpExpr.regExp; - // falls through - case 2: - var recursiveExpr = this.evaluateExpression(expr.arguments[1]); - if(!recursiveExpr.isBoolean()) return; - recursive = recursiveExpr.bool; - // falls through - case 1: - var requestExpr = this.evaluateExpression(expr.arguments[0]); - if(!requestExpr.isString()) return; - var dep = new RequireContextDependency(requestExpr.string, recursive, regExp, expr.range); - dep.loc = expr.loc; - dep.optional = this.scope.inTry; - this.state.current.addDependency(dep); - return true; + switch (expr.arguments.length) { + case 3: + var regExpExpr = this.evaluateExpression(expr.arguments[2]); + if (!regExpExpr.isRegExp()) return; + regExp = regExpExpr.regExp; + // falls through + case 2: + var recursiveExpr = this.evaluateExpression(expr.arguments[1]); + if (!recursiveExpr.isBoolean()) return; + recursive = recursiveExpr.bool; + // falls through + case 1: + var requestExpr = this.evaluateExpression(expr.arguments[0]); + if (!requestExpr.isString()) return; + var dep = new RequireContextDependency(requestExpr.string, recursive, regExp, expr.range); + dep.loc = expr.loc; + dep.optional = this.scope.inTry; + this.state.current.addDependency(dep); + return true; } } }); - diff --git a/lib/dependencies/RequireContextPlugin.js b/lib/dependencies/RequireContextPlugin.js index 8d7f9d4f3..a7d05a244 100644 --- a/lib/dependencies/RequireContextPlugin.js +++ b/lib/dependencies/RequireContextPlugin.js @@ -27,7 +27,7 @@ RequireContextPlugin.prototype.apply = function(compiler) { }); compiler.plugin("context-module-factory", function(cmf) { cmf.plugin("alternatives", function(items, callback) { - if(items.length === 0) return callback(null, items); + if (items.length === 0) return callback(null, items); callback(null, items.map(function(obj) { return extensions.filter(function(ext) { @@ -45,13 +45,13 @@ RequireContextPlugin.prototype.apply = function(compiler) { }, [])); }); cmf.plugin("alternatives", function(items, callback) { - if(items.length === 0) return callback(null, items); + if (items.length === 0) return callback(null, items); callback(null, items.map(function(obj) { - for(var i = 0; i < modulesDirectories.length; i++) { + for (var i = 0; i < modulesDirectories.length; i++) { var dir = modulesDirectories[i]; var idx = obj.request.indexOf("./" + dir + "/"); - if(idx === 0) { + if (idx === 0) { obj.request = obj.request.slice(dir.length + 3); break; } diff --git a/lib/dependencies/RequireEnsureDependenciesBlock.js b/lib/dependencies/RequireEnsureDependenciesBlock.js index 4cae9d85f..f84dfb65a 100644 --- a/lib/dependencies/RequireEnsureDependenciesBlock.js +++ b/lib/dependencies/RequireEnsureDependenciesBlock.js @@ -18,4 +18,3 @@ function RequireEnsureDependenciesBlock(expr, fnExpression, chunkName, chunkName module.exports = RequireEnsureDependenciesBlock; RequireEnsureDependenciesBlock.prototype = Object.create(AsyncDependenciesBlock.prototype); - diff --git a/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js b/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js index 40f9f59f1..12eb3f11c 100644 --- a/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js +++ b/lib/dependencies/RequireEnsureDependenciesBlockParserPlugin.js @@ -9,58 +9,58 @@ var getFunctionExpression = require("./getFunctionExpression"); module.exports = AbstractPlugin.create({ "call require.ensure": function(expr) { - var chunkName = null, chunkNameRange = null; - switch(expr.arguments.length) { - case 3: - var chunkNameExpr = this.evaluateExpression(expr.arguments[2]); - if(!chunkNameExpr.isString()) return; - chunkNameRange = chunkNameExpr.range; - chunkName = chunkNameExpr.string; - // falls through - case 2: - var dependenciesExpr = this.evaluateExpression(expr.arguments[0]); - var dependenciesItems = dependenciesExpr.isArray() ? dependenciesExpr.items : [dependenciesExpr]; - var fnExpressionArg = expr.arguments[1]; - var fnExpression = getFunctionExpression(fnExpressionArg); + var chunkName = null, + chunkNameRange = null; + switch (expr.arguments.length) { + case 3: + var chunkNameExpr = this.evaluateExpression(expr.arguments[2]); + if (!chunkNameExpr.isString()) return; + chunkNameRange = chunkNameExpr.range; + chunkName = chunkNameExpr.string; + // falls through + case 2: + var dependenciesExpr = this.evaluateExpression(expr.arguments[0]); + var dependenciesItems = dependenciesExpr.isArray() ? dependenciesExpr.items : [dependenciesExpr]; + var fnExpressionArg = expr.arguments[1]; + var fnExpression = getFunctionExpression(fnExpressionArg); - if(fnExpression) { - this.walkExpressions(fnExpression.expressions); - } + if (fnExpression) { + this.walkExpressions(fnExpression.expressions); + } - var dep = new RequireEnsureDependenciesBlock(expr, fnExpression ? fnExpression.fn : fnExpressionArg, chunkName, chunkNameRange, this.state.module, expr.loc); - var old = this.state.current; - this.state.current = dep; - try { - var failed = false; - this.inScope([], function() { - dependenciesItems.forEach(function(ee) { - if(ee.isString()) { - var edep = new RequireEnsureItemDependency(ee.string, ee.range); - edep.loc = dep.loc; - dep.addDependency(edep); - } else { - failed = true; - } + var dep = new RequireEnsureDependenciesBlock(expr, fnExpression ? fnExpression.fn : fnExpressionArg, chunkName, chunkNameRange, this.state.module, expr.loc); + var old = this.state.current; + this.state.current = dep; + try { + var failed = false; + this.inScope([], function() { + dependenciesItems.forEach(function(ee) { + if (ee.isString()) { + var edep = new RequireEnsureItemDependency(ee.string, ee.range); + edep.loc = dep.loc; + dep.addDependency(edep); + } else { + failed = true; + } + }); }); - }); - if(failed) { - return; + if (failed) { + return; + } + if (fnExpression) { + if (fnExpression.fn.body.type === "BlockStatement") + this.walkStatement(fnExpression.fn.body); + else + this.walkExpression(fnExpression.fn.body); + } + old.addBlock(dep); + } finally { + this.state.current = old; } - if(fnExpression) { - if(fnExpression.fn.body.type === "BlockStatement") - this.walkStatement(fnExpression.fn.body); - else - this.walkExpression(fnExpression.fn.body); + if (!fnExpression) { + this.walkExpression(fnExpressionArg); } - old.addBlock(dep); - } finally { - this.state.current = old; - } - if(!fnExpression) { - this.walkExpression(fnExpressionArg); - } - return true; + return true; } } }); - diff --git a/lib/dependencies/RequireEnsureDependency.js b/lib/dependencies/RequireEnsureDependency.js index 322a8b08f..a838d6a5a 100644 --- a/lib/dependencies/RequireEnsureDependency.js +++ b/lib/dependencies/RequireEnsureDependency.js @@ -20,12 +20,11 @@ RequireEnsureDependency.Template = function RequireEnsureDependencyTemplate() {} RequireEnsureDependency.Template.prototype.apply = function(dep, source, outputOptions, requestShortener) { var depBlock = dep.block; - var wrapper = DepBlockHelpers.getLoadDepBlockWrapper(depBlock, outputOptions, requestShortener, /*require.e*/"nsure"); - if(!wrapper) wrapper = [ + var wrapper = DepBlockHelpers.getLoadDepBlockWrapper(depBlock, outputOptions, requestShortener, /*require.e*/ "nsure"); + if (!wrapper) wrapper = [ "!/* require.ensure */(", "(__webpack_require__))" ]; source.replace(depBlock.expr.range[0], depBlock.expr.arguments[1].range[0] - 1, wrapper[0]); source.replace(depBlock.expr.arguments[1].range[1], depBlock.expr.range[1] - 1, wrapper[1]); }; - diff --git a/lib/dependencies/RequireEnsurePlugin.js b/lib/dependencies/RequireEnsurePlugin.js index 5630795f1..e87896b83 100644 --- a/lib/dependencies/RequireEnsurePlugin.js +++ b/lib/dependencies/RequireEnsurePlugin.js @@ -12,8 +12,7 @@ var RequireEnsureDependenciesBlockParserPlugin = require("./RequireEnsureDepende var BasicEvaluatedExpression = require("../BasicEvaluatedExpression"); -function RequireEnsurePlugin() { -} +function RequireEnsurePlugin() {} module.exports = RequireEnsurePlugin; RequireEnsurePlugin.prototype.apply = function(compiler) { diff --git a/lib/dependencies/RequireHeaderDependency.js b/lib/dependencies/RequireHeaderDependency.js index 41d65c0a2..b93878305 100644 --- a/lib/dependencies/RequireHeaderDependency.js +++ b/lib/dependencies/RequireHeaderDependency.js @@ -5,7 +5,7 @@ var NullDependency = require("./NullDependency"); function RequireHeaderDependency(range) { - if(!Array.isArray(range)) throw new Error("range must be valid"); + if (!Array.isArray(range)) throw new Error("range must be valid"); NullDependency.call(this); this.Class = RequireHeaderDependency; this.range = range; diff --git a/lib/dependencies/RequireIncludeDependency.js b/lib/dependencies/RequireIncludeDependency.js index a4b899c51..fd361394a 100644 --- a/lib/dependencies/RequireIncludeDependency.js +++ b/lib/dependencies/RequireIncludeDependency.js @@ -19,8 +19,8 @@ RequireIncludeDependency.Template = function RequireIncludeDependencyTemplate() RequireIncludeDependency.Template.prototype.apply = function(dep, source, outputOptions, requestShortener) { var comment = ""; - if(outputOptions.pathinfo && dep.module) + if (outputOptions.pathinfo && dep.module) comment = "/*! require.include " + requestShortener.shorten(dep.request) + " */"; source.replace(dep.range[0], dep.range[1] - 1, - "undefined" + comment); + "undefined" + comment); }; diff --git a/lib/dependencies/RequireIncludeDependencyParserPlugin.js b/lib/dependencies/RequireIncludeDependencyParserPlugin.js index 793f03f6e..5abcb2895 100644 --- a/lib/dependencies/RequireIncludeDependencyParserPlugin.js +++ b/lib/dependencies/RequireIncludeDependencyParserPlugin.js @@ -7,13 +7,12 @@ var RequireIncludeDependency = require("./RequireIncludeDependency"); module.exports = AbstractPlugin.create({ "call require.include": function(expr) { - if(expr.arguments.length !== 1) return; + if (expr.arguments.length !== 1) return; var param = this.evaluateExpression(expr.arguments[0]); - if(!param.isString()) return; + if (!param.isString()) return; var dep = new RequireIncludeDependency(param.string, expr.range); dep.loc = expr.loc; this.state.current.addDependency(dep); return true; } }); - diff --git a/lib/dependencies/RequireIncludePlugin.js b/lib/dependencies/RequireIncludePlugin.js index 14964df70..5f1a2bee5 100644 --- a/lib/dependencies/RequireIncludePlugin.js +++ b/lib/dependencies/RequireIncludePlugin.js @@ -8,8 +8,7 @@ var ConstDependency = require("./ConstDependency"); var BasicEvaluatedExpression = require("../BasicEvaluatedExpression"); -function RequireIncludePlugin() { -} +function RequireIncludePlugin() {} module.exports = RequireIncludePlugin; RequireIncludePlugin.prototype.apply = function(compiler) { diff --git a/lib/dependencies/RequireResolveDependencyParserPlugin.js b/lib/dependencies/RequireResolveDependencyParserPlugin.js index 33d99c318..c5d9f5549 100644 --- a/lib/dependencies/RequireResolveDependencyParserPlugin.js +++ b/lib/dependencies/RequireResolveDependencyParserPlugin.js @@ -22,13 +22,13 @@ RequireResolveDependencyParserPlugin.prototype.apply = function(parser) { return this.applyPluginsBailResult("call require.resolve(Weak)", expr, true); }); parser.plugin("call require.resolve(Weak)", function(expr, weak) { - if(expr.arguments.length !== 1) return; + if (expr.arguments.length !== 1) return; var param = this.evaluateExpression(expr.arguments[0]); var dep; - if(param.isConditional()) { + if (param.isConditional()) { param.options.forEach(function(option) { var result = this.applyPluginsBailResult("call require.resolve(Weak):item", expr, option, weak); - if(result === undefined) { + if (result === undefined) { this.applyPluginsBailResult("call require.resolve(Weak):context", expr, option, weak); } }, this); @@ -38,7 +38,7 @@ RequireResolveDependencyParserPlugin.prototype.apply = function(parser) { return true; } else { var result = this.applyPluginsBailResult("call require.resolve(Weak):item", expr, param, weak); - if(result === undefined) { + if (result === undefined) { this.applyPluginsBailResult("call require.resolve(Weak):context", expr, param, weak); } dep = new RequireResolveHeaderDependency(expr.callee.range); @@ -48,7 +48,7 @@ RequireResolveDependencyParserPlugin.prototype.apply = function(parser) { } }); parser.plugin("call require.resolve(Weak):item", function(expr, param, weak) { - if(param.isString()) { + if (param.isString()) { var dep = new RequireResolveDependency(param.string, param.range); dep.loc = expr.loc; dep.optional = !!this.scope.inTry; @@ -59,7 +59,7 @@ RequireResolveDependencyParserPlugin.prototype.apply = function(parser) { }); parser.plugin("call require.resolve(Weak):context", function(expr, param, weak) { var dep = ContextDependencyHelpers.create(RequireResolveContextDependency, param.range, param, expr, options); - if(!dep) return; + if (!dep) return; dep.loc = expr.loc; dep.optional = !!this.scope.inTry; dep.weak = weak; @@ -67,4 +67,3 @@ RequireResolveDependencyParserPlugin.prototype.apply = function(parser) { return true; }); }; - diff --git a/lib/dependencies/RequireResolveHeaderDependency.js b/lib/dependencies/RequireResolveHeaderDependency.js index 0a88809f8..6b88b8af7 100644 --- a/lib/dependencies/RequireResolveHeaderDependency.js +++ b/lib/dependencies/RequireResolveHeaderDependency.js @@ -5,7 +5,7 @@ var NullDependency = require("./NullDependency"); function RequireResolveHeaderDependency(range) { - if(!Array.isArray(range)) throw new Error("range must be valid"); + if (!Array.isArray(range)) throw new Error("range must be valid"); NullDependency.call(this); this.Class = RequireResolveHeaderDependency; this.range = range; diff --git a/lib/dependencies/TemplateArgumentDependency.js b/lib/dependencies/TemplateArgumentDependency.js index deeea64c2..0ecdb66f3 100644 --- a/lib/dependencies/TemplateArgumentDependency.js +++ b/lib/dependencies/TemplateArgumentDependency.js @@ -22,7 +22,7 @@ TemplateArgumentDependency.Template = function TemplateArgumentDependencyTemplat TemplateArgumentDependency.Template.prototype.apply = function(dep, source, outputOptions, requestShortener, dependencyTemplates) { var d = dep.dep; var template = dependencyTemplates.get(d.Class); - if(!template) throw new Error("No template for dependency: " + d.Class.name); - if(!template.applyAsTemplateArgument) throw new Error("Template cannot be applied as TemplateArgument: " + d.Class.name); + if (!template) throw new Error("No template for dependency: " + d.Class.name); + if (!template.applyAsTemplateArgument) throw new Error("Template cannot be applied as TemplateArgument: " + d.Class.name); return template.applyAsTemplateArgument(dep.name, d, source, outputOptions, requestShortener, dependencyTemplates); }; diff --git a/lib/dependencies/getFunctionExpression.js b/lib/dependencies/getFunctionExpression.js index fb3b5e576..b17ea0c92 100644 --- a/lib/dependencies/getFunctionExpression.js +++ b/lib/dependencies/getFunctionExpression.js @@ -4,14 +4,14 @@ */ module.exports = function(expr) { // - if(expr.type === "FunctionExpression") { + if (expr.type === "FunctionExpression") { return { fn: expr, expressions: [] }; } // .bind() - if(expr.type === "CallExpression" && + if (expr.type === "CallExpression" && expr.callee.type === "MemberExpression" && expr.callee.object.type === "FunctionExpression" && expr.callee.property.type === "Identifier" && @@ -23,7 +23,7 @@ module.exports = function(expr) { }; } // (function(_this) {return })(this) (Coffeescript) - if(expr.type === "CallExpression" && + if (expr.type === "CallExpression" && expr.callee.type === "FunctionExpression" && expr.callee.body.type === "BlockStatement" && expr.arguments.length === 1 && diff --git a/lib/node/NodeChunkTemplatePlugin.js b/lib/node/NodeChunkTemplatePlugin.js index b3bd7aadb..1ef85e356 100644 --- a/lib/node/NodeChunkTemplatePlugin.js +++ b/lib/node/NodeChunkTemplatePlugin.js @@ -4,8 +4,7 @@ */ var ConcatSource = require("webpack-core/lib/ConcatSource"); -function NodeChunkTemplatePlugin() { -} +function NodeChunkTemplatePlugin() {} module.exports = NodeChunkTemplatePlugin; NodeChunkTemplatePlugin.prototype.apply = function(chunkTemplate) { diff --git a/lib/node/NodeEnvironmentPlugin.js b/lib/node/NodeEnvironmentPlugin.js index 4d1211e9b..b06077e37 100644 --- a/lib/node/NodeEnvironmentPlugin.js +++ b/lib/node/NodeEnvironmentPlugin.js @@ -7,8 +7,7 @@ var NodeOutputFileSystem = require("./NodeOutputFileSystem"); var NodeJsInputFileSystem = require("enhanced-resolve/lib/NodeJsInputFileSystem"); var CachedInputFileSystem = require("enhanced-resolve/lib/CachedInputFileSystem"); -function NodeEnvironmentPlugin() { -} +function NodeEnvironmentPlugin() {} module.exports = NodeEnvironmentPlugin; NodeEnvironmentPlugin.prototype.apply = function(compiler) { compiler.inputFileSystem = new NodeJsInputFileSystem(); @@ -19,7 +18,7 @@ NodeEnvironmentPlugin.prototype.apply = function(compiler) { compiler.outputFileSystem = new NodeOutputFileSystem(); compiler.watchFileSystem = new NodeWatchFileSystem(compiler.inputFileSystem); compiler.plugin("run", function(compiler, callback) { - if(compiler.inputFileSystem === inputFileSystem) + if (compiler.inputFileSystem === inputFileSystem) inputFileSystem.purge(); callback(); }); diff --git a/lib/node/NodeHotUpdateChunkTemplatePlugin.js b/lib/node/NodeHotUpdateChunkTemplatePlugin.js index 4e823d68f..2ab20f2c2 100644 --- a/lib/node/NodeHotUpdateChunkTemplatePlugin.js +++ b/lib/node/NodeHotUpdateChunkTemplatePlugin.js @@ -4,8 +4,7 @@ */ var ConcatSource = require("webpack-core/lib/ConcatSource"); -function NodeHotUpdateChunkTemplatePlugin() { -} +function NodeHotUpdateChunkTemplatePlugin() {} module.exports = NodeHotUpdateChunkTemplatePlugin; NodeHotUpdateChunkTemplatePlugin.prototype.apply = function(hotUpdateChunkTemplate) { diff --git a/lib/node/NodeMainTemplate.runtime.js b/lib/node/NodeMainTemplate.runtime.js index 172cdb280..b0f3bed2a 100644 --- a/lib/node/NodeMainTemplate.runtime.js +++ b/lib/node/NodeMainTemplate.runtime.js @@ -12,7 +12,7 @@ module.exports = function() { function hotDownloadManifest(callback) { // eslint-disable-line no-unused-vars try { var update = require("./" + $hotMainFilename$); - } catch(e) { + } catch (e) { return callback(); } callback(null, update); diff --git a/lib/node/NodeMainTemplateAsync.runtime.js b/lib/node/NodeMainTemplateAsync.runtime.js index 61ad18913..fc454cda1 100644 --- a/lib/node/NodeMainTemplateAsync.runtime.js +++ b/lib/node/NodeMainTemplateAsync.runtime.js @@ -7,8 +7,8 @@ module.exports = function() { function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars var filename = require("path").join(__dirname, $hotChunkFilename$); require("fs").readFile(filename, "utf-8", function(err, content) { - if(err) { - if($require$.onError) + if (err) { + if ($require$.onError) return $require$.onError(err); else throw err; @@ -22,10 +22,10 @@ module.exports = function() { function hotDownloadManifest(callback) { // eslint-disable-line no-unused-vars var filename = require("path").join(__dirname, $hotMainFilename$); require("fs").readFile(filename, "utf-8", function(err, content) { - if(err) return callback(); + if (err) return callback(); try { var update = JSON.parse(content); - } catch(e) { + } catch (e) { return callback(e); } callback(null, update); diff --git a/lib/node/NodeMainTemplatePlugin.js b/lib/node/NodeMainTemplatePlugin.js index 7e92261a7..042c3e5fa 100644 --- a/lib/node/NodeMainTemplatePlugin.js +++ b/lib/node/NodeMainTemplatePlugin.js @@ -11,7 +11,7 @@ module.exports = NodeMainTemplatePlugin; NodeMainTemplatePlugin.prototype.apply = function(mainTemplate) { var self = this; mainTemplate.plugin("local-vars", function(source, chunk) { - if(chunk.chunks.length > 0) { + if (chunk.chunks.length > 0) { return this.asString([ source, "", @@ -38,7 +38,7 @@ NodeMainTemplatePlugin.prototype.apply = function(mainTemplate) { this.indent(this.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")), "}" ]; - if(self.asyncChunkLoading) { + if (self.asyncChunkLoading) { return this.asString([ "if(installedChunks[chunkId] === 1) callback.call(null, " + this.requireFn + ");", "else if(!installedChunks[chunkId]) {", @@ -55,7 +55,7 @@ NodeMainTemplatePlugin.prototype.apply = function(mainTemplate) { hashWithLength: function(length) { var shortChunkHashMap = {}; Object.keys(chunkMaps.hash).forEach(function(chunkId) { - 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] + \""; @@ -99,7 +99,7 @@ NodeMainTemplatePlugin.prototype.apply = function(mainTemplate) { hashWithLength: function(length) { var shortChunkHashMap = {}; Object.keys(chunkMaps.hash).forEach(function(chunkId) { - 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] + \""; @@ -136,7 +136,7 @@ NodeMainTemplatePlugin.prototype.apply = function(mainTemplate) { hashWithLength: function(length) { var shortChunkHashMap = {}; Object.keys(chunkMaps.hash).forEach(function(chunkId) { - if(typeof chunkMaps.hash[chunkId] === "string") + if (typeof chunkMaps.hash[chunkId] === "string") shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr(0, length); }); return "\" + " + JSON.stringify(shortChunkHashMap) + "[chunkId] + \""; diff --git a/lib/node/NodeSourcePlugin.js b/lib/node/NodeSourcePlugin.js index c759ce617..2c706c388 100644 --- a/lib/node/NodeSourcePlugin.js +++ b/lib/node/NodeSourcePlugin.js @@ -12,45 +12,45 @@ function NodeSourcePlugin(options) { module.exports = NodeSourcePlugin; NodeSourcePlugin.prototype.apply = function(compiler) { function getPathToModule(module, type) { - if(type === true || (type === undefined && nodeLibsBrowser[module])) { - if(!nodeLibsBrowser[module]) throw new Error("No browser version for node.js core module '" + module + "' available"); + if (type === true || (type === undefined && 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") { + } else if (type === "mock") { return require.resolve("node-libs-browser/mock/" + module); - } else if(type === "empty") { + } else if (type === "empty") { return require.resolve("node-libs-browser/mock/empty"); } else return module; } - if(this.options.process) { + if (this.options.process) { var processType = this.options.process; compiler.parser.plugin("expression process", function() { return ModuleParserHelpers.addParsedVariable(this, "process", "require(" + JSON.stringify(getPathToModule("process", processType)) + ")"); }); } - if(this.options.global) { + if (this.options.global) { compiler.parser.plugin("expression global", function() { this.state.module.addVariable("global", "(function() { return this; }())"); return true; }); } - if(this.options.console) { + if (this.options.console) { var consoleType = this.options.console; compiler.parser.plugin("expression console", function() { return ModuleParserHelpers.addParsedVariable(this, "console", "require(" + JSON.stringify(getPathToModule("console", consoleType)) + ")"); }); } var bufferType = this.options.Buffer; - if(typeof bufferType === "undefined") { + if (typeof bufferType === "undefined") { bufferType = this.options.buffer; - if(typeof bufferType === "undefined") + if (typeof bufferType === "undefined") bufferType = true; } - if(bufferType) { + if (bufferType) { compiler.parser.plugin("expression Buffer", function() { return ModuleParserHelpers.addParsedVariable(this, "Buffer", "require(" + JSON.stringify(getPathToModule("buffer", bufferType)) + ").Buffer"); }); } - if(this.options.setImmediate) { + if (this.options.setImmediate) { var setImmediateType = this.options.setImmediate; compiler.parser.plugin("expression setImmediate", function() { return ModuleParserHelpers.addParsedVariable(this, "setImmediate", "require(" + JSON.stringify(getPathToModule("timers", setImmediateType)) + ").setImmediate"); @@ -63,10 +63,10 @@ NodeSourcePlugin.prototype.apply = function(compiler) { compiler.plugin("after-resolvers", function(compiler) { var alias = {}; Object.keys(nodeLibsBrowser).forEach(function(lib) { - if(options[lib] !== false) + if (options[lib] !== false) alias[lib + "$"] = getPathToModule(lib, options[lib]); }); - if(Object.keys(alias).length > 0) { + if (Object.keys(alias).length > 0) { compiler.resolvers.normal.apply( new ModuleAliasPlugin(alias) ); diff --git a/lib/node/NodeTargetPlugin.js b/lib/node/NodeTargetPlugin.js index aad887b7f..ef4ebdcca 100644 --- a/lib/node/NodeTargetPlugin.js +++ b/lib/node/NodeTargetPlugin.js @@ -4,8 +4,7 @@ */ var ExternalsPlugin = require("../ExternalsPlugin"); -function NodeTargetPlugin() { -} +function NodeTargetPlugin() {} module.exports = NodeTargetPlugin; NodeTargetPlugin.prototype.apply = function(compiler) { diff --git a/lib/node/NodeWatchFileSystem.js b/lib/node/NodeWatchFileSystem.js index 832fda6bc..2f732e100 100644 --- a/lib/node/NodeWatchFileSystem.js +++ b/lib/node/NodeWatchFileSystem.js @@ -15,28 +15,28 @@ function NodeWatchFileSystem(inputFileSystem) { module.exports = NodeWatchFileSystem; NodeWatchFileSystem.prototype.watch = function watch(files, dirs, missing, startTime, options, callback, callbackUndelayed) { - if(!Array.isArray(files)) + if (!Array.isArray(files)) throw new Error("Invalid arguments: 'files'"); - if(!Array.isArray(dirs)) + if (!Array.isArray(dirs)) throw new Error("Invalid arguments: 'dirs'"); - if(!Array.isArray(missing)) + 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'"); var oldWatcher = this.watcher; this.watcher = new Watchpack(options); - if(callbackUndelayed) + if (callbackUndelayed) this.watcher.once("change", callbackUndelayed); this.watcher.once("aggregated", function(changes) { - if(this.inputFileSystem && this.inputFileSystem.purge) { + if (this.inputFileSystem && this.inputFileSystem.purge) { this.inputFileSystem.purge(changes); } var times = this.watcher.getTimes(); @@ -51,7 +51,7 @@ NodeWatchFileSystem.prototype.watch = function watch(files, dirs, missing, start this.watcher.watch(files.concat(missing), dirs, startTime); - if(oldWatcher) { + if (oldWatcher) { oldWatcher.close(); } return { diff --git a/lib/node/OldNodeWatchFileSystem.js b/lib/node/OldNodeWatchFileSystem.js index 731287a24..9e31618c6 100644 --- a/lib/node/OldNodeWatchFileSystem.js +++ b/lib/node/OldNodeWatchFileSystem.js @@ -23,7 +23,7 @@ module.exports = OldNodeWatchFileSystem; OldNodeWatchFileSystem.prototype.watch = function(files, dirs, missing, startTime, delay, callback, callbackUndelayed) { var inputFileSystem = this.inputFileSystem; - if(!callbackUndelayed) callbackUndelayed = function() {}; + if (!callbackUndelayed) callbackUndelayed = function() {}; var closed = false; var fileTimestamps = {}; var dirTimestamps = {}; @@ -43,7 +43,7 @@ OldNodeWatchFileSystem.prototype.watch = function(files, dirs, missing, startTim }); files.forEach(function(file) { var dir = path.dirname(file); - if(!directories[dir]) directories[dir] = { + if (!directories[dir]) directories[dir] = { files: [] }; directories[dir].files.push(file); @@ -54,11 +54,11 @@ OldNodeWatchFileSystem.prototype.watch = function(files, dirs, missing, startTim return directories[dir]; }); items.sort(function(a, b) { - if(a.path === b.path) return 0; + if (a.path === b.path) return 0; return a.path < b.path ? -1 : 1; }); items.forEach(function(item) { - if(item.files) { + if (item.files) { item.files.sort(); } }); @@ -69,41 +69,41 @@ OldNodeWatchFileSystem.prototype.watch = function(files, dirs, missing, startTim }; function readStat(item, callback) { - if(item.context) { + if (item.context) { fs.readdir(item.path, function(err, files) { function onTimestamp(ts) { - if(!dirTimestamps[item.context] || dirTimestamps[item.context] < ts) + if (!dirTimestamps[item.context] || dirTimestamps[item.context] < ts) dirTimestamps[item.context] = ts; - if(ts >= startTime) { + if (ts >= startTime) { dirsModified[item.context] = true; change(item.path); } return callback(); } - if(err) return onTimestamp(Infinity); + if (err) return onTimestamp(Infinity); async.map(files, function(file, callback) { file = path.join(item.path, file); var isFile = false; - if(item.files) { - if(binarySearch(item.files, function(path) { - if(path === file) return 0; - return path < file ? -1 : 1; - }) >= 0) { + if (item.files) { + if (binarySearch(item.files, function(path) { + if (path === file) return 0; + return path < file ? -1 : 1; + }) >= 0) { isFile = true; } } fs.stat(file, function(err, stat) { var ts = err ? Infinity : stat.mtime.getTime(); - if(isFile) { + if (isFile) { fileTimestamps[file] = ts; - if(ts >= startTime) filesModified[file] = true; + if (ts >= startTime) filesModified[file] = true; } return callback(null, ts); }); }, function(err, timestamps) { - if(err) return onTimestamp(Infinity); + if (err) return onTimestamp(Infinity); var ts = timestamps.reduce(function(max, ts) { - if(ts > max) + if (ts > max) return ts; return max; }, 0); @@ -115,7 +115,7 @@ OldNodeWatchFileSystem.prototype.watch = function(files, dirs, missing, startTim fs.stat(file, function(err, stat) { var ts = err ? Infinity : stat.mtime.getTime(); fileTimestamps[file] = ts; - if(ts >= startTime) { + if (ts >= startTime) { filesModified[file] = true; change(file); } @@ -128,17 +128,17 @@ OldNodeWatchFileSystem.prototype.watch = function(files, dirs, missing, startTim var isRunning = false; var isScheduled = false; item.watcher = fs.watch(item.path, function() { - if(isRunning) { + if (isRunning) { isScheduled = true; return; } isRunning = true; readStat(item, done); }); - if(item.context) { + if (item.context) { item.children = []; fs.readdir(item.path, function(err, files) { - if(err) { + if (err) { change(); onWatcherApplied(); return; @@ -146,12 +146,12 @@ OldNodeWatchFileSystem.prototype.watch = function(files, dirs, missing, startTim async.forEach(files, function(file, callback) { file = path.join(item.path, file); fs.stat(file, function(err, stat) { - if(err) { + if (err) { change(file); callback(); return; } - if(!stat.isDirectory()) return callback(); + if (!stat.isDirectory()) return callback(); var subitem = { path: file, context: item.context @@ -162,15 +162,17 @@ OldNodeWatchFileSystem.prototype.watch = function(files, dirs, missing, startTim }, onWatcherApplied); }); } else onWatcherApplied(); + function onWatcherApplied() { readStat(item, function() { callback(); done(); }); } + function done() { - if(closed) return; - if(isScheduled) { + if (closed) return; + if (isScheduled) { isScheduled = false; readStat(item, done); } else { @@ -179,10 +181,10 @@ OldNodeWatchFileSystem.prototype.watch = function(files, dirs, missing, startTim } }, function() { var timeout; - if(initialChange) { + if (initialChange) { callbackUndelayed(); - if(delay) { + if (delay) { lastChangeTime = Date.now(); change = restartDelay; timeout = setTimeout(onTimeout, delay); @@ -193,7 +195,7 @@ OldNodeWatchFileSystem.prototype.watch = function(files, dirs, missing, startTim change = function() { callbackUndelayed(); - if(delay) { + if (delay) { lastChangeTime = Date.now(); change = restartDelay; timeout = setTimeout(onTimeout, delay); @@ -217,15 +219,15 @@ OldNodeWatchFileSystem.prototype.watch = function(files, dirs, missing, startTim function onTimeout() { var nextSecond = Math.ceil(lastChangeTime / 1000) * 1000; var timeToNextSecond = nextSecond - Date.now(); - if(timeToNextSecond > 0) { + if (timeToNextSecond > 0) { setTimeout(onTimeout, timeToNextSecond); return; } change = function() {}; - if(closed) return; + if (closed) return; var outdatedFiles = Object.keys(filesModified).sort(); var outdatedDirs = Object.keys(dirsModified).sort(); - if(inputFileSystem && inputFileSystem.purge) { + if (inputFileSystem && inputFileSystem.purge) { inputFileSystem.purge(outdatedFiles); inputFileSystem.purge(outdatedDirs); } @@ -238,7 +240,7 @@ OldNodeWatchFileSystem.prototype.watch = function(files, dirs, missing, startTim closed = true; items.forEach(function closeItem(item) { item.watcher.close(); - if(item.children) item.children.forEach(closeItem); + if (item.children) item.children.forEach(closeItem); }); } @@ -252,12 +254,12 @@ function binarySearch(array, comparator) { var left = 0; var right = array.length - 1; - while(left <= right) { + while (left <= right) { var middle = ((left + right) / 2) | 0; var comp = comparator(array[middle]); - if(comp === 0) return middle; - if(comp > 0) right = middle - 1; - if(comp < 0) left = middle + 1; + if (comp === 0) return middle; + if (comp > 0) right = middle - 1; + if (comp < 0) left = middle + 1; } return -1; } diff --git a/lib/optimize/AggressiveMergingPlugin.js b/lib/optimize/AggressiveMergingPlugin.js index de2a7ffb1..831b7115e 100644 --- a/lib/optimize/AggressiveMergingPlugin.js +++ b/lib/optimize/AggressiveMergingPlugin.js @@ -3,7 +3,7 @@ Author Tobias Koppers @sokra */ function AggressiveMergingPlugin(options) { - if(options !== undefined && typeof options !== "object" || Array.isArray(options)) { + if (options !== undefined && typeof options !== "object" || Array.isArray(options)) { throw new Error("Argument should be an options object. To use defaults, pass in nothing.\nFor more info on options, see http://webpack.github.io/docs/list-of-plugins.html"); } this.options = options || {}; @@ -13,6 +13,7 @@ module.exports = AggressiveMergingPlugin; AggressiveMergingPlugin.prototype.apply = function(compiler) { var options = this.options; var minSizeReduce = options.minSizeReduce || 1.5; + function getParentsWeight(chunk) { return chunk.parents.map(function(p) { return p.initial ? options.entryChunkMultiplicator || 10 : 1; @@ -24,27 +25,42 @@ AggressiveMergingPlugin.prototype.apply = function(compiler) { compilation.plugin("optimize-chunks", function(chunks) { var combinations = []; chunks.forEach(function(a, idx) { - if(a.initial) return; - for(var i = 0; i < idx; i++) { + if (a.initial) return; + for (var i = 0; i < idx; i++) { var b = chunks[i]; - if(b.initial) continue; + if (b.initial) continue; combinations.push([b, a]); } }); combinations.forEach(function(pair) { - var a = pair[0].size({chunkOverhead: 0}); - var b = pair[1].size({chunkOverhead: 0}); - var ab = pair[0].integratedSize(pair[1], {chunkOverhead: 0}); - pair.push({ a: a, b: b, ab: ab }); - if(ab === false) { + var a = pair[0].size({ + chunkOverhead: 0 + }); + var b = pair[1].size({ + chunkOverhead: 0 + }); + var ab = pair[0].integratedSize(pair[1], { + chunkOverhead: 0 + }); + pair.push({ + a: a, + b: b, + ab: ab + }); + if (ab === false) { pair.unshift(false); - } else if(options.moveToParents) { + } else if (options.moveToParents) { var aOnly = ab - b; var bOnly = ab - a; var common = a + b - ab; var newSize = common + getParentsWeight(pair[0]) * aOnly + getParentsWeight(pair[1]) * bOnly; - pair.push({ aOnly: aOnly, bOnly: bOnly, common: common, newSize: newSize }); + pair.push({ + aOnly: aOnly, + bOnly: bOnly, + common: common, + newSize: newSize + }); } else { var newSize = ab; } @@ -60,10 +76,10 @@ AggressiveMergingPlugin.prototype.apply = function(compiler) { var pair = combinations[0]; - if(!pair) return; - if(pair[0] < minSizeReduce) return; + if (!pair) return; + if (pair[0] < minSizeReduce) return; - if(options.moveToParents) { + if (options.moveToParents) { var commonModules = pair[1].modules.filter(function(m) { return pair[2].modules.indexOf(m) >= 0; }); @@ -90,11 +106,10 @@ AggressiveMergingPlugin.prototype.apply = function(compiler) { }); }); } - if(pair[1].integrate(pair[2], "aggressive-merge")) { + if (pair[1].integrate(pair[2], "aggressive-merge")) { chunks.splice(chunks.indexOf(pair[2]), 1); this.restartApplyPlugins(); } }); }); }; - diff --git a/lib/optimize/CommonsChunkPlugin.js b/lib/optimize/CommonsChunkPlugin.js index 154264999..50a19fd8b 100644 --- a/lib/optimize/CommonsChunkPlugin.js +++ b/lib/optimize/CommonsChunkPlugin.js @@ -3,22 +3,22 @@ Author Tobias Koppers @sokra */ function CommonsChunkPlugin(options, filenameTemplate, selectedChunks, minChunks) { - if(options && typeof options === "object" && !Array.isArray(options)) { + if (options && typeof options === "object" && !Array.isArray(options)) { this.chunkNames = options.name || options.names; this.filenameTemplate = options.filename; this.minChunks = options.minChunks; this.selectedChunks = options.chunks; - if(options.children) this.selectedChunks = false; + if (options.children) this.selectedChunks = false; this.async = options.async; this.minSize = options.minSize; } else { var chunkNames = options; - if(typeof filenameTemplate !== "string" && filenameTemplate !== null) { + if (typeof filenameTemplate !== "string" && filenameTemplate !== null) { minChunks = selectedChunks; selectedChunks = filenameTemplate; filenameTemplate = chunkNames; } - if(!Array.isArray(selectedChunks) && typeof selectedChunks !== "boolean" && selectedChunks !== null) { + if (!Array.isArray(selectedChunks) && typeof selectedChunks !== "boolean" && selectedChunks !== null) { minChunks = selectedChunks; selectedChunks = undefined; } @@ -39,9 +39,9 @@ CommonsChunkPlugin.prototype.apply = function(compiler) { compiler.plugin("this-compilation", function(compilation) { compilation.plugin(["optimize-chunks", "optimize-extracted-chunks"], function(chunks) { var commonChunks; - if(!chunkNames && (selectedChunks === false || async)) { + if (!chunkNames && (selectedChunks === false || async)) { commonChunks = chunks; - } else if(Array.isArray(chunkNames)) { + } else if (Array.isArray(chunkNames)) { commonChunks = chunkNames.map(function(chunkName) { return chunks.filter(function(chunk) { return chunk.name === chunkName; @@ -52,7 +52,7 @@ CommonsChunkPlugin.prototype.apply = function(compiler) { return chunk.name === chunkNames; }); } - if(commonChunks.length === 0) { + if (commonChunks.length === 0) { var chunk = this.addChunk(chunkNames); chunk.initial = chunk.entry = true; commonChunks = [chunk]; @@ -61,28 +61,28 @@ CommonsChunkPlugin.prototype.apply = function(compiler) { var commonModulesCount = []; var commonModules = []; var usedChunks; - if(Array.isArray(selectedChunks)) { + if (Array.isArray(selectedChunks)) { usedChunks = chunks.filter(function(chunk) { - if(chunk === commonChunk) return false; + if (chunk === commonChunk) return false; return selectedChunks.indexOf(chunk.name) >= 0; }); - } else if(selectedChunks === false || async) { + } else if (selectedChunks === false || async) { usedChunks = (commonChunk.chunks || []).filter(function(chunk) { // we can only move modules from this chunk if the "commonChunk" is the only parent return async || chunk.parents.length === 1; }); } else { - if(!commonChunk.entry) { + if (!commonChunk.entry) { compilation.errors.push(new Error("CommonsChunkPlugin: While running in normal mode it's not allowed to use a non-entry chunk (" + commonChunk.name + ")")); return; } usedChunks = chunks.filter(function(chunk) { var found = commonChunks.indexOf(chunk); - if(found >= idx) return false; + if (found >= idx) return false; return chunk.entry; }); } - if(async) { + if (async) { var asyncChunk = this.addChunk(typeof async === "string" ? async : undefined); asyncChunk.chunkReason = "async commons chunk"; asyncChunk.extraAsync = true; @@ -93,7 +93,7 @@ CommonsChunkPlugin.prototype.apply = function(compiler) { usedChunks.forEach(function(chunk) { chunk.modules.forEach(function(module) { var idx = commonModules.indexOf(module); - if(idx < 0) { + if (idx < 0) { commonModules.push(module); commonModulesCount.push(1); } else { @@ -105,34 +105,34 @@ CommonsChunkPlugin.prototype.apply = function(compiler) { var reallyUsedModules = []; commonModulesCount.forEach(function(count, idx) { var module = commonModules[idx]; - if(typeof minChunks === "function") { - if(!minChunks(module, count)) + if (typeof minChunks === "function") { + if (!minChunks(module, count)) return; - } else if(count < (minChunks || Math.max(2, usedChunks.length))) { + } else if (count < (minChunks || Math.max(2, usedChunks.length))) { return; } reallyUsedModules.push(module); }); - if(minSize) { + if (minSize) { var size = reallyUsedModules.reduce(function(a, b) { return a + b.size(); }, 0); - if(size < minSize) + if (size < minSize) return; } reallyUsedModules.forEach(function(module) { usedChunks.forEach(function(chunk) { - if(module.removeChunk(chunk)) { - if(reallyUsedChunks.indexOf(chunk) < 0) + if (module.removeChunk(chunk)) { + if (reallyUsedChunks.indexOf(chunk) < 0) reallyUsedChunks.push(chunk); } }); commonChunk.addModule(module); module.addChunk(commonChunk); }); - if(async) { + if (async) { reallyUsedChunks.forEach(function(chunk) { - if(chunk.initial || chunk.entry) + if (chunk.initial || chunk.entry) return; chunk.blocks.forEach(function(block) { block.chunks.unshift(commonChunk); @@ -146,20 +146,23 @@ CommonsChunkPlugin.prototype.apply = function(compiler) { newOrigin.reasons.push("async commons"); return newOrigin; }); - }).reduce(function(arr, a) { arr.push.apply(arr, a); return arr; }, []); + }).reduce(function(arr, a) { + arr.push.apply(arr, a); + return arr; + }, []); } else { usedChunks.forEach(function(chunk) { chunk.parents = [commonChunk]; commonChunk.chunks.push(chunk); - if(chunk.initial) + if (chunk.initial) commonChunk.initial = true; - if(chunk.entry) { + if (chunk.entry) { commonChunk.entry = true; chunk.entry = false; } }); } - if(filenameTemplate) + if (filenameTemplate) commonChunk.filenameTemplate = filenameTemplate; }, this); }); diff --git a/lib/optimize/DedupePlugin.js b/lib/optimize/DedupePlugin.js index e1f3259b4..2e0460c83 100644 --- a/lib/optimize/DedupePlugin.js +++ b/lib/optimize/DedupePlugin.js @@ -5,8 +5,7 @@ var ConcatSource = require("webpack-core/lib/ConcatSource"); var TemplateArgumentDependency = require("../dependencies/TemplateArgumentDependency"); -function DedupePlugin() { -} +function DedupePlugin() {} module.exports = DedupePlugin; DedupePlugin.prototype.apply = function(compiler) { @@ -18,11 +17,11 @@ DedupePlugin.prototype.apply = function(compiler) { var modulesByHash = {}; var allDups = []; modules.forEach(function(module) { - if(!module.getSourceHash || !module.getAllModuleDependencies || !module.createTemplate || !module.getTemplateArguments || module.blocks.length > 0) return; + if (!module.getSourceHash || !module.getAllModuleDependencies || !module.createTemplate || !module.getTemplateArguments || module.blocks.length > 0) return; var hash = module.getSourceHash(); var dupModule = modulesByHash[hash]; - if(dupModule) { - if(dupModule.duplicates) { + if (dupModule) { + if (dupModule.duplicates) { dupModule.duplicates.push(module); module.duplicates = dupModule.duplicates; } else { @@ -32,20 +31,22 @@ DedupePlugin.prototype.apply = function(compiler) { modulesByHash[hash] = module; } }); - var entryChunks = chunks.filter(function(c) { return c.entry; }); + var entryChunks = chunks.filter(function(c) { + return c.entry; + }); entryChunks.forEach(function(chunk) { // for each entry chunk var hasDeduplicatedModules = false; (function x(dups, roots, visited, chunk) { var currentDups = []; var currentRoots = []; chunk.modules.forEach(function(module) { - if(module.duplicates) { - if(!module.rootDuplicatesChunks) + if (module.duplicates) { + if (!module.rootDuplicatesChunks) module.rootDuplicatesChunks = module.chunks.slice(); var chunkIndex = module.rootDuplicatesChunks.indexOf(chunk); - if(!module.rootDuplicates) module.rootDuplicates = []; + if (!module.rootDuplicates) module.rootDuplicates = []; var idx = currentDups.indexOf(module.duplicates); - if(idx >= 0) { + if (idx >= 0) { module.rootDuplicates[chunkIndex] = currentRoots[idx]; module.rootDuplicates[chunkIndex].push(module); module.rootDuplicates[chunkIndex].commonModules = @@ -53,7 +54,7 @@ DedupePlugin.prototype.apply = function(compiler) { hasDeduplicatedModules = true; } else { idx = dups.indexOf(module.duplicates); - if(idx < 0) { + if (idx < 0) { module.rootDuplicates[chunkIndex] = [module]; module.rootDuplicates[chunkIndex].commonModules = module.getAllModuleDependencies(); module.rootDuplicates[chunkIndex].initialCommonModulesLength = module.rootDuplicates[chunkIndex].commonModules.length; @@ -71,14 +72,14 @@ DedupePlugin.prototype.apply = function(compiler) { } }); chunk.chunks.forEach(function(chunk) { - if(visited.indexOf(chunk) < 0) + if (visited.indexOf(chunk) < 0) x(dups, roots, visited.concat(chunk), chunk); }); currentRoots.forEach(function(roots) { var commonModules = roots.commonModules; var initialLength = roots.initialCommonModulesLength; - if(initialLength !== commonModules.length) { + if (initialLength !== commonModules.length) { var template = roots[0].createTemplate(commonModules, roots.slice()); roots.template = template; chunk.addModule(template); @@ -88,10 +89,11 @@ DedupePlugin.prototype.apply = function(compiler) { } }); }([], [], [], chunk)); - if(hasDeduplicatedModules) + if (hasDeduplicatedModules) chunk.__DedupePluginHasDeduplicatedModules = true; }); }); + function mergeCommonModules(commonModules, newModules) { return commonModules.filter(function(module) { return newModules.indexOf(module) >= 0; @@ -99,22 +101,22 @@ DedupePlugin.prototype.apply = function(compiler) { } compilation.moduleTemplate.plugin("package", function(moduleSource, module, chunk) { - if(!module.rootDuplicatesChunks || !chunk) return moduleSource; + if (!module.rootDuplicatesChunks || !chunk) return moduleSource; var chunkIndex = module.rootDuplicatesChunks.indexOf(chunk); - if(!module.rootDuplicates || !module.rootDuplicates[chunkIndex]) return moduleSource; + if (!module.rootDuplicates || !module.rootDuplicates[chunkIndex]) return moduleSource; var rootDuplicates = module.rootDuplicates[chunkIndex]; - if(rootDuplicates.template) { + if (rootDuplicates.template) { rootDuplicates.template.addReason(module, { type: "template", request: module.request, templateModules: rootDuplicates.template.templateModules }); rootDuplicates.template.reasons.sort(function(a, b) { - if(a.request === b.request) return 0; + if (a.request === b.request) return 0; return a.request < b.request ? -1 : 1; }); var array = [JSON.stringify(rootDuplicates.template.id)].concat(module.getTemplateArguments(rootDuplicates.template.templateModules).map(function(module) { - if(module.id === null || module.id === undefined) + if (module.id === null || module.id === undefined) return "(function webpackMissingModule() { throw new Error(" + JSON.stringify("Cannot find module") + "); }())"; return JSON.stringify(module.id); })); @@ -124,19 +126,19 @@ DedupePlugin.prototype.apply = function(compiler) { rootDuplicates.sort(function(a, b) { return a.id - b.id; }); - if(module === rootDuplicates[0]) return moduleSource; + if (module === rootDuplicates[0]) return moduleSource; var source = new ConcatSource("" + JSON.stringify(rootDuplicates[0].id)); return source; } }); compilation.plugin("chunk-hash", function(chunk, hash) { - if(chunk.__DedupePluginHasDeduplicatedModules) + if (chunk.__DedupePluginHasDeduplicatedModules) hash.update("DedupePlugin (deduplication code)"); }); compilation.mainTemplate.plugin("add-module", function(source, chunk, hash, varModuleId, varModule) { // we don't need to test all nested chunks, because `__DedupePluginHasDeduplicatedModules` // is not set on entry chunks - if(!chunk.__DedupePluginHasDeduplicatedModules) { + if (!chunk.__DedupePluginHasDeduplicatedModules) { return source; } return this.asString([ @@ -175,7 +177,7 @@ DedupePlugin.prototype.apply = function(compiler) { ]); }); compilation.mainTemplate.plugin("modules", function(orginalSource, chunk) { - if(!chunk.__DedupePluginHasDeduplicatedModules) { + if (!chunk.__DedupePluginHasDeduplicatedModules) { return orginalSource; } var source = new ConcatSource(); diff --git a/lib/optimize/FlagIncludedChunksPlugin.js b/lib/optimize/FlagIncludedChunksPlugin.js index ee7333847..829ec7c3e 100644 --- a/lib/optimize/FlagIncludedChunksPlugin.js +++ b/lib/optimize/FlagIncludedChunksPlugin.js @@ -2,8 +2,7 @@ MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ -function FlagIncludedChunksPlugin() { -} +function FlagIncludedChunksPlugin() {} module.exports = FlagIncludedChunksPlugin; FlagIncludedChunksPlugin.prototype.apply = function(compiler) { @@ -11,11 +10,11 @@ FlagIncludedChunksPlugin.prototype.apply = function(compiler) { compilation.plugin("optimize-chunk-ids", function(chunks) { chunks.forEach(function(chunkA) { chunks.forEach(function(chunkB) { - if(chunkA === chunkB) return; + if (chunkA === chunkB) return; // is chunkB in chunkA? - if(chunkA.modules.length < chunkB.modules.length) return; - for(var i = 0; i < chunkB.modules.length; i++) { - if(chunkA.modules.indexOf(chunkB.modules[i]) < 0) return; + if (chunkA.modules.length < chunkB.modules.length) return; + for (var i = 0; i < chunkB.modules.length; i++) { + if (chunkA.modules.indexOf(chunkB.modules[i]) < 0) return; } chunkA.ids.push(chunkB.id); }); @@ -23,4 +22,3 @@ FlagIncludedChunksPlugin.prototype.apply = function(compiler) { }); }); }; - diff --git a/lib/optimize/LimitChunkCountPlugin.js b/lib/optimize/LimitChunkCountPlugin.js index e6265c04d..cc4213d96 100644 --- a/lib/optimize/LimitChunkCountPlugin.js +++ b/lib/optimize/LimitChunkCountPlugin.js @@ -3,7 +3,7 @@ Author Tobias Koppers @sokra */ function LimitChunkCountPlugin(options) { - if(options !== undefined && typeof options !== "object" || Array.isArray(options)) { + if (options !== undefined && typeof options !== "object" || Array.isArray(options)) { throw new Error("Argument should be an options object.\nFor more info on options, see http://webpack.github.io/docs/list-of-plugins.html"); } this.options = options || {}; @@ -15,14 +15,14 @@ LimitChunkCountPlugin.prototype.apply = function(compiler) { compiler.plugin("compilation", function(compilation) { compilation.plugin("optimize-chunks", function(chunks) { var maxChunks = options.maxChunks; - if(!maxChunks) return; - if(maxChunks < 1) return; - if(chunks.length <= maxChunks) return; + if (!maxChunks) return; + if (maxChunks < 1) return; + if (chunks.length <= maxChunks) return; - if(chunks.length > maxChunks) { + if (chunks.length > maxChunks) { var combinations = []; chunks.forEach(function(a, idx) { - for(var i = 0; i < idx; i++) { + for (var i = 0; i < idx; i++) { var b = chunks[i]; combinations.push([b, a]); } @@ -39,13 +39,13 @@ LimitChunkCountPlugin.prototype.apply = function(compiler) { }); combinations.sort(function(a, b) { var diff = b[0] - a[0]; - if(diff !== 0) return diff; + if (diff !== 0) return diff; return a[1] - b[1]; }); var pair = combinations[0]; - if(pair && pair[2].integrate(pair[3], "limit")) { + if (pair && pair[2].integrate(pair[3], "limit")) { chunks.splice(chunks.indexOf(pair[3]), 1); this.restartApplyPlugins(); } @@ -53,4 +53,3 @@ LimitChunkCountPlugin.prototype.apply = function(compiler) { }); }); }; - diff --git a/lib/optimize/MergeDuplicateChunksPlugin.js b/lib/optimize/MergeDuplicateChunksPlugin.js index b4917c919..b15b40ea2 100644 --- a/lib/optimize/MergeDuplicateChunksPlugin.js +++ b/lib/optimize/MergeDuplicateChunksPlugin.js @@ -2,8 +2,7 @@ MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ -function MergeDuplicateChunksPlugin() { -} +function MergeDuplicateChunksPlugin() {} module.exports = MergeDuplicateChunksPlugin; function getChunkIdentifier(chunk) { @@ -17,10 +16,10 @@ MergeDuplicateChunksPlugin.prototype.apply = function(compiler) { compilation.plugin("optimize-chunks", function(chunks) { var map = {}; chunks.slice().forEach(function(chunk) { - if(chunk.initial) return; + if (chunk.initial) return; var ident = getChunkIdentifier(chunk); - if(map[ident]) { - if(map[ident].integrate(chunk, "duplicate")) + if (map[ident]) { + if (map[ident].integrate(chunk, "duplicate")) chunks.splice(chunks.indexOf(chunk), 1); return; } @@ -29,4 +28,3 @@ MergeDuplicateChunksPlugin.prototype.apply = function(compiler) { }); }); }; - diff --git a/lib/optimize/MinChunkSizePlugin.js b/lib/optimize/MinChunkSizePlugin.js index b10bebd10..51c1f874c 100644 --- a/lib/optimize/MinChunkSizePlugin.js +++ b/lib/optimize/MinChunkSizePlugin.js @@ -3,7 +3,7 @@ Author Tobias Koppers @sokra */ function MinChunkSizePlugin(options) { - if(typeof options !== "object" || Array.isArray(options)) { + if (typeof options !== "object" || Array.isArray(options)) { throw new Error("Argument should be an options object.\nFor more info on options, see http://webpack.github.io/docs/list-of-plugins.html"); } this.options = options; @@ -18,7 +18,7 @@ MinChunkSizePlugin.prototype.apply = function(compiler) { var combinations = []; chunks.forEach(function(a, idx) { - for(var i = 0; i < idx; i++) { + for (var i = 0; i < idx; i++) { var b = chunks[i]; combinations.push([b, a]); } @@ -43,11 +43,11 @@ MinChunkSizePlugin.prototype.apply = function(compiler) { return pair[1] !== false; }); - if(combinations.length === 0) return; + if (combinations.length === 0) return; combinations.sort(function(a, b) { var diff = b[0] - a[0]; - if(diff !== 0) return diff; + if (diff !== 0) return diff; return a[1] - b[1]; }); @@ -59,4 +59,3 @@ MinChunkSizePlugin.prototype.apply = function(compiler) { }); }); }; - diff --git a/lib/optimize/OccurenceOrderPlugin.js b/lib/optimize/OccurenceOrderPlugin.js index 12bd22d1d..dca730d14 100644 --- a/lib/optimize/OccurenceOrderPlugin.js +++ b/lib/optimize/OccurenceOrderPlugin.js @@ -3,4 +3,3 @@ Author Tobias Koppers @sokra */ module.exports = require("./OccurrenceOrderPlugin"); - diff --git a/lib/optimize/OccurrenceOrderPlugin.js b/lib/optimize/OccurrenceOrderPlugin.js index d5e601b72..eedebb2f3 100644 --- a/lib/optimize/OccurrenceOrderPlugin.js +++ b/lib/optimize/OccurrenceOrderPlugin.js @@ -3,7 +3,7 @@ Author Tobias Koppers @sokra */ function OccurrenceOrderPlugin(preferEntry) { - if(preferEntry !== undefined && typeof preferEntry !== "boolean") { + if (preferEntry !== undefined && typeof preferEntry !== "boolean") { throw new Error("Argument should be a boolean.\nFor more info on this plugin, see http://webpack.github.io/docs/list-of-plugins.html"); } this.preferEntry = preferEntry; @@ -18,31 +18,37 @@ OccurrenceOrderPlugin.prototype.apply = function(compiler) { return c.initial; }).length; } + function occursInEntry(m) { return m.reasons.map(function(r) { - if(!r.module) return 0; + if (!r.module) return 0; return entryChunks(r.module); - }).reduce(function(a, b) { return a + b; }, 0) + entryChunks(m); + }).reduce(function(a, b) { + return a + b; + }, 0) + entryChunks(m); } + function occurs(m) { return m.reasons.map(function(r) { - if(!r.module) return 0; + if (!r.module) return 0; return r.module.chunks.length; - }).reduce(function(a, b) { return a + b; }, 0) + m.chunks.length; + }).reduce(function(a, b) { + return a + b; + }, 0) + m.chunks.length; } modules.sort(function(a, b) { - if(preferEntry) { + if (preferEntry) { var aEntryOccurs = occursInEntry(a); var bEntryOccurs = occursInEntry(b); - if(aEntryOccurs > bEntryOccurs) return -1; - if(aEntryOccurs < bEntryOccurs) return 1; + if (aEntryOccurs > bEntryOccurs) return -1; + if (aEntryOccurs < bEntryOccurs) return 1; } var aOccurs = occurs(a); var bOccurs = occurs(b); - if(aOccurs > bOccurs) return -1; - if(aOccurs < bOccurs) return 1; - if(a.identifier() > b.identifier()) return 1; - if(a.identifier() < b.identifier()) return -1; + if (aOccurs > bOccurs) return -1; + if (aOccurs < bOccurs) return 1; + if (a.identifier() > b.identifier()) return 1; + if (a.identifier() < b.identifier()) return -1; return 0; }); }); @@ -52,30 +58,31 @@ OccurrenceOrderPlugin.prototype.apply = function(compiler) { return p.initial; }).length + (c.entry ? 1 : 0); } + function occurs(c) { return c.blocks.length + (c.entry ? 1 : 0); } chunks.forEach(function(c) { c.modules.sort(function(a, b) { - if(a.identifier() > b.identifier()) return 1; - if(a.identifier() < b.identifier()) return -1; + if (a.identifier() > b.identifier()) return 1; + if (a.identifier() < b.identifier()) return -1; return 0; }); }); chunks.sort(function(a, b) { var aEntryOccurs = occursInEntry(a); var bEntryOccurs = occursInEntry(b); - if(aEntryOccurs > bEntryOccurs) return -1; - if(aEntryOccurs < bEntryOccurs) return 1; + if (aEntryOccurs > bEntryOccurs) return -1; + if (aEntryOccurs < bEntryOccurs) return 1; var aOccurs = occurs(a); var bOccurs = occurs(b); - if(aOccurs > bOccurs) return -1; - if(aOccurs < bOccurs) return 1; - if(a.modules.length > b.modules.length) return -1; - if(a.modules.length < b.modules.length) return 1; - for(var i = 0; i < a.modules.length; i++) { - if(a.modules[i].identifier() > b.modules[i].identifier()) return -1; - if(a.modules[i].identifier() < b.modules[i].identifier()) return 1; + if (aOccurs > bOccurs) return -1; + if (aOccurs < bOccurs) return 1; + if (a.modules.length > b.modules.length) return -1; + if (a.modules.length < b.modules.length) return 1; + for (var i = 0; i < a.modules.length; i++) { + if (a.modules[i].identifier() > b.modules[i].identifier()) return -1; + if (a.modules[i].identifier() < b.modules[i].identifier()) return 1; } return 0; }); diff --git a/lib/optimize/RemoveEmptyChunksPlugin.js b/lib/optimize/RemoveEmptyChunksPlugin.js index 460e6a2f2..d56eb6765 100644 --- a/lib/optimize/RemoveEmptyChunksPlugin.js +++ b/lib/optimize/RemoveEmptyChunksPlugin.js @@ -2,8 +2,7 @@ MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ -function RemoveEmptyChunksPlugin() { -} +function RemoveEmptyChunksPlugin() {} module.exports = RemoveEmptyChunksPlugin; RemoveEmptyChunksPlugin.prototype.apply = function(compiler) { @@ -18,4 +17,3 @@ RemoveEmptyChunksPlugin.prototype.apply = function(compiler) { }); }); }; - diff --git a/lib/optimize/RemoveParentModulesPlugin.js b/lib/optimize/RemoveParentModulesPlugin.js index 5cdcaa0f1..cbb52b858 100644 --- a/lib/optimize/RemoveParentModulesPlugin.js +++ b/lib/optimize/RemoveParentModulesPlugin.js @@ -3,20 +3,20 @@ Author Tobias Koppers @sokra */ function hasModule(chunk, module, checkedChunks) { - if(chunk.modules.indexOf(module) >= 0) return [chunk]; - if(chunk.entry) return false; + if (chunk.modules.indexOf(module) >= 0) return [chunk]; + if (chunk.entry) return false; return allHaveModule(chunk.parents.filter(function(c) { return checkedChunks.indexOf(c) < 0; }), module, checkedChunks); } function allHaveModule(someChunks, module, checkedChunks) { - if(!checkedChunks) checkedChunks = []; + if (!checkedChunks) checkedChunks = []; var chunks = []; - for(var i = 0; i < someChunks.length; i++) { + for (var i = 0; i < someChunks.length; i++) { checkedChunks.push(someChunks[i]); var subChunks = hasModule(someChunks[i], module, checkedChunks); - if(!subChunks) return false; + if (!subChunks) return false; addToSet(chunks, subChunks); } return chunks; @@ -24,13 +24,12 @@ function allHaveModule(someChunks, module, checkedChunks) { function addToSet(set, items) { items.forEach(function(item) { - if(set.indexOf(item) < 0) + if (set.indexOf(item) < 0) set.push(item); }); } -function RemoveParentModulesPlugin() { -} +function RemoveParentModulesPlugin() {} module.exports = RemoveParentModulesPlugin; RemoveParentModulesPlugin.prototype.apply = function(compiler) { @@ -38,9 +37,9 @@ RemoveParentModulesPlugin.prototype.apply = function(compiler) { compilation.plugin(["optimize-chunks", "optimize-extracted-chunks"], function(chunks) { chunks.forEach(function(chunk) { chunk.modules.slice().forEach(function(module) { - if(chunk.entry) return; + if (chunk.entry) return; var parentChunksWithModule = allHaveModule(chunk.parents, module); - if(parentChunksWithModule) { + if (parentChunksWithModule) { module.rewriteChunkInReasons(chunk, parentChunksWithModule); chunk.removeModule(module); } @@ -49,4 +48,3 @@ RemoveParentModulesPlugin.prototype.apply = function(compiler) { }); }); }; - diff --git a/lib/optimize/UglifyJsPlugin.js b/lib/optimize/UglifyJsPlugin.js index 729a0000d..27ad1deeb 100644 --- a/lib/optimize/UglifyJsPlugin.js +++ b/lib/optimize/UglifyJsPlugin.js @@ -10,8 +10,8 @@ var ModuleFilenameHelpers = require("../ModuleFilenameHelpers"); var uglify = require("uglify-js"); function UglifyJsPlugin(options) { - if(typeof options !== "object") options = {}; - if(typeof options.compressor !== "undefined") { + if (typeof options !== "object") options = {}; + if (typeof options.compressor !== "undefined") { options.compress = options.compressor; } this.options = options; @@ -24,7 +24,7 @@ UglifyJsPlugin.prototype.apply = function(compiler) { var requestShortener = new RequestShortener(compiler.context); compiler.plugin("compilation", function(compilation) { - if(options.sourceMap !== false) { + if (options.sourceMap !== false) { compilation.plugin("build-module", function(module) { // to get detailed location info about errors module.useSourceMap = true; @@ -46,12 +46,12 @@ UglifyJsPlugin.prototype.apply = function(compiler) { var warnings = []; try { var asset = compilation.assets[file]; - if(asset.__UglifyJsPlugin) { + if (asset.__UglifyJsPlugin) { compilation.assets[file] = asset.__UglifyJsPlugin; return; } - if(options.sourceMap !== false) { - if(asset.sourceAndMap) { + if (options.sourceMap !== false) { + if (asset.sourceAndMap) { var sourceAndMap = asset.sourceAndMap(); var inputSourceMap = sourceAndMap.map; var input = sourceAndMap.source; @@ -68,7 +68,7 @@ UglifyJsPlugin.prototype.apply = function(compiler) { line: line, column: column }); - if(!original || !original.source || original.source === file) return; + if (!original || !original.source || original.source === file) return; warnings.push(warning.replace(/\[.+:([0-9]+),([0-9]+)\]/, "") + "[" + requestShortener.shorten(original.source) + ":" + original.line + "," + original.column + "]"); }; @@ -81,12 +81,12 @@ UglifyJsPlugin.prototype.apply = function(compiler) { var ast = uglify.parse(input, { filename: file }); - if(options.compress !== false) { + if (options.compress !== false) { ast.figure_out_scope(); var compress = uglify.Compressor(options.compress); // eslint-disable-line new-cap ast = ast.transform(compress); } - if(options.mangle !== false) { + if (options.mangle !== false) { ast.figure_out_scope(); ast.compute_char_frequency(options.mangle || {}); ast.mangle_names(options.mangle || {}); @@ -94,10 +94,10 @@ UglifyJsPlugin.prototype.apply = function(compiler) { var output = {}; output.comments = options.comments || /^\**!|@preserve|@license/; output.beautify = options.beautify; - for(var k in options.output) { + for (var k in options.output) { output[k] = options.output[k]; } - if(options.sourceMap !== false) { + if (options.sourceMap !== false) { var map = uglify.SourceMap({ // eslint-disable-line new-cap file: file, root: "" @@ -106,21 +106,21 @@ UglifyJsPlugin.prototype.apply = function(compiler) { } var stream = uglify.OutputStream(output); // eslint-disable-line new-cap ast.print(stream); - if(map) map = map + ""; + if (map) map = map + ""; stream = stream + ""; asset.__UglifyJsPlugin = compilation.assets[file] = (map ? new SourceMapSource(stream, file, JSON.parse(map), input, inputSourceMap) : new RawSource(stream)); - if(warnings.length > 0) { + if (warnings.length > 0) { compilation.warnings.push(new Error(file + " from UglifyJs\n" + warnings.join("\n"))); } - } catch(err) { - if(err.line) { + } catch (err) { + if (err.line) { var original = sourceMap && sourceMap.originalPositionFor({ line: err.line, column: err.col }); - if(original && original.source) { + if (original && original.source) { compilation.errors.push(new Error(file + " from UglifyJs\n" + err.message + " [" + requestShortener.shorten(original.source) + ":" + original.line + "," + original.column + "]")); } else { compilation.errors.push(new Error(file + " from UglifyJs\n" + err.message + " [" + file + ":" + err.line + "," + err.col + "]")); diff --git a/lib/removeAndDo.js b/lib/removeAndDo.js index 69843b94b..c0aae641c 100644 --- a/lib/removeAndDo.js +++ b/lib/removeAndDo.js @@ -4,7 +4,7 @@ */ module.exports = function removeAndDo(collection, thing, action) { var idx = this[collection].indexOf(thing); - if(idx >= 0) { + if (idx >= 0) { this[collection].splice(idx, 1); thing[action](this); return true; diff --git a/lib/webpack.js b/lib/webpack.js index 40e197266..fda60a260 100644 --- a/lib/webpack.js +++ b/lib/webpack.js @@ -10,11 +10,11 @@ var WebpackOptionsDefaulter = require("./WebpackOptionsDefaulter"); function webpack(options, callback) { var compiler; - if(Array.isArray(options)) { + if (Array.isArray(options)) { compiler = new MultiCompiler(options.map(function(options) { return webpack(options); })); - } else if(typeof options === "object") { + } else if (typeof options === "object") { new WebpackOptionsDefaulter().process(options); compiler = new Compiler(); @@ -26,13 +26,13 @@ function webpack(options, callback) { } else { throw new Error("Invalid argument: options"); } - if(callback) { - if(typeof callback !== "function") throw new Error("Invalid argument: callback"); - if(options.watch === true) { + if (callback) { + if (typeof callback !== "function") throw new Error("Invalid argument: callback"); + if (options.watch === true) { var watchOptions = (!Array.isArray(options) ? options : options[0]).watchOptions || {}; // TODO remove this in next major version var watchDelay = (!Array.isArray(options) ? options : options[0]).watchDelay; - if(watchDelay) { + if (watchDelay) { console.warn("options.watchDelay is deprecated: Use 'options.watchOptions.aggregateTimeout' instead"); watchOptions.aggregateTimeout = watchDelay; } diff --git a/lib/webpack.web.js b/lib/webpack.web.js index ba677443d..5f0c01891 100644 --- a/lib/webpack.web.js +++ b/lib/webpack.web.js @@ -14,7 +14,7 @@ function webpack(options, callback) { compiler.options = options; compiler.options = new WebpackOptionsApply().process(options, compiler); new WebEnvironmentPlugin(options.inputFileSystem, options.outputFileSystem).apply(compiler); - if(callback) { + if (callback) { compiler.run(callback); } return compiler; diff --git a/lib/webworker/WebWorkerChunkTemplatePlugin.js b/lib/webworker/WebWorkerChunkTemplatePlugin.js index 41e80e39b..9671df77a 100644 --- a/lib/webworker/WebWorkerChunkTemplatePlugin.js +++ b/lib/webworker/WebWorkerChunkTemplatePlugin.js @@ -5,8 +5,7 @@ var ConcatSource = require("webpack-core/lib/ConcatSource"); var Template = require("../Template"); -function WebWorkerChunkTemplatePlugin() { -} +function WebWorkerChunkTemplatePlugin() {} module.exports = WebWorkerChunkTemplatePlugin; WebWorkerChunkTemplatePlugin.prototype.apply = function(chunkTemplate) { diff --git a/lib/webworker/WebWorkerMainTemplatePlugin.js b/lib/webworker/WebWorkerMainTemplatePlugin.js index 30aeb05f2..3d00ae473 100644 --- a/lib/webworker/WebWorkerMainTemplatePlugin.js +++ b/lib/webworker/WebWorkerMainTemplatePlugin.js @@ -4,13 +4,12 @@ */ var Template = require("../Template"); -function WebWorkerMainTemplatePlugin() { -} +function WebWorkerMainTemplatePlugin() {} module.exports = WebWorkerMainTemplatePlugin; WebWorkerMainTemplatePlugin.prototype.apply = function(mainTemplate) { mainTemplate.plugin("local-vars", function(source, chunk) { - if(chunk.chunks.length > 0) { + if (chunk.chunks.length > 0) { return this.asString([ source, "", @@ -35,22 +34,22 @@ WebWorkerMainTemplatePlugin.prototype.apply = function(mainTemplate) { "if(!installedChunks[chunkId]) {", this.indent([ "importScripts(" + - this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), { - hash: "\" + " + this.renderCurrentHashCode(hash) + " + \"", - hashWithLength: function(length) { - return "\" + " + this.renderCurrentHashCode(hash, length) + " + \""; - }.bind(this), - chunk: { - id: "\" + chunkId + \"" - } - }) + ");" + this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), { + hash: "\" + " + this.renderCurrentHashCode(hash) + " + \"", + hashWithLength: function(length) { + return "\" + " + this.renderCurrentHashCode(hash, length) + " + \""; + }.bind(this), + chunk: { + id: "\" + chunkId + \"" + } + }) + ");" ]), "}", "callback.call(null, " + this.requireFn + ");" ]); }); mainTemplate.plugin("bootstrap", function(source, chunk, hash) { - if(chunk.chunks.length > 0) { + if (chunk.chunks.length > 0) { var chunkCallbackName = this.outputOptions.chunkCallbackName || Template.toIdentifier("webpackChunk" + (this.outputOptions.library || "")); return this.asString([ source, diff --git a/lib/webworker/WebWorkerTemplatePlugin.js b/lib/webworker/WebWorkerTemplatePlugin.js index 9c2dd33eb..be3761fc1 100644 --- a/lib/webworker/WebWorkerTemplatePlugin.js +++ b/lib/webworker/WebWorkerTemplatePlugin.js @@ -5,8 +5,7 @@ var WebWorkerMainTemplatePlugin = require("./WebWorkerMainTemplatePlugin"); var WebWorkerChunkTemplatePlugin = require("./WebWorkerChunkTemplatePlugin"); -function WebWorkerTemplatePlugin() { -} +function WebWorkerTemplatePlugin() {} module.exports = WebWorkerTemplatePlugin; WebWorkerTemplatePlugin.prototype.apply = function(compiler) { compiler.plugin("this-compilation", function(compilation) {