function webpack(options, callback) { const webpackOptionsValidationErrors = validateSchema(webpackOptionsSchema, options); if(webpackOptionsValidationErrors.length) { throw new WebpackOptionsValidationError(webpackOptionsValidationErrors); } let compiler; if(Array.isArray(options)) { compiler = new MultiCompiler(options.map(options => webpack(options))); } else if(typeof options === "object") { new WebpackOptionsDefaulter().process(options); compiler = new Compiler(); compiler.context = options.context; compiler.options = options; new NodeEnvironmentPlugin().apply(compiler); if(options.plugins && Array.isArray(options.plugins)) { compiler.apply.apply(compiler, options.plugins); } compiler.applyPlugins("environment"); compiler.applyPlugins("after-environment"); compiler.options = new WebpackOptionsApply().process(options, compiler); } else { throw new Error("Invalid argument: options"); } if(callback) { if(typeof callback !== "function") throw new Error("Invalid argument: callback"); if(options.watch === true || (Array.isArray(options) && options.some(o => o.watch))) { const watchOptions = Array.isArray(options) ? options.map(o => o.watchOptions || {}) : (options.watchOptions || {}); return compiler.watch(watchOptions, callback); } compiler.run(callback); } return compiler; }
n/a
class AMDDefineDependency extends NullDependency { constructor(range, arrayRange, functionRange, objectRange, namedModule) { super(); this.range = range; this.arrayRange = arrayRange; this.functionRange = functionRange; this.objectRange = objectRange; this.namedModule = namedModule; } get type() { return "amd define"; } }
n/a
class AMDRequireArrayDependency extends Dependency { constructor(depsArray, range) { super(); this.depsArray = depsArray; this.range = range; } get type() { return "amd require array"; } }
n/a
class AMDRequireContextDependency extends ContextDependency { constructor(request, recursive, regExp, range, valueRange) { super(request, recursive, regExp); this.range = range; this.valueRange = valueRange; } get type() { return "amd require context"; } getWarnings() { if(this.critical) { return [ new CriticalDependencyWarning(this.critical) ]; } } }
n/a
class AMDRequireDependency extends NullDependency { constructor(block) { super(); this.block = block; } }
n/a
class AMDRequireItemDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; } get type() { return "amd require"; } }
n/a
class AutomaticPrefetchPlugin { apply(compiler) { compiler.plugin("compilation", (compilation, params) => { const normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(PrefetchDependency, normalModuleFactory); }); let lastModules = null; compiler.plugin("after-compile", (compilation, callback) => { lastModules = compilation.modules .filter(m => m instanceof NormalModule) .map(m => ({ context: m.context, request: m.request })); callback(); }); compiler.plugin("make", (compilation, callback) => { if(!lastModules) return callback(); asyncLib.forEach(lastModules, (m, callback) => { compilation.prefetch(m.context || compiler.context, new PrefetchDependency(m.request), callback); }, callback); }); } }
n/a
class BannerPlugin { constructor(options) { if(arguments.length > 1) throw new Error("BannerPlugin only takes one argument (pass an options object)"); if(typeof options === "string") options = { banner: options }; this.options = options || {}; this.banner = this.options.raw ? options.banner : wrapComment(options.banner); } apply(compiler) { const options = this.options; const banner = this.banner; compiler.plugin("compilation", (compilation) => { compilation.plugin("optimize-chunk-assets", (chunks, callback) => { chunks.forEach((chunk) => { if(options.entryOnly && !chunk.isInitial()) return; chunk.files .filter(ModuleFilenameHelpers.matchObject.bind(undefined, options)) .forEach((file) => compilation.assets[file] = new ConcatSource( banner, "\n", compilation.assets[file] ) ); }); callback(); }); }); } }
n/a
class CachePlugin { constructor(cache) { this.cache = cache || {}; this.FS_ACCURENCY = 2000; } apply(compiler) { if(Array.isArray(compiler.compilers)) { compiler.compilers.forEach((c, idx) => { c.apply(new CachePlugin(this.cache[idx] = this.cache[idx] || {})); }); } else { compiler.plugin("compilation", compilation => { if(!compilation.notCacheable) { compilation.cache = this.cache; } else if(this.watching) { compilation.warnings.push( new Error(`CachePlugin - Cache cannot be used because of: ${compilation.notCacheable}`) ); } }); compiler.plugin("watch-run", (compiler, callback) => { this.watching = true; callback(); }); compiler.plugin("run", (compiler, callback) => { if(!compiler._lastCompilationFileDependencies) return callback(); const fs = compiler.inputFileSystem; const fileTs = compiler.fileTimestamps = {}; asyncLib.forEach(compiler._lastCompilationFileDependencies, (file, callback) => { fs.stat(file, (err, stat) => { if(err) { if(err.code === "ENOENT") return callback(); return callback(err); } if(stat.mtime) this.applyMtime(+stat.mtime); fileTs[file] = +stat.mtime || Infinity; callback(); }); }, err => { if(err) return callback(err); Object.keys(fileTs).forEach(key => { fileTs[key] += this.FS_ACCURENCY; }); callback(); }); }); compiler.plugin("after-compile", function(compilation, callback) { compilation.compiler._lastCompilationFileDependencies = compilation.fileDependencies; compilation.compiler._lastCompilationContextDependencies = compilation.contextDependencies; callback(); }); } } /* istanbul ignore next */ applyMtime(mtime) { if(this.FS_ACCURENCY > 1 && mtime % 2 !== 0) this.FS_ACCURENCY = 1; else if(this.FS_ACCURENCY > 10 && mtime % 20 !== 0) this.FS_ACCURENCY = 10; else if(this.FS_ACCURENCY > 100 && mtime % 200 !== 0) this.FS_ACCURENCY = 100; else if(this.FS_ACCURENCY > 1000 && mtime % 2000 !== 0) this.FS_ACCURENCY = 1000; } }
n/a
class CommonJsRequireContextDependency extends ContextDependency { constructor(request, recursive, regExp, range, valueRange) { super(request, recursive, regExp); this.range = range; this.valueRange = valueRange; } get type() { return "cjs require context"; } getWarnings() { if(!this.critical) { return; } return [ new CriticalDependencyWarning(this.critical) ]; } }
n/a
class CommonJsRequireDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; } get type() { return "cjs require"; } }
n/a
function Compiler() { Tapable.call(this); this.outputPath = ""; this.outputFileSystem = null; this.inputFileSystem = null; this.recordsInputPath = null; this.recordsOutputPath = null; this.records = {}; this.fileTimestamps = {}; this.contextTimestamps = {}; this.resolvers = { normal: null, loader: null, context: null }; var deprecationReported = false; this.parser = { plugin: function(hook, fn) { if(!deprecationReported) { console.warn("webpack: Using compiler.parser is deprecated.\n" + "Use compiler.plugin(\"compilation\", function(compilation, data) {\n data.normalModuleFactory.plugin(\"parser\", function (parser, options) { parser.plugin(/* ... */); });\n}); instead. " + "It was called " + new Error().stack.split("\n")[2].trim() + "."); deprecationReported = true; } this.plugin("compilation", function(compilation, data) { data.normalModuleFactory.plugin("parser", function(parser) { parser.plugin(hook, fn); }); }); }.bind(this), apply: function() { var args = arguments; if(!deprecationReported) { console.warn("webpack: Using compiler.parser is deprecated.\n" + "Use compiler.plugin(\"compilation\", function(compilation, data) {\n data.normalModuleFactory.plugin(\"parser\", function (parser, options) { parser.apply(/* ... */); });\n}); instead. " + "It was called " + new Error().stack.split("\n")[2].trim() + "."); deprecationReported = true; } this.plugin("compilation", function(compilation, data) { data.normalModuleFactory.plugin("parser", function(parser) { parser.apply.apply(parser, args); }); }); }.bind(this) }; this.options = {}; }
n/a
function Watching(compiler, watchOptions, handler) { this.startTime = null; this.invalid = false; this.error = null; this.stats = null; this.handler = handler; this.closed = false; if(typeof watchOptions === "number") { this.watchOptions = { aggregateTimeout: watchOptions }; } else if(watchOptions && typeof watchOptions === "object") { this.watchOptions = Object.assign({}, watchOptions); } else { this.watchOptions = {}; } this.watchOptions.aggregateTimeout = this.watchOptions.aggregateTimeout || 200; this.compiler = compiler; this.running = true; this.compiler.readRecords(function(err) { if(err) return this._done(err); this._go(); }.bind(this)); }
n/a
class ConstDependency extends NullDependency { constructor(expression, range) { super(); this.expression = expression; this.range = range; } updateHash(hash) { hash.update(this.range + ""); hash.update(this.expression + ""); } }
n/a
function ContextModuleFactory(resolvers) { Tapable.call(this); this.resolvers = resolvers; }
n/a
class ContextReplacementPlugin { constructor(resourceRegExp, newContentResource, newContentRecursive, newContentRegExp) { this.resourceRegExp = resourceRegExp; if(typeof newContentResource === "function") { this.newContentCallback = newContentResource; } else if(typeof newContentResource === "string" && typeof newContentRecursive === "object") { this.newContentResource = newContentResource; this.newContentCreateContextMap = (fs, callback) => { callback(null, newContentRecursive); }; } else if(typeof newContentResource === "string" && typeof newContentRecursive === "function") { this.newContentResource = newContentResource; this.newContentCreateContextMap = newContentRecursive; } else { if(typeof newContentResource !== "string") { newContentRegExp = newContentRecursive; newContentRecursive = newContentResource; newContentResource = undefined; } if(typeof newContentRecursive !== "boolean") { newContentRegExp = newContentRecursive; newContentRecursive = undefined; } this.newContentResource = newContentResource; this.newContentRecursive = newContentRecursive; this.newContentRegExp = newContentRegExp; } } apply(compiler) { const resourceRegExp = this.resourceRegExp; const newContentCallback = this.newContentCallback; const newContentResource = this.newContentResource; const newContentRecursive = this.newContentRecursive; const newContentRegExp = this.newContentRegExp; const newContentCreateContextMap = this.newContentCreateContextMap; compiler.plugin("context-module-factory", (cmf) => { cmf.plugin("before-resolve", (result, callback) => { if(!result) return callback(); if(resourceRegExp.test(result.request)) { if(typeof newContentResource !== "undefined") result.request = newContentResource; if(typeof newContentRecursive !== "undefined") result.recursive = newContentRecursive; if(typeof newContentRegExp !== "undefined") result.regExp = newContentRegExp; if(typeof newContentCallback === "function") { newContentCallback(result); } else { result.dependencies.forEach((d) => { if(d.critical) d.critical = false; }); } } return callback(null, result); }); cmf.plugin("after-resolve", (result, callback) => { if(!result) return callback(); if(resourceRegExp.test(result.resource)) { if(typeof newContentResource !== "undefined") result.resource = path.resolve(result.resource, newContentResource); if(typeof newContentRecursive !== "undefined") result.recursive = newContentRecursive; if(typeof newContentRegExp !== "undefined") result.regExp = newContentRegExp; if(typeof newContentCreateContextMap === "function") result.resolveDependencies = createResolveDependenciesFromContextMap(newContentCreateContextMap); if(typeof newContentCallback === "function") { const origResource = result.resource; newContentCallback(result); if(result.resource !== origResource) { result.resource = path.resolve(origResource, result.resource); } } else { result.dependencies.forEach((d) => { if(d.critical) d.critical = false; }); } } return callback(null, result); }); }); } }
n/a
class DefinePlugin { constructor(definitions) { this.definitions = definitions; } apply(compiler) { const definitions = this.definitions; compiler.plugin("compilation", (compilation, params) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); params.normalModuleFactory.plugin("parser", (parser) => { (function walkDefinitions(definitions, prefix) { Object.keys(definitions).forEach((key) => { const code = definitions[key]; if(code && typeof code === "object" && !(code instanceof RegExp)) { walkDefinitions(code, prefix + key + "."); applyObjectDefine(prefix + key, code); return; } applyDefineKey(prefix, key); applyDefine(prefix + key, code); }); }(definitions, "")); function stringifyObj(obj) { return "__webpack_require__.i({" + Object.keys(obj).map((key) => { const 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); else return code + ""; } function applyDefineKey(prefix, key) { const splittedKey = key.split("."); splittedKey.slice(1).forEach((_, i) => { const fullKey = prefix + splittedKey.slice(0, i + 1).join("."); parser.plugin("can-rename " + fullKey, ParserHelpers.approve); }); } function applyDefine(key, code) { const isTypeof = /^typeof\s+/.test(key); if(isTypeof) key = key.replace(/^typeof\s+/, ""); let recurse = false; let recurseTypeof = false; code = toCode(code); if(!isTypeof) { parser.plugin("can-rename " + key, ParserHelpers.approve); parser.plugin("evaluate Identifier " + key, (expr) => { /** * this is needed in case there is a recursion in the DefinePlugin * to prevent an endless recursion * e.g.: new DefinePlugin({ * "a": "b", * "b": "a" * }); */ if(recurse) return; recurse = true; const res = parser.evaluate(code); recurse = false; res.setRange(expr.range); return res; }); parser.plugin("expression " + key, ParserHelpers.toConstantDependency(code)); } const typeofCode = isTypeof ? code : "typeof (" + code + ")"; parser.plugin("evaluate typeof " + key, (expr) => { /** * this is needed in case there is a recursion in the DefinePlugin * to prevent an endless recursion * e.g.: new DefinePlugin({ * "typeof a": "tyepof b", * "typeof b": "typeof a" * }); */ if(recurseTypeof) return; recurseTypeof = true; const res = parser.evaluate(typeofCode); recurseTypeof = false; res.setRange(expr.range); return res; }); parser.plugin("typeof " + key, (expr) => { const res = parser.evaluate(typeofCode); if(!res.isString()) return; return ParserHelpers.toConstantDependency(JSON.stringify(res.string)).bind(parser)(expr); }); } function applyObjectDefine(key, obj) { const code = stringifyObj(obj); parser.plugin("can-rename " + key, ParserHelpers.approve); parser.plugin("evaluate Identifier " + key, (expr) => new BasicEvaluatedExpression().setRange(expr.range)); parser.plugin("evaluate typeof " + key, ParserHelpers.evaluateToString("object")); parser.plugin("expression " + key, ParserHelpers.toConstantDependency(code)); parser.plugin("typeof " + key, ParserHelpers.toConstantDependency(JSON.stringify("object"))); } }); } ...
n/a
class Dependency { constructor() { this.module = null; } isEqualResource() { return false; } // Returns the referenced module and export getReference() { if(!this.module) return null; return { module: this.module, importedNames: true, // true: full object, false: only sideeffects/no export, array of strings: the exports with this names }; } // Returns the exported names getExports() { return null; } getWarnings() { return null; } getErrors() { return null; } updateHash(hash) { hash.update((this.module && this.module.id) + ""); } disconnect() { this.module = null; } // TODO: remove in webpack 3 compare(a, b) { return compareLocations(a.loc, b.loc); } }
n/a
class DllPlugin { constructor(options) { this.options = options; } apply(compiler) { compiler.plugin("entry-option", (context, entry) => { function itemToPlugin(item, name) { if(Array.isArray(item)) return new DllEntryPlugin(context, item, name); else throw new Error("DllPlugin: supply an Array as entry"); } if(typeof entry === "object" && !Array.isArray(entry)) { Object.keys(entry).forEach(name => { compiler.apply(itemToPlugin(entry[name], name)); }); } else { compiler.apply(itemToPlugin(entry, "main")); } return true; }); compiler.apply(new LibManifestPlugin(this.options)); compiler.apply(new FlagInitialModulesAsUsedPlugin()); } }
n/a
class DllReferencePlugin { constructor(options) { this.options = options; } apply(compiler) { compiler.plugin("compilation", (compilation, params) => { const normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(DelegatedSourceDependency, normalModuleFactory); }); compiler.plugin("before-compile", (params, callback) => { const manifest = this.options.manifest; if(typeof manifest === "string") { params.compilationDependencies.push(manifest); compiler.inputFileSystem.readFile(manifest, function(err, result) { if(err) return callback(err); params["dll reference " + manifest] = JSON.parse(result.toString("utf-8")); return callback(); }); } else { return callback(); } }); compiler.plugin("compile", (params) => { let manifest = this.options.manifest; if(typeof manifest === "string") { manifest = params["dll reference " + manifest]; } const name = this.options.name || manifest.name; const sourceType = this.options.sourceType || "var"; const externals = {}; const source = "dll-reference " + name; externals[source] = name; params.normalModuleFactory.apply(new ExternalModuleFactoryPlugin(sourceType, externals)); params.normalModuleFactory.apply(new DelegatedModuleFactoryPlugin({ source: source, type: this.options.type, scope: this.options.scope, context: this.options.context || compiler.options.context, content: this.options.content || manifest.content, extensions: this.options.extensions })); }); } }
n/a
class DynamicEntryPlugin { constructor(context, entry) { this.context = context; this.entry = entry; } apply(compiler) { compiler.plugin("compilation", (compilation, params) => { const multiModuleFactory = new MultiModuleFactory(); const normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(MultiEntryDependency, multiModuleFactory); compilation.dependencyFactories.set(SingleEntryDependency, normalModuleFactory); }); compiler.plugin("make", (compilation, callback) => { const addEntry = (entry, name) => { const dep = DynamicEntryPlugin.createDependency(entry, name); return new Promise((resolve, reject) => { compilation.addEntry(this.context, dep, name, (err) => { if(err) return reject(err); resolve(); }); }); }; Promise.resolve(this.entry()).then((entry) => { if(typeof entry === "string" || Array.isArray(entry)) { addEntry(entry, "main").then(() => callback(), callback); } else if(typeof entry === "object") { Promise.all(Object.keys(entry).map((name) => { return addEntry(entry[name], name); })).then(() => callback(), callback); } }); }); } }
n/a
class EnvironmentPlugin { constructor(keys) { if(Array.isArray(keys)) { this.keys = keys; this.defaultValues = {}; } else if(keys && typeof keys === "object") { this.keys = Object.keys(keys); this.defaultValues = keys; } else { this.keys = Array.prototype.slice.call(arguments); this.defaultValues = {}; } } apply(compiler) { const definitions = this.keys.reduce((defs, key) => { const value = process.env[key] !== undefined ? process.env[key] : this.defaultValues[key]; if(value === undefined) { compiler.plugin("this-compilation", compilation => { const error = new Error( `EnvironmentPlugin - ${key} environment variable is undefined.\n\n` + "You can pass an object with default values to suppress this warning.\n" + "See https://webpack.js.org/plugins/environment-plugin for example." ); error.name = "EnvVariableNotDefinedError"; compilation.warnings.push(error); }); } defs[`process.env.${key}`] = typeof value === "undefined" ? "undefined" : JSON.stringify(value); return defs; }, {}); compiler.apply(new DefinePlugin(definitions)); } }
n/a
class EvalDevToolModulePlugin { constructor(sourceUrlComment, moduleFilenameTemplate) { this.sourceUrlComment = sourceUrlComment; this.moduleFilenameTemplate = moduleFilenameTemplate; } apply(compiler) { compiler.plugin("compilation", (compilation) => { compilation.moduleTemplate.apply(new EvalDevToolModuleTemplatePlugin(this.sourceUrlComment, this.moduleFilenameTemplate)); }); } }
n/a
class EvalSourceMapDevToolPlugin { constructor(options) { if(arguments.length > 1) throw new Error("EvalSourceMapDevToolPlugin only takes one argument (pass an options object)"); if(typeof options === "string") { options = { append: options }; } if(!options) options = {}; this.options = options; } apply(compiler) { const options = this.options; compiler.plugin("compilation", (compilation) => { new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); compilation.moduleTemplate.apply(new EvalSourceMapDevToolModuleTemplatePlugin(compilation, options)); }); } }
n/a
class ExtendedAPIPlugin { apply(compiler) { compiler.plugin("compilation", (compilation, params) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); compilation.mainTemplate.plugin("require-extensions", function(source, chunk, hash) { const buf = [source]; buf.push(""); buf.push("// __webpack_hash__"); buf.push(`${this.requireFn}.h = ${JSON.stringify(hash)};`); buf.push(""); buf.push("// __webpack_chunkname__"); buf.push(`${this.requireFn}.cn = ${JSON.stringify(chunk.name)};`); return this.asString(buf); }); compilation.mainTemplate.plugin("global-hash", () => true); params.normalModuleFactory.plugin("parser", (parser, parserOptions) => { Object.keys(REPLACEMENTS).forEach(key => { parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key])); parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key])); }); }); }); } }
n/a
class ExternalsPlugin { constructor(type, externals) { this.type = type; this.externals = externals; } apply(compiler) { compiler.plugin("compile", (params) => { params.normalModuleFactory.apply(new ExternalModuleFactoryPlugin(this.type, this.externals)); }); } }
n/a
class HarmonyAcceptDependency extends NullDependency { constructor(range, dependencies, hasCallback) { super(); this.range = range; this.dependencies = dependencies; this.hasCallback = hasCallback; } get type() { return "accepted harmony modules"; } }
n/a
class HarmonyAcceptImportDependency extends HarmonyImportDependency { constructor(request, importedVar, range) { super(request, importedVar, range); } get type() { return "harmony accept"; } }
n/a
class HarmonyCompatibilityDependency extends NullDependency { constructor(originModule) { super(); this.originModule = originModule; } get type() { return "harmony export header"; } }
n/a
class HarmonyExportExpressionDependency extends NullDependency { constructor(originModule, range, rangeStatement) { super(); this.originModule = originModule; this.range = range; this.rangeStatement = rangeStatement; } get type() { return "harmony export expression"; } getExports() { return { exports: ["default"] }; } describeHarmonyExport() { return { exportedName: "default", precedence: 1, }; } }
n/a
class HarmonyExportHeaderDependency extends NullDependency { constructor(range, rangeStatement) { super(); this.range = range; this.rangeStatement = rangeStatement; } get type() { return "harmony export header"; } }
n/a
class HarmonyExportImportedSpecifierDependency extends NullDependency { constructor(originModule, importDependency, importedVar, id, name) { super(); this.originModule = originModule; this.importDependency = importDependency; this.importedVar = importedVar; this.id = id; this.name = name; } get type() { return "harmony export imported specifier"; } getReference() { const name = this.name; const used = this.originModule.isUsed(name); const active = HarmonyModulesHelpers.isActive(this.originModule, this); const importedModule = this.importDependency.module; if(!importedModule || !used || !active) return null; if(!this.originModule.usedExports) return null; if(name) { const nameIsNotInUsedExports = Array.isArray(this.originModule.usedExports) && this.originModule.usedExports.indexOf(name) < 0; if(nameIsNotInUsedExports) return null; // export { name as name } if(this.id) { return { module: importedModule, importedNames: [this.id] }; } // export { * as name } return { module: importedModule, importedNames: true }; } // export * if(Array.isArray(this.originModule.usedExports)) { // reexport * with known used exports var activeExports = HarmonyModulesHelpers.getActiveExports(this.originModule, this); if(Array.isArray(importedModule.providedExports)) { return { module: importedModule, importedNames: this.originModule.usedExports.filter((id) => { const notInActiveExports = activeExports.indexOf(id) < 0; const notDefault = id !== "default"; const inProvidedExports = importedModule.providedExports.indexOf(id) >= 0; return notInActiveExports && notDefault && inProvidedExports; }), }; } return { module: importedModule, importedNames: this.originModule.usedExports.filter(id => { const notInActiveExports = activeExports.indexOf(id) < 0; const notDefault = id !== "default"; return notInActiveExports && notDefault; }), }; } if(Array.isArray(importedModule.providedExports)) { return { module: importedModule, importedNames: importedModule.providedExports.filter(id => id !== "default"), }; } return { module: importedModule, importedNames: true, }; } getExports() { if(this.name) { return { exports: [this.name] }; } const importedModule = this.importDependency.module; if(!importedModule) { // no imported module available return { exports: null }; } if(Array.isArray(importedModule.providedExports)) { return { exports: importedModule.providedExports.filter(id => id !== "default"), dependencies: [importedModule] }; } if(importedModule.providedExports) { return { exports: true }; } return { exports: null, dependencies: [importedModule] }; } describeHarmonyExport() { const importedModule = this.importDependency.module; if(!this.name && importedModule && Array.isArray(importedModule.providedExports)) { // for a star export and when we know which exports are provided, we can tell so return { exportedName: importedModule.providedExports, precedence: 3 }; } return { exportedName: this.name, precedence: this.name ? 2 : 3 }; } updateHash(hash) { super.updateHash(hash); const hashValue = this.getHashValue(this.importDependency.module); hash.update(hashValue); } getHashValue(importedModule) { if(!importedModule) { return ""; } const stringifiedUsedExport = JSON.stringify(importedModule.usedExports); const stringifiedProvidedExport = JSON.stringify(importedModule.providedExports); return importedModule.used + stringifiedUsedExport + stringifiedProvidedExport; } }
n/a
class HarmonyExportSpecifierDependency extends NullDependency { constructor(originModule, id, name, position, immutable) { super(); this.originModule = originModule; this.id = id; this.name = name; this.position = position; this.immutable = immutable; } get type() { return "harmony export specifier"; } getExports() { return { exports: [this.name] }; } describeHarmonyExport() { return { exportedName: this.name, precedence: 1 }; } }
n/a
class HarmonyImportDependency extends ModuleDependency { constructor(request, importedVar, range) { super(request); this.range = range; this.importedVar = importedVar; } get type() { return "harmony import"; } getReference() { if(!this.module) return null; return { module: this.module, importedNames: false }; } updateHash(hash) { super.updateHash(hash); hash.update((this.module && (!this.module.meta || this.module.meta.harmonyModule)) + ""); } }
n/a
class HarmonyImportSpecifierDependency extends NullDependency { constructor(importDependency, importedVar, id, name, range, strictExportPresence) { super(); this.importDependency = importDependency; this.importedVar = importedVar; this.id = id; this.name = name; this.range = range; this.strictExportPresence = strictExportPresence; } get type() { return "harmony import specifier"; } getReference() { if(!this.importDependency.module) return null; return { module: this.importDependency.module, importedNames: this.id ? [this.id] : true }; } getWarnings() { if(this.strictExportPresence) { return []; } return this._getErrors(); } getErrors() { if(this.strictExportPresence) { return this._getErrors(); } return []; } _getErrors() { const importedModule = this.importDependency.module; if(!importedModule || !importedModule.meta || !importedModule.meta.harmonyModule) { return; } if(!this.id) { return; } if(importedModule.isProvided(this.id) !== false) { return; } const idIsNotNameMessage = this.id !== this.name ? ` (imported as '${this.name}')` : ""; const errorMessage = `"export '${this.id}'${idIsNotNameMessage} was not found in '${this.importDependency.userRequest}'`; const err = new Error(errorMessage); err.hideStack = true; return [err]; } updateHash(hash) { super.updateHash(hash); const importedModule = this.importDependency.module; hash.update((importedModule && importedModule.id) + ""); hash.update((importedModule && this.id) + ""); hash.update((importedModule && this.importedVar) + ""); hash.update((importedModule && this.id && importedModule.isUsed(this.id)) + ""); hash.update((importedModule && (!importedModule.meta || importedModule.meta.harmonyModule)) + ""); hash.update((importedModule && (importedModule.used + JSON.stringify(importedModule.usedExports))) + ""); } }
n/a
class HashedModuleIdsPlugin { constructor(options) { this.options = Object.assign({ hashFunction: "md5", hashDigest: "base64", hashDigestLength: 4 }, options); } apply(compiler) { const options = this.options; compiler.plugin("compilation", (compilation) => { const usedIds = new Set(); compilation.plugin("before-module-ids", (modules) => { modules.forEach((module) => { if(module.id === null && module.libIdent) { const id = module.libIdent({ context: this.options.context || compiler.options.context }); const hash = createHash(options.hashFunction); hash.update(id); const hashId = hash.digest(options.hashDigest); let len = options.hashDigestLength; while(usedIds.has(hashId.substr(0, len))) len++; module.id = hashId.substr(0, len); usedIds.add(module.id); } }); }); }); } }
n/a
function HotModuleReplacementPlugin(options) { options = options || {}; this.multiStep = options.multiStep; this.fullBuildTimeout = options.fullBuildTimeout || 200; }
n/a
class IgnorePlugin { constructor(resourceRegExp, contextRegExp) { this.resourceRegExp = resourceRegExp; this.contextRegExp = contextRegExp; this.checkIgnore = this.checkIgnore.bind(this); } /* * Only returns true if a "resourceRegExp" exists * and the resource given matches the regexp. */ checkResouce(resource) { if(!this.resourceRegExp) { return false; } return this.resourceRegExp.test(resource); } /* * Returns true if contextRegExp does not exist * or if context matches the given regexp. */ checkContext(context) { if(!this.contextRegExp) { return true; } return this.contextRegExp.test(context); } /* * Returns true if result should be ignored. * false if it shouldn't. * * Not that if "contextRegExp" is given, both the "resourceRegExp" * and "contextRegExp" have to match. */ checkResult(result) { if(!result) { return true; } return this.checkResouce(result.request) && this.checkContext(result.context); } checkIgnore(result, callback) { // check if result is ignored if(this.checkResult(result)) { return callback(); } return callback(null, result); } apply(compiler) { compiler.plugin("normal-module-factory", (nmf) => { nmf.plugin("before-resolve", this.checkIgnore); }); compiler.plugin("context-module-factory", (cmf) => { cmf.plugin("before-resolve", this.checkIgnore); }); } }
n/a
class ImportContextDependency extends ContextDependency { constructor(request, recursive, regExp, range, valueRange, chunkName) { super(request, recursive, regExp); this.range = range; this.valueRange = valueRange; this.async = true; this.chunkName = chunkName; } get type() { return "import() context"; } getWarnings() { if(!this.critical) { return; } return [ new CriticalDependencyWarning(this.critical) ]; } }
n/a
class ImportDependency extends ModuleDependency { constructor(request, block) { super(request); this.block = block; } get type() { return "import()"; } }
n/a
class JsonpTemplatePlugin { apply(compiler) { compiler.plugin("this-compilation", (compilation) => { compilation.mainTemplate.apply(new JsonpMainTemplatePlugin()); compilation.chunkTemplate.apply(new JsonpChunkTemplatePlugin()); compilation.hotUpdateChunkTemplate.apply(new JsonpHotUpdateChunkTemplatePlugin()); }); } }
n/a
class LibraryTemplatePlugin { constructor(name, target, umdNamedDefine, auxiliaryComment) { this.name = name; this.target = target; this.umdNamedDefine = umdNamedDefine; this.auxiliaryComment = auxiliaryComment; } apply(compiler) { compiler.plugin("this-compilation", (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": case "commonjs-module": 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, { optionalAmdExternalAsGlobal: this.target === "umd2", namedDefine: this.umdNamedDefine, auxiliaryComment: this.auxiliaryComment })); 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`); } }); } }
n/a
class LoaderOptionsPlugin { constructor(options) { if(typeof options !== "object") options = {}; if(!options.test) options.test = { test: () => true }; this.options = options; } apply(compiler) { const options = this.options; compiler.plugin("compilation", (compilation) => { compilation.plugin("normal-module-loader", (context, module) => { const resource = module.resource; if(!resource) return; const i = resource.indexOf("?"); if(ModuleFilenameHelpers.matchObject(options, i < 0 ? resource : resource.substr(0, i))) { const filterSet = new Set(["include", "exclude", "test"]); Object.keys(options) .filter((key) => !filterSet.has(key)) .forEach((key) => context[key] = options[key]); } }); }); } }
...
switch(err.params.additionalProperty) {
case "debug":
return `${baseMessage}\n` +
"The 'debug' property was removed in webpack 2.\n" +
"Loaders should be updated to allow passing this option via loader options in module.rules.\n" +
"Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:\n" +
"plugins: [\n" +
" new webpack.LoaderOptionsPlugin({\n" +
" debug: true\n" +
" })\n" +
"]";
}
return baseMessage + "\n" +
"For typos: please correct them.\n" +
"For loader options: webpack 2 no longer allows custom properties in configuration.\n" +
...
class LoaderTargetPlugin { constructor(target) { this.target = target; } apply(compiler) { compiler.plugin("compilation", (compilation) => { compilation.plugin("normal-module-loader", (loaderContext) => loaderContext.target = this.target); }); } }
n/a
class LocalModuleDependency extends NullDependency { constructor(localModule, range) { super(); localModule.flagUsed(); this.localModule = localModule; this.range = range; } }
n/a
function MemoryFileSystem(data) { this.data = data || {}; }
n/a
class ModuleHotAcceptDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; this.weak = true; } get type() { return "module.hot.accept"; } }
n/a
class ModuleHotDeclineDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; this.weak = true; } get type() { return "module.hot.decline"; } }
n/a
function MultiCompiler(compilers) { Tapable.call(this); if(!Array.isArray(compilers)) { compilers = Object.keys(compilers).map(function(name) { compilers[name].name = name; return compilers[name]; }); } this.compilers = compilers; function delegateProperty(name) { Object.defineProperty(this, name, { configurable: false, get: function() { throw new Error("Cannot read " + name + " of a MultiCompiler"); }, set: function(value) { this.compilers.forEach(function(compiler) { compiler[name] = value; }); }.bind(this) }); } delegateProperty.call(this, "outputFileSystem"); delegateProperty.call(this, "inputFileSystem"); Object.defineProperty(this, "outputPath", { 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)) { commonPath = commonPath.replace(/[\/\\][^\/\\]*$/, ""); } } if(!commonPath && compilers[0].outputPath[0] === "/") return "/"; return commonPath; } }); var doneCompilers = 0; var compilerStats = []; this.compilers.forEach(function(compiler, idx) { var compilerDone = false; compiler.plugin("done", function(stats) { if(!compilerDone) { compilerDone = true; doneCompilers++; } compilerStats[idx] = stats; if(doneCompilers === this.compilers.length) { this.applyPlugins("done", new MultiStats(compilerStats)); } }.bind(this)); compiler.plugin("invalid", function() { if(compilerDone) { compilerDone = false; doneCompilers--; } this.applyPlugins("invalid"); }.bind(this)); }, this); }
n/a
class NamedChunksPlugin { static defaultNameResolver(chunk) { return chunk.name || null; } constructor(nameResolver) { this.nameResolver = nameResolver || NamedChunksPlugin.defaultNameResolver; } apply(compiler) { compiler.plugin("compilation", (compilation) => { compilation.plugin("before-chunk-ids", (chunks) => { chunks.forEach((chunk) => { if(chunk.id === null) { chunk.id = this.nameResolver(chunk); } }); }); }); } }
n/a
class NamedModulesPlugin { constructor(options) { this.options = options || {}; } apply(compiler) { compiler.plugin("compilation", (compilation) => { compilation.plugin("before-module-ids", (modules) => { modules.forEach((module) => { if(module.id === null && module.libIdent) { module.id = module.libIdent({ context: this.options.context || compiler.options.context }); } }); }); }); } }
n/a
class NewWatchingPlugin { apply(compiler) { compiler.plugin("compilation", function(compilation) { compilation.warnings.push(new Error("The 'NewWatchingPlugin' is no longer necessary (now default)")); }); } }
n/a
class NoEmitOnErrorsPlugin { apply(compiler) { compiler.plugin("should-emit", (compilation) => { if(compilation.errors.length > 0) return false; }); compiler.plugin("compilation", (compilation) => { compilation.plugin("should-record", () => { if(compilation.errors.length > 0) return false; }); }); } }
n/a
class NoErrorsPlugin { apply(compiler) { compiler.plugin("should-emit", (compilation) => { if(!deprecationReported) { compilation.warnings.push("webpack: Using NoErrorsPlugin is deprecated.\n" + "Use NoEmitOnErrorsPlugin instead.\n"); deprecationReported = true; } if(compilation.errors.length > 0) return false; }); compiler.plugin("compilation", (compilation) => { compilation.plugin("should-record", () => { if(compilation.errors.length > 0) return false; }); }); } }
n/a
class NodeEnvironmentPlugin { apply(compiler) { compiler.inputFileSystem = new CachedInputFileSystem(new NodeJsInputFileSystem(), 60000); const inputFileSystem = compiler.inputFileSystem; compiler.outputFileSystem = new NodeOutputFileSystem(); compiler.watchFileSystem = new NodeWatchFileSystem(compiler.inputFileSystem); compiler.plugin("before-run", (compiler, callback) => { if(compiler.inputFileSystem === inputFileSystem) inputFileSystem.purge(); callback(); }); } }
n/a
function NodeMainTemplatePlugin(asyncChunkLoading) { this.asyncChunkLoading = asyncChunkLoading; }
n/a
function NodeSourcePlugin(options) { this.options = options; }
n/a
class NormalModuleReplacementPlugin { constructor(resourceRegExp, newResource) { this.resourceRegExp = resourceRegExp; this.newResource = newResource; } apply(compiler) { const resourceRegExp = this.resourceRegExp; const newResource = this.newResource; compiler.plugin("normal-module-factory", (nmf) => { nmf.plugin("before-resolve", (result, callback) => { if(!result) return callback(); if(resourceRegExp.test(result.request)) { if(typeof newResource === "function") { newResource(result); } else { result.request = newResource; } } return callback(null, result); }); nmf.plugin("after-resolve", (result, callback) => { if(!result) return callback(); if(resourceRegExp.test(result.resource)) { if(typeof newResource === "function") { newResource(result); } else { result.resource = path.resolve(path.dirname(result.resource), newResource); } } return callback(null, result); }); }); } }
n/a
class NullDependency extends Dependency { get type() { return "null"; } isEqualResource() { return false; } updateHash() {} }
n/a
class PrefetchPlugin { constructor(context, request) { if(!request) { this.request = context; } else { this.context = context; this.request = request; } } apply(compiler) { compiler.plugin("compilation", (compilation, params) => { const normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(PrefetchDependency, normalModuleFactory); }); compiler.plugin("make", (compilation, callback) => { compilation.prefetch(this.context || compiler.context, new PrefetchDependency(this.request), callback); }); } }
n/a
class ProgressPlugin { constructor(options) { if(typeof options === "function") { options = { handler: options }; } options = options || {}; this.profile = options.profile; this.handler = options.handler; } apply(compiler) { const handler = this.handler || defaultHandler; const profile = this.profile; if(compiler.compilers) { const states = new Array(compiler.compilers.length); compiler.compilers.forEach(function(compiler, idx) { compiler.apply(new ProgressPlugin(function(p, msg) { states[idx] = Array.prototype.slice.apply(arguments); handler.apply(null, [ states.map(state => state && state[0] || 0).reduce((a, b) => a + b) / states.length, `[${idx}] ${msg}` ].concat(Array.prototype.slice.call(arguments, 2))); })); }); } else { let lastModulesCount = 0; let moduleCount = 500; let doneModules = 0; const activeModules = []; const update = function update(module) { handler( 0.1 + (doneModules / Math.max(lastModulesCount, moduleCount)) * 0.6, "building modules", `${doneModules}/${moduleCount} modules`, `${activeModules.length} active`, activeModules[activeModules.length - 1] ); }; const moduleDone = function moduleDone(module) { doneModules++; const ident = module.identifier(); if(ident) { const idx = activeModules.indexOf(ident); if(idx >= 0) activeModules.splice(idx, 1); } update(); }; compiler.plugin("compilation", function(compilation) { if(compilation.compiler.isChild()) return; lastModulesCount = moduleCount; moduleCount = 0; doneModules = 0; handler(0, "compiling"); compilation.plugin("build-module", function(module) { moduleCount++; const ident = module.identifier(); if(ident) { activeModules.push(ident); } update(); }); compilation.plugin("failed-module", moduleDone); compilation.plugin("succeed-module", moduleDone); const syncHooks = { "seal": [0.71, "sealing"], "optimize": [0.72, "optimizing"], "optimize-modules-basic": [0.73, "basic module optimization"], "optimize-modules": [0.74, "module optimization"], "optimize-modules-advanced": [0.75, "advanced module optimization"], "optimize-chunks-basic": [0.76, "basic chunk optimization"], "optimize-chunks": [0.77, "chunk optimization"], "optimize-chunks-advanced": [0.78, "advanced chunk optimization"], // optimize-tree "revive-modules": [0.80, "module reviving"], "optimize-module-order": [0.81, "module order optimization"], "optimize-module-ids": [0.82, "module id optimization"], "revive-chunks": [0.83, "chunk reviving"], "optimize-chunk-order": [0.84, "chunk order optimization"], "optimize-chunk-ids": [0.85, "chunk id optimization"], "before-hash": [0.86, "hashing"], "before-module-assets": [0.87, "module assets processing"], "before-chunk-assets": [0.88, "chunk assets processing"], "additional-chunk-assets": [0.89, "additional chunk assets processing"], "record": [0.90, "recording"] }; Object.keys(syncHooks).forEach(name => { let pass = 0; const settings = syncHooks[name]; compilation.plugin(name, () => { if(pass++ > 0) handler(settings[0], settings[1], `pass ${pass}`); else handler(settings[0], settings[1]); }); }); compilation.plugin("optimize-tree", (chunks, modules, callback) => { handler(0.79, "module and chunk tree optimization"); callback(); }); compilation.plugin("additional-assets", callback => { handler(0.91, "additional asset processing"); callback(); }); compilation.plugin("optimize-chunk-assets", (chunks, callback) => { handler(0.92, "chunk asset optimization"); callback(); }); compilation.plugin("optimize-assets", (assets, callback) => { handler(0.94, "asset optimization"); callback(); ...
n/a
class ProvidePlugin { constructor(definitions) { this.definitions = definitions; } apply(compiler) { const definitions = this.definitions; compiler.plugin("compilation", (compilation, params) => { compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); params.normalModuleFactory.plugin("parser", (parser, parserOptions) => { Object.keys(definitions).forEach(name => { var request = [].concat(definitions[name]); var splittedName = name.split("."); if(splittedName.length > 0) { splittedName.slice(1).forEach((_, i) => { const name = splittedName.slice(0, i + 1).join("."); parser.plugin(`can-rename ${name}`, ParserHelpers.approve); }); } parser.plugin(`expression ${name}`, function(expr) { let nameIdentifier = name; const scopedName = name.indexOf(".") >= 0; let expression = `require(${JSON.stringify(request[0])})`; if(scopedName) { nameIdentifier = `__webpack_provided_${name.replace(/\./g, "_dot_")}`; } if(request.length > 1) { expression += request.slice(1).map(r => `[${JSON.stringify(r)}]`).join(""); } if(!ParserHelpers.addParsedVariableToModule(this, nameIdentifier, expression)) { return false; } if(scopedName) { ParserHelpers.toConstantDependency(nameIdentifier).bind(this)(expr); } return true; }); }); }); }); } }
n/a
class RequireContextDependency extends ContextDependency { constructor(request, recursive, regExp, range) { super(request, recursive, regExp); this.range = range; } get type() { return "require.context"; } }
n/a
class RequireEnsureDependency extends NullDependency { constructor(block) { super(); this.block = block; } get type() { return "require.ensure"; } }
n/a
class RequireEnsureItemDependency extends ModuleDependency { constructor(request) { super(request); } get type() { return "require.ensure item"; } }
n/a
class RequireHeaderDependency extends NullDependency { constructor(range) { super(); if(!Array.isArray(range)) throw new Error("range must be valid"); this.range = range; } }
n/a
class RequireIncludeDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; } get type() { return "require.include"; } }
n/a
class RequireResolveContextDependency extends ContextDependency { constructor(request, recursive, regExp, range, valueRange) { super(request, recursive, regExp); this.range = range; this.valueRange = valueRange; } get type() { return "amd require context"; } getWarnings() { if(!this.critical) { return; } return [ new CriticalDependencyWarning(this.critical) ]; } }
n/a
class RequireResolveDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; } get type() { return "require.resolve"; } }
n/a
class RequireResolveHeaderDependency extends NullDependency { constructor(range) { super(); if(!Array.isArray(range)) throw new Error("range must be valid"); this.range = range; } }
n/a
class SetVarMainTemplatePlugin { constructor(varExpression, copyObject) { this.varExpression = varExpression; this.copyObject = copyObject; } apply(compilation) { const mainTemplate = compilation.mainTemplate; compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => { const varExpression = mainTemplate.applyPluginsWaterfall("asset-path", this.varExpression, { hash, chunk }); if(this.copyObject) { return new ConcatSource(`(function(e, a) { for(var i in a) e[i] = a[i]; }(${varExpression}, `, source, "))"); } else { const prefix = `${varExpression} =\n`; return new ConcatSource(prefix, source); } }); mainTemplate.plugin("global-hash-paths", (paths) => { if(this.varExpression) paths.push(this.varExpression); return paths; }); mainTemplate.plugin("hash", hash => { hash.update("set var"); hash.update(`${this.varExpression}`); hash.update(`${this.copyObject}`); }); } }
n/a
class SourceMapDevToolPlugin { constructor(options) { if(arguments.length > 1) throw new Error("SourceMapDevToolPlugin only takes one argument (pass an options object)"); // TODO: remove in webpack 3 if(typeof options === "string") { options = { sourceMapFilename: options }; } if(!options) options = {}; this.sourceMapFilename = options.filename; this.sourceMappingURLComment = options.append === false ? false : options.append || "\n//# sourceMappingURL=[url]"; this.moduleFilenameTemplate = options.moduleFilenameTemplate || "webpack:///[resourcePath]"; this.fallbackModuleFilenameTemplate = options.fallbackModuleFilenameTemplate || "webpack:///[resourcePath]?[hash]"; this.options = options; } apply(compiler) { const sourceMapFilename = this.sourceMapFilename; const sourceMappingURLComment = this.sourceMappingURLComment; const moduleFilenameTemplate = this.moduleFilenameTemplate; const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate; const requestShortener = new RequestShortener(compiler.context); const options = this.options; options.test = options.test || /\.(js|css)($|\?)/i; compiler.plugin("compilation", compilation => { new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation); compilation.plugin("after-optimize-chunk-assets", function(chunks) { let allModules = []; let allModuleFilenames = []; const tasks = []; chunks.forEach(function(chunk) { chunk.files.filter(ModuleFilenameHelpers.matchObject.bind(undefined, options)).map(function(file) { const asset = compilation.assets[file]; if(asset.__SourceMapDevToolFile === file && asset.__SourceMapDevToolData) { const data = asset.__SourceMapDevToolData; for(const cachedFile in data) { compilation.assets[cachedFile] = data[cachedFile]; if(cachedFile !== file) chunk.files.push(cachedFile); } return; } let source, sourceMap; if(asset.sourceAndMap) { const sourceAndMap = asset.sourceAndMap(options); sourceMap = sourceAndMap.map; source = sourceAndMap.source; } else { sourceMap = asset.map(options); source = asset.source(); } if(sourceMap) { return { chunk, file, asset, source, sourceMap }; } }).filter(Boolean).map(task => { const modules = task.sourceMap.sources.map(source => { const module = compilation.findModule(source); return module || source; }); const moduleFilenames = modules.map(module => ModuleFilenameHelpers.createFilename(module, moduleFilenameTemplate, requestShortener )); task.modules = modules; task.moduleFilenames = moduleFilenames; return task; }).forEach(task => { allModules = allModules.concat(task.modules); allModuleFilenames = allModuleFilenames.concat(task.moduleFilenames); tasks.push(task); }); }); allModuleFilenames = ModuleFilenameHelpers.replaceDuplicates(allModuleFilenames, (filename, i) => ModuleFilenameHelpers.createFilename (allModules[i], fallbackModuleFilenameTemplate, requestShortener), (ai, bi) => { let a = allModules[ai]; let b = allModules[bi]; a = !a ? "" : typeof a === "string" ? a : a.identifier(); b = !b ? "" : typeof b === "string" ? b : b.identifier(); return a.length - b.length; }); allModuleFilenames = ModuleFilenameHelpers.replaceDuplicates(allModuleFilenames, (filename, i, n) => { for(let j = 0; j < n; j++) filename += "*"; return filename; }); tasks.forEach(task => { task.moduleFilenames = allModuleFilenames.slice(0, task.moduleFilenames.length); allModuleFilenames = allModuleFilenames.slice(task.moduleFilenames.length); }); tasks.forEach(function(task) { const chunk = task.chunk; const file = task.file; const asset = task.asset; const sourceMap = task.sou ...
n/a
class UmdMainTemplatePlugin { constructor(name, options) { this.name = name; this.optionalAmdExternalAsGlobal = options.optionalAmdExternalAsGlobal; this.namedDefine = options.namedDefine; this.auxiliaryComment = options.auxiliaryComment; } apply(compilation) { const mainTemplate = compilation.mainTemplate; compilation.templatesPlugin("render-with-entry", function(source, chunk, hash) { let externals = chunk.modules.filter(m => m.external); const optionalExternals = []; let requiredExternals = []; if(this.optionalAmdExternalAsGlobal) { externals.forEach(m => { if(m.optional) { optionalExternals.push(m); } else { requiredExternals.push(m); } }); externals = requiredExternals.concat(optionalExternals); } else { requiredExternals = externals; } function replaceKeys(str) { return mainTemplate.applyPluginsWaterfall("asset-path", str, { hash, chunk }); } function externalsDepsArray(modules) { return `[${replaceKeys(modules.map(m => JSON.stringify(typeof m.request === "object" ? m.request.amd : m.request)).join(", "))}]`; } function externalsRootArray(modules) { return replaceKeys(modules.map(m => { let request = m.request; if(typeof request === "object") request = request.root; return `root${accessorToObjectAccess([].concat(request))}`; }).join(", ")); } function externalsRequireArray(type) { return replaceKeys(externals.map(m => { let expr; let request = m.request; if(typeof request === "object") request = request[type]; if(Array.isArray(request)) { expr = `require(${JSON.stringify(request[0])})${accessorToObjectAccess(request.slice(1))}`; } else expr = `require(${JSON.stringify(request)})`; if(m.optional) { expr = `(function webpackLoadOptionalExternalModule() { try { return ${expr}; } catch(e) {} }())`; } return expr; }).join(", ")); } function externalsArguments(modules) { return modules.map(m => Template.toIdentifier(`__WEBPACK_EXTERNAL_MODULE_${m.id}__`)).join(", "); } function libraryName(library) { return JSON.stringify(replaceKeys([].concat(library).pop())); } let amdFactory; if(optionalExternals.length > 0) { const wrapperArguments = externalsArguments(requiredExternals); const factoryArguments = requiredExternals.length > 0 ? externalsArguments(requiredExternals) + ", " + externalsRootArray(optionalExternals) : externalsRootArray(optionalExternals); amdFactory = `function webpackLoadOptionalExternalModuleAmd(${wrapperArguments}) {\n` + ` return factory(${factoryArguments});\n` + " }"; } else { amdFactory = "factory"; } return new ConcatSource(new OriginalSource( "(function webpackUniversalModuleDefinition(root, factory) {\n" + (this.auxiliaryComment && typeof this.auxiliaryComment === "string" ? " //" + this.auxiliaryComment + "\n" : this.auxiliaryComment.commonjs2 ? " //" + this.auxiliaryComment.commonjs2 + "\n" : "" ) + " if(typeof exports === 'object' && typeof module === 'object')\n" + " module.exports = factory(" + externalsRequireArray("commonjs2") + ");\n" + (this.auxiliaryComment && typeof this.auxiliaryComment === "string" ? " //" + this.auxiliaryComment + "\n" : this.auxiliaryComment.amd ? " //" + this.auxiliaryComment.amd + "\n" : "" ) + " else if(typeof define === 'function' && define.amd)\n" + (requiredExternals.length > 0 ? (this.name && this.namedDefine === true ? " define(" + libraryName(this.name) + ", " + externalsDepsArray(requiredExternals) + ", " + amdFactory + ");\n" : " define(" + externalsDepsArray(requiredExternals) + ", " + amdFactory + ");\n" ) : (this.name && this.namedDefine === true ? " define(" + libraryName(this.name) + ", [], " + amdFactory + ");\n" : " ...
n/a
class UnsupportedDependency extends NullDependency { constructor(request, range) { super(); this.request = request; this.range = range; } }
n/a
class WatchIgnorePlugin { constructor(paths) { this.paths = paths; } apply(compiler) { compiler.plugin("after-environment", () => { compiler.watchFileSystem = new IgnoringWatchFileSystem(compiler.watchFileSystem, this.paths); }); } }
n/a
class WebpackOptionsApply extends OptionsApply { constructor() { super(); } process(options, compiler) { let ExternalsPlugin; compiler.outputPath = options.output.path; compiler.recordsInputPath = options.recordsInputPath || options.recordsPath; compiler.recordsOutputPath = options.recordsOutputPath || options.recordsPath; compiler.name = options.name; compiler.dependencies = options.dependencies; if(typeof options.target === "string") { let JsonpTemplatePlugin; let NodeSourcePlugin; let NodeTargetPlugin; let NodeTemplatePlugin; switch(options.target) { case "web": JsonpTemplatePlugin = require("./JsonpTemplatePlugin"); NodeSourcePlugin = require("./node/NodeSourcePlugin"); compiler.apply( new JsonpTemplatePlugin(options.output), new FunctionModulePlugin(options.output), new NodeSourcePlugin(options.node), new LoaderTargetPlugin("web") ); break; case "webworker": { let WebWorkerTemplatePlugin = require("./webworker/WebWorkerTemplatePlugin"); NodeSourcePlugin = require("./node/NodeSourcePlugin"); compiler.apply( new WebWorkerTemplatePlugin(), new FunctionModulePlugin(options.output), new NodeSourcePlugin(options.node), new LoaderTargetPlugin("webworker") ); break; } case "node": case "async-node": NodeTemplatePlugin = require("./node/NodeTemplatePlugin"); NodeTargetPlugin = require("./node/NodeTargetPlugin"); compiler.apply( new NodeTemplatePlugin({ asyncChunkLoading: options.target === "async-node" }), new FunctionModulePlugin(options.output), new NodeTargetPlugin(), new LoaderTargetPlugin("node") ); break; case "node-webkit": JsonpTemplatePlugin = require("./JsonpTemplatePlugin"); NodeTargetPlugin = require("./node/NodeTargetPlugin"); 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": case "electron-main": NodeTemplatePlugin = require("./node/NodeTemplatePlugin"); NodeTargetPlugin = require("./node/NodeTargetPlugin"); ExternalsPlugin = require("./ExternalsPlugin"); compiler.apply( new NodeTemplatePlugin({ asyncChunkLoading: true }), new FunctionModulePlugin(options.output), new NodeTargetPlugin(), new ExternalsPlugin("commonjs", [ "app", "auto-updater", "browser-window", "content-tracing", "dialog", "electron", "global-shortcut", "ipc", "ipc-main", "menu", "menu-item", "power-monitor", "power-save-blocker", "protocol", "session", "web-contents", "tray", "clipboard", "crash-reporter", "native-image", "screen", "shell" ]), new LoaderTargetPlugin(options.target) ); break; case "electron-renderer": JsonpTemplatePlugin = require("./JsonpTemplatePlugin"); NodeTargetPlugin = require("./node/NodeTargetPlugin"); ExternalsPlugin = require("./ExternalsPlugin"); compiler.apply( new JsonpTemplatePlugin(options.output), new FunctionModulePlugin(options.output), new NodeTargetPlugin(), new ExternalsPlugin("commonjs", [ "desktop-capturer", "electron", "ipc", "ipc-renderer", "remote", "web-frame", "clipboard", "crash-reporter", "native-image", "screen", "shell" ]), new LoaderTargetPlugin(options.target) ); break; default: throw new Error("Unsupported target '" + options.target + "'."); ...
n/a
class WebpackOptionsDefaulter extends OptionsDefaulter { constructor() { super(); this.set("devtool", false); this.set("cache", true); this.set("context", process.cwd()); this.set("target", "web"); this.set("module.unknownContextRequest", "."); this.set("module.unknownContextRegExp", false); this.set("module.unknownContextRecursive", true); this.set("module.unknownContextCritical", true); this.set("module.exprContextRequest", "."); this.set("module.exprContextRegExp", false); this.set("module.exprContextRecursive", true); this.set("module.exprContextCritical", true); this.set("module.wrappedContextRegExp", /.*/); this.set("module.wrappedContextRecursive", true); this.set("module.wrappedContextCritical", false); this.set("module.strictExportPresence", false); this.set("module.unsafeCache", true); this.set("output", "call", (value, options) => { if(typeof value === "string") { return { filename: value }; } else if(typeof value !== "object") { return {}; } else { return value; } }); this.set("output.filename", "[name].js"); this.set("output.chunkFilename", "make", (options) => { const filename = options.output.filename; return filename.indexOf("[name]") >= 0 ? filename.replace("[name]", "[id]") : "[id]." + filename; }); this.set("output.library", ""); this.set("output.hotUpdateFunction", "make", (options) => { return Template.toIdentifier("webpackHotUpdate" + options.output.library); }); this.set("output.jsonpFunction", "make", (options) => { return Template.toIdentifier("webpackJsonp" + options.output.library); }); this.set("output.libraryTarget", "var"); this.set("output.path", process.cwd()); this.set("output.sourceMapFilename", "[file].map[query]"); this.set("output.hotUpdateChunkFilename", "[id].[hash].hot-update.js"); this.set("output.hotUpdateMainFilename", "[hash].hot-update.json"); this.set("output.crossOriginLoading", false); this.set("output.hashFunction", "md5"); this.set("output.hashDigest", "hex"); this.set("output.hashDigestLength", 20); this.set("output.devtoolLineToLine", false); this.set("output.strictModuleExceptionHandling", false); this.set("node", {}); this.set("node.console", false); this.set("node.process", true); this.set("node.global", true); this.set("node.Buffer", true); this.set("node.setImmediate", true); this.set("node.__filename", "mock"); this.set("node.__dirname", "mock"); this.set("performance.maxAssetSize", 250000); this.set("performance.maxEntrypointSize", 250000); this.set("performance.hints", false); this.set("resolve", {}); this.set("resolve.unsafeCache", true); this.set("resolve.modules", ["node_modules"]); this.set("resolve.extensions", [".js", ".json"]); this.set("resolve.aliasFields", "make", (options) => { if(options.target === "web" || options.target === "webworker") return ["browser"]; else return []; }); this.set("resolve.mainFields", "make", (options) => { if(options.target === "web" || options.target === "webworker") return ["browser", "module", "main"]; else return ["module", "main"]; }); this.set("resolveLoader", {}); this.set("resolveLoader.unsafeCache", true); this.set("resolveLoader.mainFields", ["loader", "main"]); this.set("resolveLoader.extensions", [".js", ".json"]); } }
n/a
class WebpackOptionsValidationError extends WebpackError { constructor(validationErrors) { super(); this.name = "WebpackOptionsValidationError"; this.message = "Invalid configuration object. " + "Webpack has been initialised using a configuration object that does not match the API schema.\n" + validationErrors.map(err => " - " + indent(WebpackOptionsValidationError.formatValidationError(err), " ", false)).join("\n"); this.validationErrors = validationErrors; Error.captureStackTrace(this, this.constructor); } static formatSchema(schema, prevSchemas) { prevSchemas = prevSchemas || []; const formatInnerSchema = (innerSchema, addSelf) => { if(!addSelf) return WebpackOptionsValidationError.formatSchema(innerSchema, prevSchemas); if(prevSchemas.indexOf(innerSchema) >= 0) return "(recursive)"; return WebpackOptionsValidationError.formatSchema(innerSchema, prevSchemas.concat(schema)); }; if(schema.type === "string") { if(schema.minLength === 1) return "non-empty string"; else if(schema.minLength > 1) return `string (min length ${schema.minLength})`; return "string"; } else if(schema.type === "boolean") { return "boolean"; } else if(schema.type === "number") { return "number"; } else if(schema.type === "object") { if(schema.properties) { const required = schema.required || []; return `object { ${Object.keys(schema.properties).map(property => { if(required.indexOf(property) < 0) return property + "?"; return property; }).concat(schema.additionalProperties ? ["..."] : []).join(", ")} }`; } if(schema.additionalProperties) { return `object { <key>: ${formatInnerSchema(schema.additionalProperties)} }`; } return "object"; } else if(schema.type === "array") { return `[${formatInnerSchema(schema.items)}]`; } switch(schema.instanceof) { case "Function": return "function"; case "RegExp": return "RegExp"; } if(schema.$ref) return formatInnerSchema(getSchemaPart(schema.$ref), true); if(schema.allOf) return schema.allOf.map(formatInnerSchema).join(" & "); if(schema.oneOf) return schema.oneOf.map(formatInnerSchema).join(" | "); if(schema.anyOf) return schema.anyOf.map(formatInnerSchema).join(" | "); if(schema.enum) return schema.enum.map(item => JSON.stringify(item)).join(" | "); return JSON.stringify(schema, 0, 2); } static formatValidationError(err) { const dataPath = `configuration${err.dataPath}`; if(err.keyword === "additionalProperties") { const baseMessage = `${dataPath} has an unknown property '${err.params.additionalProperty}'. These properties are valid:\n${getSchemaPartText (err.parentSchema)}`; if(!err.dataPath) { switch(err.params.additionalProperty) { case "debug": return `${baseMessage}\n` + "The 'debug' property was removed in webpack 2.\n" + "Loaders should be updated to allow passing this option via loader options in module.rules.\n" + "Until loaders are updated one can use the LoaderOptionsPlugin to switch loaders into debug mode:\n" + "plugins: [\n" + " new webpack.LoaderOptionsPlugin({\n" + " debug: true\n" + " })\n" + "]"; } return baseMessage + "\n" + "For typos: please correct them.\n" + "For loader options: webpack 2 no longer allows custom properties in configuration.\n" + " Loaders should be updated to allow passing options via loader options in module.rules.\n" + " Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:\n" + " plugins: [\n" + " new webpack.LoaderOptionsPlugin({\n" + " // test: /\\.xxx$/, // may apply this only for some modules\n" + " options: {\n" + ` ${err.params.additionalProperty}: ...\n` + " }\n" + " })\n" + " ]"; } return baseMessage; } else if(err.keyword === "oneOf" || err.keyword === "anyOf") { if(err.children && ...
n/a
validate = function () { [native code] }
n/a
function validateSchema(schema, options) { if(Array.isArray(options)) { const errors = options.map((options) => validateObject(schema, options)); errors.forEach((list, idx) => { list.forEach(function applyPrefix(err) { err.dataPath = `[${idx}]${err.dataPath}`; if(err.children) { err.children.forEach(applyPrefix); } }); }); return errors.reduce((arr, items) => { return arr.concat(items); }, []); } else { return validateObject(schema, options); } }
n/a
function webpack(options, callback) { new WebpackOptionsDefaulter().process(options); const compiler = new Compiler(); compiler.options = options; compiler.options = new WebpackOptionsApply().process(options, compiler); new WebEnvironmentPlugin(options.inputFileSystem, options.outputFileSystem).apply(compiler); if(callback) { compiler.run(callback); } return compiler; }
n/a
class AMDDefineDependency extends NullDependency { constructor(range, arrayRange, functionRange, objectRange, namedModule) { super(); this.range = range; this.arrayRange = arrayRange; this.functionRange = functionRange; this.objectRange = objectRange; this.namedModule = namedModule; } get type() { return "amd define"; } }
n/a
class AMDDefineDependencyTemplate { get definitions() { return { f: [ "var __WEBPACK_AMD_DEFINE_RESULT__;", `!(__WEBPACK_AMD_DEFINE_RESULT__ = #.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` ], o: [ "", "!(module.exports = #)" ], of: [ "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;", `!(__WEBPACK_AMD_DEFINE_FACTORY__ = (#), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` ], af: [ "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_RESULT__ = #.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` ], ao: [ "", "!(#, module.exports = #)" ], aof: [ "var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;", `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))` ], lf: [ "var XXX, XXXmodule;", "!(XXXmodule = { id: YYY, exports: {}, loaded: false }, XXX = #.call(XXXmodule.exports, __webpack_require__, XXXmodule.exports , XXXmodule), XXXmodule.loaded = true, XXX === undefined && (XXX = XXXmodule.exports))" ], lo: [ "var XXX;", "!(XXX = #)" ], lof: [ "var XXX, XXXfactory, XXXmodule;", "!(XXXfactory = (#), (XXXmodule = { id: YYY, exports: {}, loaded: false }), XXX = (typeof XXXfactory === 'function' ? (XXXfactory .call(XXXmodule.exports, __webpack_require__, XXXmodule.exports, XXXmodule)) : XXXfactory), (XXXmodule.loaded = true), XXX === undefined && (XXX = XXXmodule.exports))" ], laf: [ "var __WEBPACK_AMD_DEFINE_ARRAY__, XXX;", "!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, XXX = (#.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)))" ], lao: [ "var XXX;", "!(#, XXX = #)" ], laof: [ "var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_FACTORY__, XXX;", `!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, __WEBPACK_AMD_DEFINE_FACTORY__ = (#), XXX = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__))` ] }; } apply(dependency, source) { const branch = this.branch(dependency); const defAndText = this.definitions[branch]; const definitions = defAndText[0]; const text = defAndText[1]; this.replace(dependency, source, definitions, text); } localModuleVar(dependency) { return dependency.localModule && dependency.localModule.used && dependency.localModule.variableName(); } branch(dependency) { const localModuleVar = this.localModuleVar(dependency) ? "l" : ""; const arrayRange = dependency.arrayRange ? "a" : ""; const objectRange = dependency.objectRange ? "o" : ""; const functionRange = dependency.functionRange ? "f" : ""; return localModuleVar + arrayRange + objectRange + functionRange; } replace(dependency, source, definition, text) { const localModuleVar = this.localModuleVar(dependency); if(localModuleVar) { text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); definition = definition.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); } if(dependency.namedModule) { text = text.replac ...
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class AMDRequireArrayDependency extends Dependency { constructor(depsArray, range) { super(); this.depsArray = depsArray; this.range = range; } get type() { return "amd require array"; } }
n/a
class AMDRequireArrayDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { const content = this.getContent(dep, outputOptions, requestShortener); source.replace(dep.range[0], dep.range[1] - 1, content); } getContent(dep, outputOptions, requestShortener) { const requires = dep.depsArray.map((dependency) => { const optionalComment = this.optionalComment(outputOptions.pathinfo, requestShortener.shorten(dependency.request)); return this.contentForDependency(dependency, optionalComment); }); return `[${requires.join(", ")}]`; } optionalComment(pathInfo, shortenedRequest) { if(!pathInfo) { return ""; } return `/*! ${shortenedRequest} */ `; } contentForDependency(dep, comment) { if(typeof dep === "string") { return dep; } if(dep.module) { const stringifiedId = JSON.stringify(dep.module.id); return `__webpack_require__(${comment}${stringifiedId})`; } return webpackMissingModuleModule(dep.request); } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class AMDRequireContextDependency extends ContextDependency { constructor(request, recursive, regExp, range, valueRange) { super(request, recursive, regExp); this.range = range; this.valueRange = valueRange; } get type() { return "amd require context"; } getWarnings() { if(this.critical) { return [ new CriticalDependencyWarning(this.critical) ]; } } }
n/a
class ContextDependencyTemplateAsRequireCall { apply(dep, source, outputOptions, requestShortener) { const comment = outputOptions.pathinfo ? "/*! " + requestShortener.shorten(dep.request) + " */ " : ""; const containsDeps = dep.module && dep.module.dependencies && dep.module.dependencies.length > 0; const isAsync = dep.module && dep.module.async; if(dep.module && (isAsync || containsDeps)) { if(dep.valueRange) { if(Array.isArray(dep.replaces)) { for(let i = 0; i < dep.replaces.length; i++) { const rep = dep.replaces[i]; source.replace(rep.range[0], rep.range[1] - 1, rep.value); } } 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 { source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")"); } } else { const content = require("./WebpackMissingModule").module(dep.request); source.replace(dep.range[0], dep.range[1] - 1, content); } } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class AMDRequireDependency extends NullDependency { constructor(block) { super(); this.block = block; } }
n/a
class AMDRequireDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { const depBlock = dep.block; const wrapper = DepBlockHelpers.getLoadDepBlockWrapper(depBlock, outputOptions, requestShortener, "require"); // has array range but no function range if(depBlock.arrayRange && !depBlock.functionRange) { const startBlock = wrapper[0] + "function() {"; const endBlock = `;}${wrapper[1]}__webpack_require__.oe${wrapper[2]}`; source.replace(depBlock.outerRange[0], depBlock.arrayRange[0] - 1, startBlock); source.replace(depBlock.arrayRange[1], depBlock.outerRange[1] - 1, endBlock); return; } // has function range but no array range if(depBlock.functionRange && !depBlock.arrayRange) { const startBlock = wrapper[0] + "function() {("; const endBlock = `.call(exports, __webpack_require__, exports, module));}${wrapper[1]}__webpack_require__.oe${wrapper[2]}`; source.replace(depBlock.outerRange[0], depBlock.functionRange[0] - 1, startBlock); source.replace(depBlock.functionRange[1], depBlock.outerRange[1] - 1, endBlock); return; } // has array range, function range, and errorCallbackRange if(depBlock.arrayRange && depBlock.functionRange && depBlock.errorCallbackRange) { const startBlock = wrapper[0] + "function() { "; const errorRangeBlock = `}${depBlock.functionBindThis ? ".bind(this)" : ""}${wrapper[1]}`; const endBlock = `${depBlock.errorCallbackBindThis ? ".bind(this)" : ""}${wrapper[2]}`; source.replace(depBlock.outerRange[0], depBlock.arrayRange[0] - 1, startBlock); source.insert(depBlock.arrayRange[0] + 0.9, "var __WEBPACK_AMD_REQUIRE_ARRAY__ = "); source.replace(depBlock.arrayRange[1], depBlock.functionRange[0] - 1, "; ("); source.insert(depBlock.functionRange[1], ".apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__));"); source.replace(depBlock.functionRange[1], depBlock.errorCallbackRange[0] - 1, errorRangeBlock); source.replace(depBlock.errorCallbackRange[1], depBlock.outerRange[1] - 1, endBlock); return; } // has array range, function range, but no errorCallbackRange if(depBlock.arrayRange && depBlock.functionRange) { const startBlock = wrapper[0] + "function() { "; const endBlock = `}${depBlock.functionBindThis ? ".bind(this)" : ""}${wrapper[1]}__webpack_require__.oe${wrapper[2]}`; source.replace(depBlock.outerRange[0], depBlock.arrayRange[0] - 1, startBlock); source.insert(depBlock.arrayRange[0] + 0.9, "var __WEBPACK_AMD_REQUIRE_ARRAY__ = "); source.replace(depBlock.arrayRange[1], depBlock.functionRange[0] - 1, "; ("); source.insert(depBlock.functionRange[1], ".apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__));"); source.replace(depBlock.functionRange[1], depBlock.outerRange[1] - 1, endBlock); } } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class AMDRequireItemDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; } get type() { return "amd require"; } }
n/a
class ModuleDependencyTemplateAsRequireId { apply(dep, source, outputOptions, requestShortener) { if(!dep.range) return; const comment = outputOptions.pathinfo ? `/*! ${requestShortener.shorten(dep.request)} */ ` : ""; let content; if(dep.module) content = `__webpack_require__(${comment}${JSON.stringify(dep.module.id)})`; else content = require("./WebpackMissingModule").module(dep.request); source.replace(dep.range[0], dep.range[1] - 1, content); } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class CommonJsRequireContextDependency extends ContextDependency { constructor(request, recursive, regExp, range, valueRange) { super(request, recursive, regExp); this.range = range; this.valueRange = valueRange; } get type() { return "cjs require context"; } getWarnings() { if(!this.critical) { return; } return [ new CriticalDependencyWarning(this.critical) ]; } }
n/a
class ContextDependencyTemplateAsRequireCall { apply(dep, source, outputOptions, requestShortener) { const comment = outputOptions.pathinfo ? "/*! " + requestShortener.shorten(dep.request) + " */ " : ""; const containsDeps = dep.module && dep.module.dependencies && dep.module.dependencies.length > 0; const isAsync = dep.module && dep.module.async; if(dep.module && (isAsync || containsDeps)) { if(dep.valueRange) { if(Array.isArray(dep.replaces)) { for(let i = 0; i < dep.replaces.length; i++) { const rep = dep.replaces[i]; source.replace(rep.range[0], rep.range[1] - 1, rep.value); } } 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 { source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")"); } } else { const content = require("./WebpackMissingModule").module(dep.request); source.replace(dep.range[0], dep.range[1] - 1, content); } } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class CommonJsRequireDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; } get type() { return "cjs require"; } }
n/a
class ModuleDependencyTemplateAsId { apply(dep, source, outputOptions, requestShortener) { if(!dep.range) return; const comment = outputOptions.pathinfo ? `/*! ${requestShortener.shorten(dep.request)} */ ` : ""; let content; if(dep.module) content = comment + JSON.stringify(dep.module.id); else content = require("./WebpackMissingModule").module(dep.request); source.replace(dep.range[0], dep.range[1] - 1, content); } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
function Compiler() { Tapable.call(this); this.outputPath = ""; this.outputFileSystem = null; this.inputFileSystem = null; this.recordsInputPath = null; this.recordsOutputPath = null; this.records = {}; this.fileTimestamps = {}; this.contextTimestamps = {}; this.resolvers = { normal: null, loader: null, context: null }; var deprecationReported = false; this.parser = { plugin: function(hook, fn) { if(!deprecationReported) { console.warn("webpack: Using compiler.parser is deprecated.\n" + "Use compiler.plugin(\"compilation\", function(compilation, data) {\n data.normalModuleFactory.plugin(\"parser\", function (parser, options) { parser.plugin(/* ... */); });\n}); instead. " + "It was called " + new Error().stack.split("\n")[2].trim() + "."); deprecationReported = true; } this.plugin("compilation", function(compilation, data) { data.normalModuleFactory.plugin("parser", function(parser) { parser.plugin(hook, fn); }); }); }.bind(this), apply: function() { var args = arguments; if(!deprecationReported) { console.warn("webpack: Using compiler.parser is deprecated.\n" + "Use compiler.plugin(\"compilation\", function(compilation, data) {\n data.normalModuleFactory.plugin(\"parser\", function (parser, options) { parser.apply(/* ... */); });\n}); instead. " + "It was called " + new Error().stack.split("\n")[2].trim() + "."); deprecationReported = true; } this.plugin("compilation", function(compilation, data) { data.normalModuleFactory.plugin("parser", function(parser) { parser.apply.apply(parser, args); }); }); }.bind(this) }; this.options = {}; }
n/a
function Watching(compiler, watchOptions, handler) { this.startTime = null; this.invalid = false; this.error = null; this.stats = null; this.handler = handler; this.closed = false; if(typeof watchOptions === "number") { this.watchOptions = { aggregateTimeout: watchOptions }; } else if(watchOptions && typeof watchOptions === "object") { this.watchOptions = Object.assign({}, watchOptions); } else { this.watchOptions = {}; } this.watchOptions.aggregateTimeout = this.watchOptions.aggregateTimeout || 200; this.compiler = compiler; this.running = true; this.compiler.readRecords(function(err) { if(err) return this._done(err); this._go(); }.bind(this)); }
n/a
function Watching(compiler, watchOptions, handler) { this.startTime = null; this.invalid = false; this.error = null; this.stats = null; this.handler = handler; this.closed = false; if(typeof watchOptions === "number") { this.watchOptions = { aggregateTimeout: watchOptions }; } else if(watchOptions && typeof watchOptions === "object") { this.watchOptions = Object.assign({}, watchOptions); } else { this.watchOptions = {}; } this.watchOptions.aggregateTimeout = this.watchOptions.aggregateTimeout || 200; this.compiler = compiler; this.running = true; this.compiler.readRecords(function(err) { if(err) return this._done(err); this._go(); }.bind(this)); }
n/a
_done = function (err, compilation) { this.running = false; if(this.invalid) return this._go(); this.error = err || null; this.stats = compilation ? compilation.getStats() : null; if(this.stats) { this.stats.startTime = this.startTime; this.stats.endTime = new Date().getTime(); } 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 && !this.closed) this.watch(compilation.fileDependencies, compilation.contextDependencies, compilation.missingDependencies); }
...
} else {
this.watchOptions = {};
}
this.watchOptions.aggregateTimeout = this.watchOptions.aggregateTimeout || 200;
this.compiler = compiler;
this.running = true;
this.compiler.readRecords(function(err) {
if(err) return this._done(err);
this._go();
}.bind(this));
}
Watching.prototype._go = function() {
var self = this;
...
_go = function () { var self = this; self.startTime = new Date().getTime(); self.running = true; self.invalid = false; self.compiler.applyPluginsAsync("watch-run", self, function(err) { if(err) return self._done(err); self.compiler.compile(function onCompiled(err, compilation) { if(err) return self._done(err); if(self.invalid) return self._done(); if(self.compiler.applyPluginsBailResult("should-emit", compilation) === false) { return self._done(null, compilation); } self.compiler.emitAssets(compilation, function(err) { if(err) return self._done(err); if(self.invalid) return self._done(); self.compiler.emitRecords(function(err) { if(err) return self._done(err); if(compilation.applyPluginsBailResult("need-additional-pass")) { compilation.needAdditionalPass = true; var stats = compilation.getStats(); stats.startTime = self.startTime; stats.endTime = new Date().getTime(); self.compiler.applyPlugins("done", stats); self.compiler.applyPluginsAsync("additional-pass", function(err) { if(err) return self._done(err); self.compiler.compile(onCompiled); }); return; } return self._done(null, compilation); }); }); }); }); }
...
}
this.watchOptions.aggregateTimeout = this.watchOptions.aggregateTimeout || 200;
this.compiler = compiler;
this.running = true;
this.compiler.readRecords(function(err) {
if(err) return this._done(err);
this._go();
}.bind(this));
}
Watching.prototype._go = function() {
var self = this;
self.startTime = new Date().getTime();
self.running = true;
...
close = function (callback) { if(callback === undefined) callback = function() {}; this.closed = true; if(this.watcher) { this.watcher.close(); this.watcher = null; } if(this.pausedWatcher) { this.pausedWatcher.close(); this.pausedWatcher = null; } if(this.running) { this.invalid = true; this._done = () => { this.compiler.applyPlugins("watch-close"); callback(); }; } else { this.compiler.applyPlugins("watch-close"); callback(); } }
...
};
Watching.prototype.close = function(callback) {
if(callback === undefined) callback = function() {};
this.closed = true;
if(this.watcher) {
this.watcher.close();
this.watcher = null;
}
if(this.pausedWatcher) {
this.pausedWatcher.close();
this.pausedWatcher = null;
}
if(this.running) {
...
invalidate = function () { if(this.watcher) { this.pausedWatcher = this.watcher; this.watcher.pause(); this.watcher = null; } if(this.running) { this.invalid = true; return false; } else { this._go(); } }
...
this.watcher = this.compiler.watchFileSystem.watch(files, dirs, missing, this.startTime, this.watchOptions, function(err, filesModified
, contextModified, missingModified, fileTimestamps, contextTimestamps) {
this.pausedWatcher = this.watcher;
this.watcher = null;
if(err) return this.handler(err);
this.compiler.fileTimestamps = fileTimestamps;
this.compiler.contextTimestamps = contextTimestamps;
this.invalidate();
}.bind(this), function(fileName, changeTime) {
this.compiler.applyPlugins("invalid", fileName, changeTime);
}.bind(this));
};
Watching.prototype.invalidate = function() {
if(this.watcher) {
...
watch = function (files, dirs, missing) { this.pausedWatcher = null; this.watcher = this.compiler.watchFileSystem.watch(files, dirs, missing, this.startTime, this.watchOptions, function(err, filesModified , contextModified, missingModified, fileTimestamps, contextTimestamps) { this.pausedWatcher = this.watcher; this.watcher = null; if(err) return this.handler(err); this.compiler.fileTimestamps = fileTimestamps; this.compiler.contextTimestamps = contextTimestamps; this.invalidate(); }.bind(this), function(fileName, changeTime) { this.compiler.applyPlugins("invalid", fileName, changeTime); }.bind(this)); }
...
var watchOptions = firstOptions.watchOptions || firstOptions.watch || options.watch || {};
if(watchOptions.stdin) {
process.stdin.on("end", function() {
process.exit(0); // eslint-disable-line
});
process.stdin.resume();
}
compiler.watch(watchOptions, compilerCallback);
console.log("\nWebpack is watching the files…\n");
} else
compiler.run(compilerCallback);
}
processOptions(options);
...
compile = function (callback) { var self = this; var params = self.newCompilationParams(); self.applyPluginsAsync("before-compile", params, function(err) { if(err) return callback(err); self.applyPlugins("compile", params); var compilation = self.newCompilation(params); self.applyPluginsParallel("make", compilation, function(err) { if(err) return callback(err); compilation.finish(); compilation.seal(function(err) { if(err) return callback(err); self.applyPluginsAsync("after-compile", compilation, function(err) { if(err) return callback(err); return callback(null, compilation); }); }); }); }); }
...
Watching.prototype._go = function() {
var self = this;
self.startTime = new Date().getTime();
self.running = true;
self.invalid = false;
self.compiler.applyPluginsAsync("watch-run", self, function(err) {
if(err) return self._done(err);
self.compiler.compile(function onCompiled(err, compilation) {
if(err) return self._done(err);
if(self.invalid) return self._done();
if(self.compiler.applyPluginsBailResult("should-emit", compilation) === false) {
return self._done(null, compilation);
}
...
function Compiler() { Tapable.call(this); this.outputPath = ""; this.outputFileSystem = null; this.inputFileSystem = null; this.recordsInputPath = null; this.recordsOutputPath = null; this.records = {}; this.fileTimestamps = {}; this.contextTimestamps = {}; this.resolvers = { normal: null, loader: null, context: null }; var deprecationReported = false; this.parser = { plugin: function(hook, fn) { if(!deprecationReported) { console.warn("webpack: Using compiler.parser is deprecated.\n" + "Use compiler.plugin(\"compilation\", function(compilation, data) {\n data.normalModuleFactory.plugin(\"parser\", function (parser, options) { parser.plugin(/* ... */); });\n}); instead. " + "It was called " + new Error().stack.split("\n")[2].trim() + "."); deprecationReported = true; } this.plugin("compilation", function(compilation, data) { data.normalModuleFactory.plugin("parser", function(parser) { parser.plugin(hook, fn); }); }); }.bind(this), apply: function() { var args = arguments; if(!deprecationReported) { console.warn("webpack: Using compiler.parser is deprecated.\n" + "Use compiler.plugin(\"compilation\", function(compilation, data) {\n data.normalModuleFactory.plugin(\"parser\", function (parser, options) { parser.apply(/* ... */); });\n}); instead. " + "It was called " + new Error().stack.split("\n")[2].trim() + "."); deprecationReported = true; } this.plugin("compilation", function(compilation, data) { data.normalModuleFactory.plugin("parser", function(parser) { parser.apply.apply(parser, args); }); }); }.bind(this) }; this.options = {}; }
n/a
createChildCompiler = function (compilation, compilerName, outputOptions, plugins) { var childCompiler = new Compiler(); if(Array.isArray(plugins)) { plugins.forEach(plugin => childCompiler.apply(plugin)); } 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; childCompiler.outputPath = this.outputPath; childCompiler.inputFileSystem = this.inputFileSystem; childCompiler.outputFileSystem = null; childCompiler.resolvers = this.resolvers; childCompiler.fileTimestamps = this.fileTimestamps; childCompiler.contextTimestamps = this.contextTimestamps; 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) { childCompiler.options.output[name] = outputOptions[name]; } childCompiler.parentCompilation = compilation; return childCompiler; }
...
}
getStats() {
return new Stats(this);
}
createChildCompiler(name, outputOptions) {
return this.compiler.createChildCompiler(this, name, outputOptions);
}
checkConstraints() {
const usedIds = {};
const modules = this.modules;
for(let indexModule = 0; indexModule < modules.length; indexModule++) {
...
createCompilation = function () { return new Compilation(this); }
...
};
Compiler.prototype.createCompilation = function() {
return new Compilation(this);
};
Compiler.prototype.newCompilation = function(params) {
var compilation = this.createCompilation();
compilation.fileTimestamps = this.fileTimestamps;
compilation.contextTimestamps = this.contextTimestamps;
compilation.name = this.name;
compilation.records = this.records;
compilation.compilationDependencies = params.compilationDependencies;
this.applyPlugins("this-compilation", compilation, params);
this.applyPlugins("compilation", compilation, params);
...
createContextModuleFactory = function () { var contextModuleFactory = new ContextModuleFactory(this.resolvers, this.inputFileSystem); this.applyPlugins("context-module-factory", contextModuleFactory); return contextModuleFactory; }
...
this.applyPlugins("context-module-factory", contextModuleFactory);
return contextModuleFactory;
};
Compiler.prototype.newCompilationParams = function() {
var params = {
normalModuleFactory: this.createNormalModuleFactory(),
contextModuleFactory: this.createContextModuleFactory(),
compilationDependencies: []
};
return params;
};
Compiler.prototype.compile = function(callback) {
var self = this;
...
createNormalModuleFactory = function () { var normalModuleFactory = new NormalModuleFactory(this.options.context, this.resolvers, this.options.module || {}); this.applyPlugins("normal-module-factory", normalModuleFactory); return normalModuleFactory; }
...
var contextModuleFactory = new ContextModuleFactory(this.resolvers, this.inputFileSystem);
this.applyPlugins("context-module-factory", contextModuleFactory);
return contextModuleFactory;
};
Compiler.prototype.newCompilationParams = function() {
var params = {
normalModuleFactory: this.createNormalModuleFactory(),
contextModuleFactory: this.createContextModuleFactory(),
compilationDependencies: []
};
return params;
};
Compiler.prototype.compile = function(callback) {
...
emitAssets = function (compilation, callback) { var outputPath; this.applyPluginsAsync("emit", compilation, function(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); require("async").forEach(Object.keys(compilation.assets), function(file, callback) { var targetFile = file; var queryStringIdx = targetFile.indexOf("?"); if(queryStringIdx >= 0) { targetFile = targetFile.substr(0, queryStringIdx); } 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); var targetPath = this.outputFileSystem.join(outputPath, targetFile); var source = compilation.assets[file]; if(source.existsAt === targetPath) { source.emitted = false; return callback(); } var content = source.source(); if(!Buffer.isBuffer(content)) { content = new Buffer(content, "utf8"); //eslint-disable-line } source.existsAt = targetPath; source.emitted = true; this.outputFileSystem.writeFile(targetPath, content, callback); } }.bind(this), function(err) { if(err) return callback(err); afterEmit.call(this); }.bind(this)); } function afterEmit() { this.applyPluginsAsyncSeries1("after-emit", compilation, function(err) { if(err) return callback(err); return callback(); }); } }
...
if(err) return self._done(err);
if(self.invalid) return self._done();
if(self.compiler.applyPluginsBailResult("should-emit", compilation) === false) {
return self._done(null, compilation);
}
self.compiler.emitAssets(compilation, function(err) {
if(err) return self._done(err);
if(self.invalid) return self._done();
self.compiler.emitRecords(function(err) {
if(err) return self._done(err);
if(compilation.applyPluginsBailResult("need-additional-pass")) {
...
function emitRecords(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); this.outputFileSystem.mkdirp(recordsOutputPathDirectory, function(err) { if(err) return callback(err); writeFile.call(this); }.bind(this)); function writeFile() { this.outputFileSystem.writeFile(this.recordsOutputPath, JSON.stringify(this.records, undefined, 2), callback); } }
...
return self._done(null, compilation);
}
self.compiler.emitAssets(compilation, function(err) {
if(err) return self._done(err);
if(self.invalid) return self._done();
self.compiler.emitRecords(function(err) {
if(err) return self._done(err);
if(compilation.applyPluginsBailResult("need-additional-pass")) {
compilation.needAdditionalPass = true;
var stats = compilation.getStats();
stats.startTime = self.startTime;
...
isChild = function () { return !!this.parentCompilation; }
...
if(ident) {
const idx = activeModules.indexOf(ident);
if(idx >= 0) activeModules.splice(idx, 1);
}
update();
};
compiler.plugin("compilation", function(compilation) {
if(compilation.compiler.isChild()) return;
lastModulesCount = moduleCount;
moduleCount = 0;
doneModules = 0;
handler(0, "compiling");
compilation.plugin("build-module", function(module) {
moduleCount++;
const ident = module.identifier();
...
newCompilation = function (params) { var compilation = this.createCompilation(); compilation.fileTimestamps = this.fileTimestamps; compilation.contextTimestamps = this.contextTimestamps; compilation.name = this.name; compilation.records = this.records; compilation.compilationDependencies = params.compilationDependencies; this.applyPlugins("this-compilation", compilation, params); this.applyPlugins("compilation", compilation, params); return compilation; }
...
var self = this;
var params = self.newCompilationParams();
self.applyPluginsAsync("before-compile", params, function(err) {
if(err) return callback(err);
self.applyPlugins("compile", params);
var compilation = self.newCompilation(params);
self.applyPluginsParallel("make", compilation, function(err) {
if(err) return callback(err);
compilation.finish();
compilation.seal(function(err) {
...
newCompilationParams = function () { var params = { normalModuleFactory: this.createNormalModuleFactory(), contextModuleFactory: this.createContextModuleFactory(), compilationDependencies: [] }; return params; }
...
compilationDependencies: []
};
return params;
};
Compiler.prototype.compile = function(callback) {
var self = this;
var params = self.newCompilationParams();
self.applyPluginsAsync("before-compile", params, function(err) {
if(err) return callback(err);
self.applyPlugins("compile", params);
var compilation = self.newCompilation(params);
...
purgeInputFileSystem = function () { if(this.inputFileSystem && this.inputFileSystem.purge) this.inputFileSystem.purge(); }
...
profile: argv.profile
}));
}
function compilerCallback(err, stats) {
if(!options.watch || err) {
// Do not keep cache anymore
compiler.purgeInputFileSystem();
}
if(err) {
lastHash = null;
console.error(err.stack || err);
if(err.details) console.error(err.details);
process.exit(1); // eslint-disable-line
}
...
function readRecords(callback) { var self = this; if(!self.recordsInputPath) { self.records = {}; return callback(); } self.inputFileSystem.stat(self.recordsInputPath, function(err) { // It doesn't exist // We can ignore self. if(err) return callback(); self.inputFileSystem.readFile(self.recordsInputPath, function(err, content) { if(err) return callback(err); try { self.records = JSON.parse(content.toString("utf-8")); } catch(e) { e.message = "Cannot parse records: " + e.message; return callback(e); } return callback(); }); }); }
...
this.watchOptions = Object.assign({}, watchOptions);
} else {
this.watchOptions = {};
}
this.watchOptions.aggregateTimeout = this.watchOptions.aggregateTimeout || 200;
this.compiler = compiler;
this.running = true;
this.compiler.readRecords(function(err) {
if(err) return this._done(err);
this._go();
}.bind(this));
}
Watching.prototype._go = function() {
...
run = function (callback) { var self = this; var startTime = new Date().getTime(); self.applyPluginsAsync("before-run", self, function(err) { if(err) return callback(err); self.applyPluginsAsync("run", self, function(err) { if(err) return callback(err); self.readRecords(function(err) { if(err) return callback(err); self.compile(function onCompiled(err, compilation) { if(err) return callback(err); if(self.applyPluginsBailResult("should-emit", compilation) === false) { var stats = compilation.getStats(); stats.startTime = startTime; stats.endTime = new Date().getTime(); self.applyPlugins("done", stats); return callback(null, stats); } self.emitAssets(compilation, function(err) { if(err) return callback(err); if(compilation.applyPluginsBailResult("need-additional-pass")) { compilation.needAdditionalPass = true; var stats = compilation.getStats(); stats.startTime = startTime; stats.endTime = new Date().getTime(); self.applyPlugins("done", stats); self.applyPluginsAsync("additional-pass", function(err) { if(err) return callback(err); self.compile(onCompiled); }); return; } self.emitRecords(function(err) { if(err) return callback(err); var stats = compilation.getStats(); stats.startTime = startTime; stats.endTime = new Date().getTime(); self.applyPlugins("done", stats); return callback(null, stats); }); }); }); }); }); }); }
...
process.exit(0); // eslint-disable-line
});
process.stdin.resume();
}
compiler.watch(watchOptions, compilerCallback);
console.log("\nWebpack is watching the files…\n");
} else
compiler.run(compilerCallback);
}
processOptions(options);
...
runAsChild = function (callback) { this.compile(function(err, compilation) { if(err) return callback(err); this.parentCompilation.children.push(compilation); Object.keys(compilation.assets).forEach(function(name) { this.parentCompilation.assets[name] = compilation.assets[name]; }.bind(this)); var entries = Object.keys(compilation.entrypoints).map(function(name) { return compilation.entrypoints[name].chunks; }).reduce(function(array, chunks) { return array.concat(chunks); }, []); return callback(null, entries, compilation); }.bind(this)); }
n/a
watch = function (watchOptions, handler) { this.fileTimestamps = {}; this.contextTimestamps = {}; var watching = new Watching(this, watchOptions, handler); return watching; }
...
var watchOptions = firstOptions.watchOptions || firstOptions.watch || options.watch || {};
if(watchOptions.stdin) {
process.stdin.on("end", function() {
process.exit(0); // eslint-disable-line
});
process.stdin.resume();
}
compiler.watch(watchOptions, compilerCallback);
console.log("\nWebpack is watching the files…\n");
} else
compiler.run(compilerCallback);
}
processOptions(options);
...
class ConstDependency extends NullDependency { constructor(expression, range) { super(); this.expression = expression; this.range = range; } updateHash(hash) { hash.update(this.range + ""); hash.update(this.expression + ""); } }
n/a
class ConstDependencyTemplate { apply(dep, source) { if(typeof dep.range === "number") { source.insert(dep.range, dep.expression); return; } source.replace(dep.range[0], dep.range[1] - 1, dep.expression); } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
create = function (Dep, range, param, expr, options, chunkName) { let dep; let prefix; let postfix; let prefixRange; let valueRange; let idx; let context; let regExp; if(param.isTemplateString()) { prefix = param.quasis[0].string; postfix = param.quasis.length > 1 ? param.quasis[param.quasis.length - 1].string : ""; prefixRange = [param.quasis[0].range[0], param.quasis[0].range[1]]; valueRange = param.range; idx = prefix.lastIndexOf("/"); context = "."; if(idx >= 0) { context = prefix.substr(0, idx); prefix = `.${prefix.substr(idx)}`; } // If there are more than two quasis, maybe the generated RegExp can be more precise? regExp = new RegExp(`^${quotemeta(prefix)}${options.wrappedContextRegExp.source}${quotemeta(postfix)}$`); dep = new Dep(context, options.wrappedContextRecursive, regExp, range, valueRange, chunkName); dep.loc = expr.loc; dep.replaces = [{ range: prefixRange, value: prefix }]; dep.critical = options.wrappedContextCritical && "a part of the request of a dependency is an expression"; return dep; } else if(param.isWrapped() && (param.prefix && param.prefix.isString() || param.postfix && param.postfix.isString())) { prefix = param.prefix && param.prefix.isString() ? param.prefix.string : ""; postfix = param.postfix && param.postfix.isString() ? param.postfix.string : ""; prefixRange = param.prefix && param.prefix.isString() ? param.prefix.range : null; valueRange = [prefixRange ? prefixRange[1] : param.range[0], param.range[1]]; idx = prefix.lastIndexOf("/"); context = "."; if(idx >= 0) { context = prefix.substr(0, idx); prefix = `.${prefix.substr(idx)}`; } regExp = new RegExp(`^${quotemeta(prefix)}${options.wrappedContextRegExp.source}${quotemeta(postfix)}$`); dep = new Dep(context, options.wrappedContextRecursive, regExp, range, valueRange, chunkName); dep.loc = expr.loc; dep.prepend = param.prefix && param.prefix.isString() ? prefix : null; dep.critical = options.wrappedContextCritical && "a part of the request of a dependency is an expression"; return dep; } else { dep = new Dep(options.exprContextRequest, options.exprContextRecursive, options.exprContextRegExp, range, param.range, chunkName ); dep.loc = expr.loc; dep.critical = options.exprContextCritical && "the request of a dependency is an expression"; return dep; } }
...
var outputOptions = options.stats;
if(typeof outputOptions === "boolean" || typeof outputOptions === "string") {
outputOptions = statsPresetToOptions(outputOptions);
} else if(!outputOptions) {
outputOptions = {};
}
outputOptions = Object.create(outputOptions);
if(Array.isArray(options) && !outputOptions.children) {
outputOptions.children = options.map(o => o.stats);
}
if(typeof outputOptions.context === "undefined")
outputOptions.context = firstOptions.context;
ifArg("json", function(bool) {
...
function ContextModuleFactory(resolvers) { Tapable.call(this); this.resolvers = resolvers; }
n/a
function ContextModuleFactory(resolvers) { Tapable.call(this); this.resolvers = resolvers; }
n/a
create = function (data, callback) { var module = this; var context = data.context; var dependencies = data.dependencies; var dependency = dependencies[0]; this.applyPluginsAsyncWaterfall("before-resolve", { context: context, request: dependency.request, recursive: dependency.recursive, regExp: dependency.regExp, async: dependency.async, dependencies: dependencies }, function(err, result) { if(err) return callback(err); // Ignored if(!result) return callback(); var context = result.context; var request = result.request; var recursive = result.recursive; var regExp = result.regExp; var asyncContext = result.async; var dependencies = result.dependencies; var loaders, resource, loadersPrefix = ""; var idx = request.lastIndexOf("!"); if(idx >= 0) { loaders = request.substr(0, idx + 1); for(var i = 0; i < loaders.length && loaders[i] === "!"; i++) { loadersPrefix += "!"; } loaders = loaders.substr(i).replace(/!+$/, "").replace(/!!+/g, "!"); if(loaders === "") loaders = []; else loaders = loaders.split("!"); resource = request.substr(idx + 1); } else { loaders = []; resource = request; } var resolvers = module.resolvers; asyncLib.parallel([ function(callback) { resolvers.context.resolve({}, context, resource, function(err, result) { if(err) return callback(err); callback(null, result); }); }, function(callback) { asyncLib.map(loaders, function(loader, callback) { resolvers.loader.resolve({}, context, loader, function(err, result) { if(err) return callback(err); callback(null, result); }); }, callback); } ], function(err, result) { if(err) return callback(err); module.applyPluginsAsyncWaterfall("after-resolve", { loaders: loadersPrefix + result[1].join("!") + (result[1].length > 0 ? "!" : ""), resource: result[0], recursive: recursive, regExp: regExp, async: asyncContext, dependencies: dependencies, resolveDependencies: module.resolveDependencies.bind(module) }, function(err, result) { if(err) return callback(err); // Ignored if(!result) return callback(); return callback(null, new ContextModule(result.resolveDependencies, result.resource, result.recursive, result.regExp, result .loaders, result.async, dependency.chunkName)); }); }); }); }
...
var outputOptions = options.stats;
if(typeof outputOptions === "boolean" || typeof outputOptions === "string") {
outputOptions = statsPresetToOptions(outputOptions);
} else if(!outputOptions) {
outputOptions = {};
}
outputOptions = Object.create(outputOptions);
if(Array.isArray(options) && !outputOptions.children) {
outputOptions.children = options.map(o => o.stats);
}
if(typeof outputOptions.context === "undefined")
outputOptions.context = firstOptions.context;
ifArg("json", function(bool) {
...
function resolveDependencies(fs, resource, recursive, regExp, callback) { if(!regExp || !resource) return callback(null, []); (function addDirectory(directory, callback) { fs.readdir(directory, function(err, files) { if(err) return callback(err); if(!files || files.length === 0) return callback(null, []); asyncLib.map(files.filter(function(p) { return p.indexOf(".") !== 0; }), function(seqment, callback) { var subResource = path.join(directory, seqment); fs.stat(subResource, function(err, stat) { if(err) return callback(err); if(stat.isDirectory()) { if(!recursive) return callback(); addDirectory.call(this, subResource, callback); } 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); alternatives = alternatives.filter(function(obj) { return regExp.test(obj.request); }).map(function(obj) { var dep = new ContextElementDependency(obj.request); dep.optional = true; return dep; }); callback(null, alternatives); }); } else callback(); }.bind(this)); }.bind(this), function(err, result) { if(err) return callback(err); if(!result) return callback(null, []); callback(null, result.filter(function(i) { return !!i; }).reduce(function(a, i) { return a.concat(i); }, [])); }); }.bind(this)); }.call(this, resource, callback)); }
...
this.built = false;
super.unbuild();
}
build(options, compilation, resolver, fs, callback) {
this.built = true;
this.builtTime = new Date().getTime();
this.resolveDependencies(fs, this.context, this.recursive, this.regExp, (err, dependencies
) => {
if(err) return callback(err);
if(!dependencies) {
this.dependencies = [];
callback();
return;
}
...
getDepBlockPromise = function (depBlock, outputOptions, requestShortener, name) { if(depBlock.chunks) { var chunks = depBlock.chunks.filter(function(chunk) { return !chunk.hasRuntime() && chunk.id !== null; }); if(chunks.length === 1) { var chunk = chunks[0]; return "__webpack_require__.e" + asComment(name) + "(" + JSON.stringify(chunk.id) + "" + (outputOptions.pathinfo && depBlock.chunkName ? "/*! " + requestShortener.shorten(depBlock.chunkName) + " */" : "") + asComment(depBlock.chunkReason) + ")"; } else if(chunks.length > 0) { return "Promise.all" + asComment(name) + "(" + (outputOptions.pathinfo && depBlock.chunkName ? "/*! " + requestShortener.shorten(depBlock.chunkName) + " */" : "") + "[" + chunks.map(function(chunk) { return "__webpack_require__.e(" + JSON.stringify(chunk.id) + ")"; }).join(", ") + "])"; } } return "Promise.resolve()"; }
...
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var DepBlockHelpers = exports;
DepBlockHelpers.getLoadDepBlockWrapper = function(depBlock, outputOptions, requestShortener, name) {
var promiseCode = DepBlockHelpers.getDepBlockPromise(depBlock, outputOptions, requestShortener
, name);
return [
promiseCode + ".then(",
").catch(",
")"
];
};
...
getLoadDepBlockWrapper = function (depBlock, outputOptions, requestShortener, name) { var promiseCode = DepBlockHelpers.getDepBlockPromise(depBlock, outputOptions, requestShortener, name); return [ promiseCode + ".then(", ").catch(", ")" ]; }
...
this.block = block;
}
}
AMDRequireDependency.Template = class AMDRequireDependencyTemplate {
apply(dep, source, outputOptions, requestShortener) {
const depBlock = dep.block;
const wrapper = DepBlockHelpers.getLoadDepBlockWrapper(depBlock, outputOptions, requestShortener
, "require");
// has array range but no function range
if(depBlock.arrayRange && !depBlock.functionRange) {
const startBlock = wrapper[0] + "function() {";
const endBlock = `;}${wrapper[1]}__webpack_require__.oe${wrapper[2]}`;
source.replace(depBlock.outerRange[0], depBlock.arrayRange[0] - 1, startBlock);
source.replace(depBlock.arrayRange[1], depBlock.outerRange[1] - 1, endBlock);
...
class Dependency { constructor() { this.module = null; } isEqualResource() { return false; } // Returns the referenced module and export getReference() { if(!this.module) return null; return { module: this.module, importedNames: true, // true: full object, false: only sideeffects/no export, array of strings: the exports with this names }; } // Returns the exported names getExports() { return null; } getWarnings() { return null; } getErrors() { return null; } updateHash(hash) { hash.update((this.module && this.module.id) + ""); } disconnect() { this.module = null; } // TODO: remove in webpack 3 compare(a, b) { return compareLocations(a.loc, b.loc); } }
n/a
(a, b) => compareLocations(a.loc, b.loc)
n/a
class DynamicEntryPlugin { constructor(context, entry) { this.context = context; this.entry = entry; } apply(compiler) { compiler.plugin("compilation", (compilation, params) => { const multiModuleFactory = new MultiModuleFactory(); const normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(MultiEntryDependency, multiModuleFactory); compilation.dependencyFactories.set(SingleEntryDependency, normalModuleFactory); }); compiler.plugin("make", (compilation, callback) => { const addEntry = (entry, name) => { const dep = DynamicEntryPlugin.createDependency(entry, name); return new Promise((resolve, reject) => { compilation.addEntry(this.context, dep, name, (err) => { if(err) return reject(err); resolve(); }); }); }; Promise.resolve(this.entry()).then((entry) => { if(typeof entry === "string" || Array.isArray(entry)) { addEntry(entry, "main").then(() => callback(), callback); } else if(typeof entry === "object") { Promise.all(Object.keys(entry).map((name) => { return addEntry(entry[name], name); })).then(() => callback(), callback); } }); }); } }
n/a
createDependency = function (entry, name) { if(Array.isArray(entry)) return MultiEntryPlugin.createDependency(entry, name); else return SingleEntryPlugin.createDependency(entry, name); }
...
compilation.dependencyFactories.set(MultiEntryDependency, multiModuleFactory);
compilation.dependencyFactories.set(SingleEntryDependency, normalModuleFactory);
});
compiler.plugin("make", (compilation, callback) => {
const addEntry = (entry, name) => {
const dep = DynamicEntryPlugin.createDependency(entry, name);
return new Promise((resolve, reject) => {
compilation.addEntry(this.context, dep, name, (err) => {
if(err) return reject(err);
resolve();
});
});
};
...
(stack, message) => { stack = exports.cutOffLoaderExecution(stack); stack = exports.cutOffMessage(stack, message); return stack; }
n/a
(stack) => { stack = stack.split("\n"); for(let i = 0; i < stack.length; i++) if(stack[i].indexOf(loaderFlag) >= 0) stack.length = i; return stack.join("\n"); }
n/a
(stack, message) => { const nextLine = stack.indexOf("\n"); if(nextLine === -1) { return stack === message ? "" : stack; } else { const firstLine = stack.substr(0, nextLine); return firstLine === message ? stack.substr(nextLine + 1) : stack; } }
n/a
class HarmonyAcceptDependency extends NullDependency { constructor(range, dependencies, hasCallback) { super(); this.range = range; this.dependencies = dependencies; this.hasCallback = hasCallback; } get type() { return "accepted harmony modules"; } }
n/a
class HarmonyAcceptDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { const content = dep.dependencies .map(dependency => makeHarmonyImportStatement( false, dependency, outputOptions, requestShortener )).join(""); if(dep.hasCallback) { source.insert(dep.range[0], `function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content}(`); source.insert(dep.range[1], ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }"); return; } source.insert(dep.range[1] - 0.5, `, function() { ${content} }`); } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class HarmonyAcceptImportDependency extends HarmonyImportDependency { constructor(request, importedVar, range) { super(request, importedVar, range); } get type() { return "harmony accept"; } }
n/a
class HarmonyAcceptImportDependencyTemplate { apply(dep, source, outputOptions, requestShortener) {} }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class HarmonyCompatibilityDependency extends NullDependency { constructor(originModule) { super(); this.originModule = originModule; } get type() { return "harmony export header"; } }
n/a
class HarmonyExportDependencyTemplate { apply(dep, source) { const usedExports = dep.originModule.usedExports; if(usedExports && !Array.isArray(usedExports)) { const exportName = dep.originModule.exportsArgument || "exports"; const content = `Object.defineProperty(${exportName}, \"__esModule\", { value: true });\n`; source.insert(-1, content); } } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class HarmonyExportExpressionDependency extends NullDependency { constructor(originModule, range, rangeStatement) { super(); this.originModule = originModule; this.range = range; this.rangeStatement = rangeStatement; } get type() { return "harmony export expression"; } getExports() { return { exports: ["default"] }; } describeHarmonyExport() { return { exportedName: "default", precedence: 1, }; } }
n/a
class HarmonyExportDependencyTemplate { apply(dep, source) { const used = dep.originModule.isUsed("default"); const content = this.getContent(dep.originModule, used); if(dep.range) { source.replace(dep.rangeStatement[0], dep.range[0] - 1, content + "("); source.replace(dep.range[1], dep.rangeStatement[1] - 1, ");"); return; } source.replace(dep.rangeStatement[0], dep.rangeStatement[1] - 1, content); } getContent(module, used) { const exportsName = module.exportsArgument || "exports"; if(used) { return `/* harmony default export */ ${exportsName}[${JSON.stringify(used)}] = `; } return "/* unused harmony default export */ var _unused_webpack_default_export = "; } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class HarmonyExportHeaderDependency extends NullDependency { constructor(range, rangeStatement) { super(); this.range = range; this.rangeStatement = rangeStatement; } get type() { return "harmony export header"; } }
n/a
class HarmonyExportDependencyTemplate { apply(dep, source) { const content = ""; const replaceUntil = dep.range ? dep.range[0] - 1 : dep.rangeStatement[1] - 1; source.replace(dep.rangeStatement[0], replaceUntil, content); } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class HarmonyExportImportedSpecifierDependency extends NullDependency { constructor(originModule, importDependency, importedVar, id, name) { super(); this.originModule = originModule; this.importDependency = importDependency; this.importedVar = importedVar; this.id = id; this.name = name; } get type() { return "harmony export imported specifier"; } getReference() { const name = this.name; const used = this.originModule.isUsed(name); const active = HarmonyModulesHelpers.isActive(this.originModule, this); const importedModule = this.importDependency.module; if(!importedModule || !used || !active) return null; if(!this.originModule.usedExports) return null; if(name) { const nameIsNotInUsedExports = Array.isArray(this.originModule.usedExports) && this.originModule.usedExports.indexOf(name) < 0; if(nameIsNotInUsedExports) return null; // export { name as name } if(this.id) { return { module: importedModule, importedNames: [this.id] }; } // export { * as name } return { module: importedModule, importedNames: true }; } // export * if(Array.isArray(this.originModule.usedExports)) { // reexport * with known used exports var activeExports = HarmonyModulesHelpers.getActiveExports(this.originModule, this); if(Array.isArray(importedModule.providedExports)) { return { module: importedModule, importedNames: this.originModule.usedExports.filter((id) => { const notInActiveExports = activeExports.indexOf(id) < 0; const notDefault = id !== "default"; const inProvidedExports = importedModule.providedExports.indexOf(id) >= 0; return notInActiveExports && notDefault && inProvidedExports; }), }; } return { module: importedModule, importedNames: this.originModule.usedExports.filter(id => { const notInActiveExports = activeExports.indexOf(id) < 0; const notDefault = id !== "default"; return notInActiveExports && notDefault; }), }; } if(Array.isArray(importedModule.providedExports)) { return { module: importedModule, importedNames: importedModule.providedExports.filter(id => id !== "default"), }; } return { module: importedModule, importedNames: true, }; } getExports() { if(this.name) { return { exports: [this.name] }; } const importedModule = this.importDependency.module; if(!importedModule) { // no imported module available return { exports: null }; } if(Array.isArray(importedModule.providedExports)) { return { exports: importedModule.providedExports.filter(id => id !== "default"), dependencies: [importedModule] }; } if(importedModule.providedExports) { return { exports: true }; } return { exports: null, dependencies: [importedModule] }; } describeHarmonyExport() { const importedModule = this.importDependency.module; if(!this.name && importedModule && Array.isArray(importedModule.providedExports)) { // for a star export and when we know which exports are provided, we can tell so return { exportedName: importedModule.providedExports, precedence: 3 }; } return { exportedName: this.name, precedence: this.name ? 2 : 3 }; } updateHash(hash) { super.updateHash(hash); const hashValue = this.getHashValue(this.importDependency.module); hash.update(hashValue); } getHashValue(importedModule) { if(!importedModule) { return ""; } const stringifiedUsedExport = JSON.stringify(importedModule.usedExports); const stringifiedProvidedExport = JSON.stringify(importedModule.providedExports); return importedModule.used + stringifiedUsedExport + stringifiedProvidedExport; } }
n/a
class HarmonyExportImportedSpecifierDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { const content = this.getContent(dep); source.insert(-1, content); } getContent(dep) { const name = dep.importedVar; const used = dep.originModule.isUsed(dep.name); const importedModule = dep.importDependency.module; const active = HarmonyModulesHelpers.isActive(dep.originModule, dep); const importsExportsUnknown = !importedModule || !Array.isArray(importedModule.providedExports); const getReexportStatement = this.reexportStatementCreator(dep.originModule, importsExportsUnknown, name); // we want to rexport something, but the export isn't used if(!used) { return "/* unused harmony reexport " + dep.name + " */\n"; } // we want to reexport something but another exports overrides this one if(!active) { return "/* inactive harmony reexport " + (dep.name || "namespace") + " */\n"; } // we want to reexport the default export from a non-hamory module const isNotAHarmonyModule = !(importedModule && (!importedModule.meta || importedModule.meta.harmonyModule)); if(dep.name && dep.id === "default" && isNotAHarmonyModule) { return "/* harmony reexport (default from non-hamory) */ " + getReexportStatement(JSON.stringify(used), null); } // we want to reexport a key as new key if(dep.name && dep.id) { var idUsed = importedModule && importedModule.isUsed(dep.id); return "/* harmony reexport (binding) */ " + getReexportStatement(JSON.stringify(used), JSON.stringify(idUsed)); } // we want to reexport the module object as named export if(dep.name) { return "/* harmony reexport (module object) */ " + getReexportStatement(JSON.stringify(used), ""); } // we know which exports are used if(Array.isArray(dep.originModule.usedExports)) { const activeExports = HarmonyModulesHelpers.getActiveExports(dep.originModule, dep); const items = dep.originModule.usedExports.map(function(id) { if(id === "default") return; if(activeExports.indexOf(id) >= 0) return; if(importedModule.isProvided(id) === false) return; var exportUsed = dep.originModule.isUsed(id); var idUsed = importedModule && importedModule.isUsed(id); return [exportUsed, idUsed]; }).filter(Boolean); if(items.length === 0) { return "/* unused harmony namespace reexport */\n"; } return items.map(function(item) { return "/* harmony namespace reexport (by used) */ " + getReexportStatement(JSON.stringify(item[0]), JSON.stringify(item[1])); }).join(""); } // not sure which exports are used, but we know which are provided if(dep.originModule.usedExports && importedModule && Array.isArray(importedModule.providedExports)) { const activeExports = HarmonyModulesHelpers.getActiveExports(dep.originModule, dep); const items = importedModule.providedExports.map(function(id) { if(id === "default") return; if(activeExports.indexOf(id) >= 0) return; var exportUsed = dep.originModule.isUsed(id); var idUsed = importedModule && importedModule.isUsed(id); return [exportUsed, idUsed]; }).filter(Boolean); if(items.length === 0) { return "/* empty harmony namespace reexport */\n"; } return items.map(function(item) { return "/* harmony namespace reexport (by provided) */ " + getReexportStatement(JSON.stringify(item[0]), JSON.stringify(item [1])); }).join(""); } // not sure which exports are used and provided if(dep.originModule.usedExports) { const activeExports = HarmonyModulesHelpers.getActiveExports(dep.originModule, dep); let content = "/* harmony namespace reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in " + name + ") "; // Filter out exports which are defined by other exports // and filter out default export because it cannot be reexported with * if(activeExports.length > 0) content += "if(" + JSON.stringify(activeExports.concat("default")) + ".indexOf(__WEBPACK_IMPORT_KEY__) < 0) "; else ...
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class HarmonyExportSpecifierDependency extends NullDependency { constructor(originModule, id, name, position, immutable) { super(); this.originModule = originModule; this.id = id; this.name = name; this.position = position; this.immutable = immutable; } get type() { return "harmony export specifier"; } getExports() { return { exports: [this.name] }; } describeHarmonyExport() { return { exportedName: this.name, precedence: 1 }; } }
n/a
class HarmonyExportSpecifierDependencyTemplate { apply(dep, source) { const content = this.getPrefix(dep) + this.getContent(dep); source.insert(dep.position, content); } getPrefix(dep) { return dep.position > 0 ? "\n" : ""; } getContent(dep) { const used = dep.originModule.isUsed(dep.name); const active = HarmonyModulesHelpers.isActive(dep.originModule, dep); if(!used) { return `/* unused harmony export ${(dep.name || "namespace")} */\n`; } if(!active) { return `/* inactive harmony export ${(dep.name || "namespace")} */\n`; } const exportsName = dep.originModule.exportsArgument || "exports"; if(dep.immutable) { return `/* harmony export (immutable) */ ${exportsName}[${JSON.stringify(used)}] = ${dep.id};\n`; } return `/* harmony export (binding) */ __webpack_require__.d(${exportsName}, ${JSON.stringify(used)}, function() { return ${dep .id}; });\n`; } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class HarmonyImportDependency extends ModuleDependency { constructor(request, importedVar, range) { super(request); this.range = range; this.importedVar = importedVar; } get type() { return "harmony import"; } getReference() { if(!this.module) return null; return { module: this.module, importedNames: false }; } updateHash(hash) { super.updateHash(hash); hash.update((this.module && (!this.module.meta || this.module.meta.harmonyModule)) + ""); } }
n/a
class HarmonyImportDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { const content = makeImportStatement(true, dep, outputOptions, requestShortener); source.replace(dep.range[0], dep.range[1] - 1, ""); source.insert(-1, content); } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
function makeImportStatement(declare, dep, outputOptions, requestShortener) { const comment = getOptionalComment(outputOptions.pathinfo, requestShortener.shorten(dep.request)); const declaration = declare ? "var " : ""; const newline = declare ? "\n" : " "; if(!dep.module) { const stringifiedError = JSON.stringify(`Cannot find module "${dep.request}"`); return `throw new Error(${stringifiedError});${newline}`; } if(dep.importedVar) { const isHarmonyModule = dep.module.meta && dep.module.meta.harmonyModule; const content = `/* harmony import */ ${declaration}${dep.importedVar} = __webpack_require__(${comment}${JSON.stringify(dep.module .id)});${newline}`; if(isHarmonyModule) { return content; } return `${content}/* harmony import */ ${declaration}${dep.importedVar}_default = __webpack_require__.n(${dep.importedVar});${ newline}`; } return ""; }
n/a
class HarmonyImportSpecifierDependency extends NullDependency { constructor(importDependency, importedVar, id, name, range, strictExportPresence) { super(); this.importDependency = importDependency; this.importedVar = importedVar; this.id = id; this.name = name; this.range = range; this.strictExportPresence = strictExportPresence; } get type() { return "harmony import specifier"; } getReference() { if(!this.importDependency.module) return null; return { module: this.importDependency.module, importedNames: this.id ? [this.id] : true }; } getWarnings() { if(this.strictExportPresence) { return []; } return this._getErrors(); } getErrors() { if(this.strictExportPresence) { return this._getErrors(); } return []; } _getErrors() { const importedModule = this.importDependency.module; if(!importedModule || !importedModule.meta || !importedModule.meta.harmonyModule) { return; } if(!this.id) { return; } if(importedModule.isProvided(this.id) !== false) { return; } const idIsNotNameMessage = this.id !== this.name ? ` (imported as '${this.name}')` : ""; const errorMessage = `"export '${this.id}'${idIsNotNameMessage} was not found in '${this.importDependency.userRequest}'`; const err = new Error(errorMessage); err.hideStack = true; return [err]; } updateHash(hash) { super.updateHash(hash); const importedModule = this.importDependency.module; hash.update((importedModule && importedModule.id) + ""); hash.update((importedModule && this.id) + ""); hash.update((importedModule && this.importedVar) + ""); hash.update((importedModule && this.id && importedModule.isUsed(this.id)) + ""); hash.update((importedModule && (!importedModule.meta || importedModule.meta.harmonyModule)) + ""); hash.update((importedModule && (importedModule.used + JSON.stringify(importedModule.usedExports))) + ""); } }
n/a
class HarmonyImportSpecifierDependencyTemplate { apply(dep, source) { const content = this.getContent(dep); source.replace(dep.range[0], dep.range[1] - 1, content); } getContent(dep) { const importedModule = dep.importDependency.module; const defaultImport = dep.directImport && dep.id === "default" && !(importedModule && (!importedModule.meta || importedModule. meta.harmonyModule)); const shortHandPrefix = this.getShortHandPrefix(dep); const importedVar = dep.importedVar; const importedVarSuffix = this.getImportVarSuffix(dep, defaultImport, importedModule); if(dep.call && defaultImport) { return `${shortHandPrefix}${importedVar}_default()`; } if(dep.call && dep.id) { return `${shortHandPrefix}__webpack_require__.i(${importedVar}${importedVarSuffix})`; } return `${shortHandPrefix}${importedVar}${importedVarSuffix}`; } getImportVarSuffix(dep, defaultImport, importedModule) { if(defaultImport) { return "_default.a"; } if(dep.id) { const used = importedModule ? importedModule.isUsed(dep.id) : dep.id; const optionalComment = dep.id !== used ? " /* " + dep.id + " */" : ""; return `[${JSON.stringify(used)}${optionalComment}]`; } return ""; } getShortHandPrefix(dep) { if(!dep.shorthand) { return ""; } return dep.name + ": "; } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
function HotModuleReplacementPlugin(options) { options = options || {}; this.multiStep = options.multiStep; this.fullBuildTimeout = options.fullBuildTimeout || 200; }
n/a
apply = function (compiler) { var multiStep = this.multiStep; var fullBuildTimeout = this.fullBuildTimeout; var hotUpdateChunkFilename = compiler.options.output.hotUpdateChunkFilename; var hotUpdateMainFilename = compiler.options.output.hotUpdateMainFilename; compiler.plugin("compilation", function(compilation, params) { var hotUpdateChunkTemplate = compilation.hotUpdateChunkTemplate; if(!hotUpdateChunkTemplate) return; var normalModuleFactory = params.normalModuleFactory; compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); compilation.dependencyFactories.set(ModuleHotAcceptDependency, normalModuleFactory); compilation.dependencyTemplates.set(ModuleHotAcceptDependency, new ModuleHotAcceptDependency.Template()); compilation.dependencyFactories.set(ModuleHotDeclineDependency, normalModuleFactory); compilation.dependencyTemplates.set(ModuleHotDeclineDependency, new ModuleHotDeclineDependency.Template()); compilation.plugin("record", function(compilation, records) { if(records.hash === this.hash) return; records.hash = compilation.hash; records.moduleHashs = {}; this.modules.forEach(function(module) { var identifier = module.identifier(); var hash = require("crypto").createHash("md5"); module.updateHash(hash); records.moduleHashs[identifier] = hash.digest("hex"); }); records.chunkHashs = {}; this.chunks.forEach(function(chunk) { records.chunkHashs[chunk.id] = chunk.hash; }); records.chunkModuleIds = {}; this.chunks.forEach(function(chunk) { records.chunkModuleIds[chunk.id] = chunk.modules.map(function(m) { return m.id; }); }); }); var initialPass = false; var recompilation = false; compilation.plugin("after-hash", function() { var records = this.records; if(!records) { initialPass = true; return; } if(!records.hash) initialPass = true; var preHash = records.preHash || "x"; var prepreHash = records.prepreHash || "x"; if(preHash === this.hash) { recompilation = true; this.modifyHash(prepreHash); return; } records.prepreHash = records.hash || "x"; records.preHash = this.hash; this.modifyHash(records.prepreHash); }); compilation.plugin("should-generate-chunk-assets", function() { if(multiStep && !recompilation && !initialPass) return false; }); compilation.plugin("need-additional-pass", function() { if(multiStep && !recompilation && !initialPass) return true; }); compiler.plugin("additional-pass", function(callback) { if(multiStep) return setTimeout(callback, fullBuildTimeout); return callback(); }); compilation.plugin("additional-chunk-assets", function() { var records = this.records; 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"); module.updateHash(hash); hash = hash.digest("hex"); module.hotUpdate = records.moduleHashs[identifier] !== hash; }); var hotUpdateMainContent = { h: this.hash, c: {} }; Object.keys(records.chunkHashs).forEach(function(chunkId) { chunkId = isNaN(+chunkId) ? chunkId : +chunkId; var currentChunk = this.chunks.find(chunk => chunk.id === chunkId); if(currentChunk) { var newModules = currentChunk.modules.filter(function(module) { return module.hotUpdate; }); var allModules = {}; currentChunk.modules.forEach(function(module) { allModules[module.id] = true; }); var removedModules = records.chunkModuleIds[chunkId].filter(function(id) { return !allModules[id]; }); if(newModules.length > 0 || removedModules.length > 0) { var source = hotUpdateChunkTemplate.render(chunkId, newModules, removedM ...
...
process.exit(1); // eslint-disable-line no-process-exit
}
throw e;
}
if(argv.progress) {
var ProgressPlugin = require("../lib/ProgressPlugin");
compiler.apply(new ProgressPlugin({
profile: argv.profile
}));
}
function compilerCallback(err, stats) {
if(!options.watch || err) {
// Do not keep cache anymore
...
class ImportContextDependency extends ContextDependency { constructor(request, recursive, regExp, range, valueRange, chunkName) { super(request, recursive, regExp); this.range = range; this.valueRange = valueRange; this.async = true; this.chunkName = chunkName; } get type() { return "import() context"; } getWarnings() { if(!this.critical) { return; } return [ new CriticalDependencyWarning(this.critical) ]; } }
n/a
class ContextDependencyTemplateAsRequireCall { apply(dep, source, outputOptions, requestShortener) { const comment = outputOptions.pathinfo ? "/*! " + requestShortener.shorten(dep.request) + " */ " : ""; const containsDeps = dep.module && dep.module.dependencies && dep.module.dependencies.length > 0; const isAsync = dep.module && dep.module.async; if(dep.module && (isAsync || containsDeps)) { if(dep.valueRange) { if(Array.isArray(dep.replaces)) { for(let i = 0; i < dep.replaces.length; i++) { const rep = dep.replaces[i]; source.replace(rep.range[0], rep.range[1] - 1, rep.value); } } 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 { source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")"); } } else { const content = require("./WebpackMissingModule").module(dep.request); source.replace(dep.range[0], dep.range[1] - 1, content); } } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class ImportDependency extends ModuleDependency { constructor(request, block) { super(request); this.block = block; } get type() { return "import()"; } }
n/a
class ImportDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { const depBlock = dep.block; const promise = DepBlockHelpers.getDepBlockPromise(depBlock, outputOptions, requestShortener, "import()"); const comment = this.getOptionalComment(outputOptions.pathinfo, requestShortener.shorten(dep.request)); const content = this.getContent(promise, dep, comment); source.replace(depBlock.range[0], depBlock.range[1] - 1, content); } getOptionalComment(pathinfo, shortenedRequest) { if(!pathinfo) { return ""; } return `/*! ${shortenedRequest} */ `; } getContent(promise, dep, comment) { if(promise && dep.module) { const stringifiedId = JSON.stringify(dep.module.id); return `${promise}.then(__webpack_require__.bind(null, ${comment}${stringifiedId}))`; } if(dep.module) { const stringifiedId = JSON.stringify(dep.module.id); return `Promise.resolve(__webpack_require__(${comment}${stringifiedId}))`; } return webpackMissingPromiseModule(dep.request); } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class LocalModuleDependency extends NullDependency { constructor(localModule, range) { super(); localModule.flagUsed(); this.localModule = localModule; this.range = range; } }
n/a
class LocalModuleDependencyTemplate { apply(dep, source) { if(!dep.range) return; source.replace(dep.range[0], dep.range[1] - 1, dep.localModule.variableName()); } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
(state, name) => { if(!state.localModules) state.localModules = []; var m = new LocalModule(state.module, name, state.localModules.length); state.localModules.push(m); return m; }
...
array ? array.range : null,
fn ? fn.range : null,
obj ? obj.range : null,
namedModule ? namedModule : null
);
dep.loc = expr.loc;
if(namedModule) {
dep.localModule = LocalModulesHelpers.addLocalModule(parser.state, namedModule);
}
parser.state.current.addDependency(dep);
return true;
});
parser.plugin("call define:amd:array", (expr, param, identifiers, namedModule) => {
if(param.isArray()) {
param.items.forEach((param, idx) => {
...
(state, name, 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) return state.localModules[i]; } return null; }
...
let localModule;
if(request === "require") {
identifiers[idx] = request;
dep = "__webpack_require__";
} else if(["exports", "module"].indexOf(request) >= 0) {
identifiers[idx] = request;
dep = request;
} else if(localModule = LocalModulesHelpers.getLocalModule(parser.state, request
)) { // eslint-disable-line no-cond-assign
dep = new LocalModuleDependency(localModule);
dep.loc = expr.loc;
parser.state.current.addDependency(dep);
} else {
dep = new AMDRequireItemDependency(request);
dep.loc = expr.loc;
dep.optional = !!parser.scope.inTry;
...
function MemoryFileSystem(data) { this.data = data || {}; }
n/a
_remove = function (_path, name, testFn) { var path = pathToArray(_path); if(path.length === 0) { throw new MemoryFileSystemError(errors.code.EPERM, _path); } var current = this.data; for(var i = 0; i < path.length - 1; i++) { if(!isDir(current[path[i]])) throw new MemoryFileSystemError(errors.code.ENOENT, _path); current = current[path[i]]; } if(!testFn(current[path[i]])) throw new MemoryFileSystemError(errors.code.ENOENT, _path); delete current[path[i]]; return; }
n/a
createReadStream = function (path, options) { var stream = new ReadableStream(); var done = false; var data; try { data = this.readFileSync(path); } catch (e) { stream._read = function() { if (done) { return; } done = true; this.emit('error', e); this.push(null); }; return stream; } options = options || { }; options.start = options.start || 0; options.end = options.end || data.length; stream._read = function() { if (done) { return; } done = true; this.push(data.slice(options.start, options.end)); this.push(null); }; return stream; }
n/a
createWriteStream = function (path, options) { var stream = new WritableStream(), self = this; try { // Zero the file and make sure it is writable this.writeFileSync(path, new Buffer(0)); } catch(e) { // This or setImmediate? stream.once('prefinish', function() { stream.emit('error', e); }); return stream; } var bl = [ ], len = 0; stream._write = function(chunk, encoding, callback) { bl.push(chunk); len += chunk.length; self.writeFile(path, Buffer.concat(bl, len), callback); } return stream; }
n/a
exists = function (path, callback) { return callback(this.existsSync(path)); }
n/a
existsSync = function (_path) { return !!this.meta(_path); }
...
};
var configArgList = Array.isArray(argv.config) ? argv.config : [argv.config];
configFiles = configArgList.map(mapConfigArg);
} else {
for(i = 0; i < defaultConfigFiles.length; i++) {
var webpackConfig = defaultConfigFiles[i].path;
if(fs.existsSync(webpackConfig)) {
configFiles.push({
path: webpackConfig,
ext: defaultConfigFiles[i].ext
});
break;
}
}
...
function join(path, request) { if(!request) return normalize(path); if(absoluteWinRegExp.test(request)) return normalize(request.replace(/\//g, "\\")); if(absoluteNixRegExp.test(request)) return normalize(request); if(path == "/") return normalize(path + request); if(absoluteWinRegExp.test(path)) return normalize(path.replace(/\//g, "\\") + "\\" + request.replace(/\//g, "\\")); if(absoluteNixRegExp.test(path)) return normalize(path + "/" + request); return normalize(path + "/" + request); }
...
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var path = require("path");
// Local version replace global one
try {
var localWebpack = require.resolve(path.join(process.cwd(), "node_modules",
x22;webpack", "bin", "webpack.js"));
if(__filename !== localWebpack) {
return require(localWebpack);
}
} catch(e) {}
var yargs = require("yargs")
.usage("webpack " + require("../package.json").version + "\n" +
"Usage: https://webpack.js.org/api/cli/\n" +
...
meta = function (_path) { var path = pathToArray(_path); var current = this.data; for(var i = 0; i < path.length - 1; i++) { if(!isDir(current[path[i]])) return; current = current[path[i]]; } return current[path[i]]; }
n/a
mkdir = function (path, optArg, callback) { if(!callback) { callback = optArg; optArg = undefined; } try { var result = this[fn + "Sync"](path, optArg); } catch(e) { setImmediate(function() { callback(e); }); return; } setImmediate(function() { callback(null, result); }); }
n/a
mkdirSync = function (_path) { var path = pathToArray(_path); if(path.length === 0) return; var current = this.data; for(var i = 0; i < path.length - 1; i++) { if(!isDir(current[path[i]])) throw new MemoryFileSystemError(errors.code.ENOENT, _path); current = current[path[i]]; } if(isDir(current[path[i]])) throw new MemoryFileSystemError(errors.code.EEXIST, _path); else if(isFile(current[path[i]])) throw new MemoryFileSystemError(errors.code.ENOTDIR, _path); current[path[i]] = {"":true}; return; }
n/a
mkdirp = function (path, callback) { try { var result = this[fn + "Sync"](path); } catch(e) { setImmediate(function() { callback(e); }); return; } setImmediate(function() { callback(null, result); }); }
...
Compiler.prototype.emitAssets = function(compilation, callback) {
var outputPath;
this.applyPluginsAsync("emit", compilation, function(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);
require("async").forEach(Object.keys(compilation.assets), function(file, callback) {
...
mkdirpSync = function (_path) { var path = pathToArray(_path); if(path.length === 0) return; var current = this.data; for(var i = 0; i < path.length; i++) { if(isFile(current[path[i]])) throw new MemoryFileSystemError(errors.code.ENOTDIR, _path); else if(!isDir(current[path[i]])) current[path[i]] = {"":true}; current = current[path[i]]; } return; }
n/a
function normalize(path) { var parts = path.split(/(\\+|\/+)/); if(parts.length === 1) return path; var result = []; var absolutePathStart = 0; for(var i = 0, sep = false; i < parts.length; i++, sep = !sep) { var part = parts[i]; if(i === 0 && /^([A-Z]:)?$/i.test(part)) { result.push(part); absolutePathStart = 2; } else if(sep) { result.push(part[0]); } else if(part === "..") { switch(result.length) { case 0: // i. e. ".." => ".." // i. e. "../a/b/c" => "../a/b/c" result.push(part); break; case 2: // i. e. "a/.." => "" // i. e. "/.." => "/" // i. e. "C:\.." => "C:\" // i. e. "a/../b/c" => "b/c" // i. e. "/../b/c" => "/b/c" // i. e. "C:\..\a\b\c" => "C:\a\b\c" i++; sep = !sep; result.length = absolutePathStart; break; case 4: // i. e. "a/b/.." => "a" // i. e. "/a/.." => "/" // i. e. "C:\a\.." => "C:\" // i. e. "/a/../b/c" => "/b/c" if(absolutePathStart === 0) { result.length -= 3; } else { i++; sep = !sep; result.length = 2; } break; default: // i. e. "/a/b/.." => "/a" // i. e. "/a/b/../c" => "/a/c" result.length -= 3; break; } } else if(part === ".") { switch(result.length) { case 0: // i. e. "." => "." // i. e. "./a/b/c" => "./a/b/c" result.push(part); break; case 2: // i. e. "a/." => "a" // i. e. "/." => "/" // i. e. "C:\." => "C:\" // i. e. "C:\.\a\b\c" => "C:\a\b\c" if(absolutePathStart === 0) { result.length--; } else { i++; sep = !sep; } break; default: // i. e. "a/b/." => "a/b" // i. e. "/a/." => "/" // i. e. "C:\a\." => "C:\" // i. e. "a/./b/c" => "a/b/c" // i. e. "/a/./b/c" => "/a/b/c" result.length--; break; } } else if(part) { result.push(part); } } if(result.length === 1 && /^[A-Za-z]:$/.test(result)) return result[0] + "\\"; return result.join(""); }
n/a
function pathToArray(path) { path = normalize(path); var nix = /^\//.test(path); if(!nix) { if(!/^[A-Za-z]:/.test(path)) { throw new MemoryFileSystemError(errors.code.EINVAL, path); } path = path.replace(/[\\\/]+/g, "\\"); // multi slashs path = path.split(/[\\\/]/); path[0] = path[0].toUpperCase(); } else { path = path.replace(/\/+/g, "/"); // multi slashs path = path.substr(1).split("/"); } if(!path[path.length-1]) path.pop(); return path; }
n/a
readFile = function (path, optArg, callback) { if(!callback) { callback = optArg; optArg = undefined; } try { var result = this[fn + "Sync"](path, optArg); } catch(e) { setImmediate(function() { callback(e); }); return; } setImmediate(function() { callback(null, result); }); }
...
return callback();
}
self.inputFileSystem.stat(self.recordsInputPath, function(err) {
// It doesn't exist
// We can ignore self.
if(err) return callback();
self.inputFileSystem.readFile(self.recordsInputPath, function(err, content) {
if(err) return callback(err);
try {
self.records = JSON.parse(content.toString("utf-8"));
} catch(e) {
e.message = "Cannot parse records: " + e.message;
return callback(e);
...
readFileSync = function (_path, encoding) { var path = pathToArray(_path); var current = this.data; for(var i = 0; i < path.length - 1; i++) { if(!isDir(current[path[i]])) throw new MemoryFileSystemError(errors.code.ENOENT, _path); current = current[path[i]]; } if(!isFile(current[path[i]])) { if(isDir(current[path[i]])) throw new MemoryFileSystemError(errors.code.EISDIR, _path); else throw new MemoryFileSystemError(errors.code.ENOENT, _path); } current = current[path[i]]; return encoding ? current.toString(encoding) : current; }
n/a
readdir = function (path, callback) { try { var result = this[fn + "Sync"](path); } catch(e) { setImmediate(function() { callback(e); }); return; } setImmediate(function() { callback(null, result); }); }
...
});
};
ContextModuleFactory.prototype.resolveDependencies = function resolveDependencies(fs, resource, recursive, regExp, callback) {
if(!regExp || !resource)
return callback(null, []);
(function addDirectory(directory, callback) {
fs.readdir(directory, function(err, files) {
if(err) return callback(err);
if(!files || files.length === 0) return callback(null, []);
asyncLib.map(files.filter(function(p) {
return p.indexOf(".") !== 0;
}), function(seqment, callback) {
var subResource = path.join(directory, seqment);
...
readdirSync = function (_path) { if(_path === "/") return Object.keys(this.data).filter(Boolean); var path = pathToArray(_path); var current = this.data; for(var i = 0; i < path.length - 1; i++) { if(!isDir(current[path[i]])) throw new MemoryFileSystemError(errors.code.ENOENT, _path); current = current[path[i]]; } if(!isDir(current[path[i]])) { if(isFile(current[path[i]])) throw new MemoryFileSystemError(errors.code.ENOTDIR, _path); else throw new MemoryFileSystemError(errors.code.ENOENT, _path); } return Object.keys(current[path[i]]).filter(Boolean); }
n/a
readlink = function (path, callback) { try { var result = this[fn + "Sync"](path); } catch(e) { setImmediate(function() { callback(e); }); return; } setImmediate(function() { callback(null, result); }); }
n/a
readlinkSync = function (_path) { throw new MemoryFileSystemError(errors.code.ENOSYS, _path); }
n/a
rmdir = function (path, callback) { try { var result = this[fn + "Sync"](path); } catch(e) { setImmediate(function() { callback(e); }); return; } setImmediate(function() { callback(null, result); }); }
n/a
rmdirSync = function (_path) { return this._remove(_path, "Directory", isDir); }
n/a
stat = function (path, callback) { try { var result = this[fn + "Sync"](path); } catch(e) { setImmediate(function() { callback(e); }); return; } setImmediate(function() { callback(null, result); }); }
...
callback();
});
compiler.plugin("run", (compiler, callback) => {
if(!compiler._lastCompilationFileDependencies) return callback();
const fs = compiler.inputFileSystem;
const fileTs = compiler.fileTimestamps = {};
asyncLib.forEach(compiler._lastCompilationFileDependencies, (file, callback) => {
fs.stat(file, (err, stat) => {
if(err) {
if(err.code === "ENOENT") return callback();
return callback(err);
}
if(stat.mtime)
this.applyMtime(+stat.mtime);
...
statSync = function (_path) { var current = this.meta(_path); if(_path === "/" || isDir(current)) { return { isFile: falseFn, isDirectory: trueFn, isBlockDevice: falseFn, isCharacterDevice: falseFn, isSymbolicLink: falseFn, isFIFO: falseFn, isSocket: falseFn }; } else if(isFile(current)) { return { isFile: trueFn, isDirectory: falseFn, isBlockDevice: falseFn, isCharacterDevice: falseFn, isSymbolicLink: falseFn, isFIFO: falseFn, isSocket: falseFn }; } else { throw new MemoryFileSystemError(errors.code.ENOENT, _path); } }
n/a
unlink = function (path, callback) { try { var result = this[fn + "Sync"](path); } catch(e) { setImmediate(function() { callback(e); }); return; } setImmediate(function() { callback(null, result); }); }
n/a
unlinkSync = function (_path) { return this._remove(_path, "File", isFile); }
n/a
writeFile = function (path, content, encoding, callback) { if(!callback) { callback = encoding; encoding = undefined; } try { this.writeFileSync(path, content, encoding); } catch(e) { return callback(e); } return callback(); }
...
if(!Buffer.isBuffer(content)) {
content = new Buffer(content, "utf8"); //eslint-disable-line
}
source.existsAt = targetPath;
source.emitted = true;
this.outputFileSystem.writeFile(targetPath, content, callback);
}
}.bind(this), function(err) {
if(err) return callback(err);
afterEmit.call(this);
}.bind(this));
...
writeFileSync = function (_path, content, encoding) { if(!content && !encoding) throw new Error("No content"); var path = pathToArray(_path); if(path.length === 0) { throw new MemoryFileSystemError(errors.code.EISDIR, _path); } var current = this.data; for(var i = 0; i < path.length - 1; i++) { if(!isDir(current[path[i]])) throw new MemoryFileSystemError(errors.code.ENOENT, _path); current = current[path[i]]; } if(isDir(current[path[i]])) throw new MemoryFileSystemError(errors.code.EISDIR, _path); current[path[i]] = encoding || typeof content === "string" ? new Buffer(content, encoding) : content; return; }
n/a
function createFilename(module, moduleFilenameTemplate, requestShortener) { let absoluteResourcePath; let hash; let identifier; let moduleId; let shortIdentifier; if(module === undefined) module = ""; if(typeof module === "string") { shortIdentifier = requestShortener.shorten(module); identifier = shortIdentifier; moduleId = ""; absoluteResourcePath = module.split("!").pop(); hash = getHash(identifier); } else { shortIdentifier = module.readableIdentifier(requestShortener); identifier = requestShortener.shorten(module.identifier()); moduleId = module.id; absoluteResourcePath = module.identifier().split("!").pop(); hash = getHash(identifier); } const resource = shortIdentifier.split("!").pop(); const loaders = getBefore(shortIdentifier, "!"); const allLoaders = getBefore(identifier, "!"); const query = getAfter(resource, "?"); const resourcePath = resource.substr(0, resource.length - query.length); if(typeof moduleFilenameTemplate === "function") { return moduleFilenameTemplate({ identifier: identifier, shortIdentifier: shortIdentifier, resource: resource, resourcePath: resourcePath, absoluteResourcePath: absoluteResourcePath, allLoaders: allLoaders, query: query, moduleId: moduleId, hash: hash }); } return moduleFilenameTemplate .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE, identifier) .replace(ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE, shortIdentifier) .replace(ModuleFilenameHelpers.REGEXP_RESOURCE, resource) .replace(ModuleFilenameHelpers.REGEXP_RESOURCE_PATH, resourcePath) .replace(ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH, absoluteResourcePath) .replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS, allLoaders) .replace(ModuleFilenameHelpers.REGEXP_LOADERS, loaders) .replace(ModuleFilenameHelpers.REGEXP_QUERY, query) .replace(ModuleFilenameHelpers.REGEXP_ID, moduleId) .replace(ModuleFilenameHelpers.REGEXP_HASH, hash); }
...
this.sourceUrlComment = sourceUrlComment || "\n//# sourceURL=[url]";
this.moduleFilenameTemplate = moduleFilenameTemplate || "webpack:///[resourcePath]?[loaders]";
}
apply(moduleTemplate) {
moduleTemplate.plugin("module", (source, module) => {
const content = source.source();
const str = ModuleFilenameHelpers.createFilename(module, this.moduleFilenameTemplate
, moduleTemplate.requestShortener);
const footer = ["\n",
ModuleFilenameHelpers.createFooter(module, moduleTemplate.requestShortener),
this.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)});`);
});
moduleTemplate.plugin("hash", hash => {
...
function createFooter(module, requestShortener) { if(!module) module = ""; if(typeof module === "string") { return [ "// WEBPACK FOOTER //", `// ${requestShortener.shorten(module)}` ].join("\n"); } else { return [ "//////////////////", "// WEBPACK FOOTER", `// ${module.readableIdentifier(requestShortener)}`, `// module id = ${module.id}`, `// module chunks = ${module.chunks.map(c => c.id).join(" ")}` ].join("\n"); } }
...
}
apply(moduleTemplate) {
moduleTemplate.plugin("module", (source, module) => {
const content = source.source();
const str = ModuleFilenameHelpers.createFilename(module, this.moduleFilenameTemplate, moduleTemplate.requestShortener);
const footer = ["\n",
ModuleFilenameHelpers.createFooter(module, moduleTemplate.requestShortener),
this.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)});`);
});
moduleTemplate.plugin("hash", hash => {
hash.update("EvalDevToolModuleTemplatePlugin");
hash.update("2");
...
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; return true; }
...
apply(compiler) {
const options = this.options;
compiler.plugin("compilation", (compilation) => {
compilation.plugin("normal-module-loader", (context, module) => {
const resource = module.resource;
if(!resource) return;
const i = resource.indexOf("?");
if(ModuleFilenameHelpers.matchObject(options, i < 0 ? resource : resource.substr
(0, i))) {
const filterSet = new Set(["include", "exclude", "test"]);
Object.keys(options)
.filter((key) => !filterSet.has(key))
.forEach((key) => context[key] = options[key]);
}
});
});
...
function matchPart(str, test) { if(!test) return true; test = asRegExp(test); if(Array.isArray(test)) { return test.map(asRegExp).filter(function(regExp) { return regExp.test(str); }).length > 0; } else { return test.test(str); } }
n/a
function replaceDuplicates(array, fn, comparator) { const countMap = Object.create(null); const posMap = Object.create(null); array.forEach((item, idx) => { countMap[item] = (countMap[item] || []); countMap[item].push(idx); posMap[item] = 0; }); if(comparator) { Object.keys(countMap).forEach(item => { countMap[item].sort(comparator); }); } return array.map((item, i) => { if(countMap[item].length > 1) { if(comparator && countMap[item][0] === i) return item; return fn(item, i, posMap[item]++); } else return item; }); }
...
const modules = sourceMap.sources.map(function(source) {
const module = self.compilation.findModule(source);
return module || source;
});
let moduleFilenames = modules.map(function(module) {
return ModuleFilenameHelpers.createFilename(module, self.moduleFilenameTemplate, this.requestShortener);
}, this);
moduleFilenames = ModuleFilenameHelpers.replaceDuplicates(moduleFilenames, function
(filename, i, n) {
for(let j = 0; j < n; j++)
filename += "*";
return filename;
});
sourceMap.sources = moduleFilenames;
if(sourceMap.sourcesContent) {
sourceMap.sourcesContent = sourceMap.sourcesContent.map(function(content, i) {
...
class ModuleHotAcceptDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; this.weak = true; } get type() { return "module.hot.accept"; } }
n/a
class ModuleDependencyTemplateAsId { apply(dep, source, outputOptions, requestShortener) { if(!dep.range) return; const comment = outputOptions.pathinfo ? `/*! ${requestShortener.shorten(dep.request)} */ ` : ""; let content; if(dep.module) content = comment + JSON.stringify(dep.module.id); else content = require("./WebpackMissingModule").module(dep.request); source.replace(dep.range[0], dep.range[1] - 1, content); } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class ModuleHotDeclineDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; this.weak = true; } get type() { return "module.hot.decline"; } }
n/a
class ModuleDependencyTemplateAsId { apply(dep, source, outputOptions, requestShortener) { if(!dep.range) return; const comment = outputOptions.pathinfo ? `/*! ${requestShortener.shorten(dep.request)} */ ` : ""; let content; if(dep.module) content = comment + JSON.stringify(dep.module.id); else content = require("./WebpackMissingModule").module(dep.request); source.replace(dep.range[0], dep.range[1] - 1, content); } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
function MultiCompiler(compilers) { Tapable.call(this); if(!Array.isArray(compilers)) { compilers = Object.keys(compilers).map(function(name) { compilers[name].name = name; return compilers[name]; }); } this.compilers = compilers; function delegateProperty(name) { Object.defineProperty(this, name, { configurable: false, get: function() { throw new Error("Cannot read " + name + " of a MultiCompiler"); }, set: function(value) { this.compilers.forEach(function(compiler) { compiler[name] = value; }); }.bind(this) }); } delegateProperty.call(this, "outputFileSystem"); delegateProperty.call(this, "inputFileSystem"); Object.defineProperty(this, "outputPath", { 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)) { commonPath = commonPath.replace(/[\/\\][^\/\\]*$/, ""); } } if(!commonPath && compilers[0].outputPath[0] === "/") return "/"; return commonPath; } }); var doneCompilers = 0; var compilerStats = []; this.compilers.forEach(function(compiler, idx) { var compilerDone = false; compiler.plugin("done", function(stats) { if(!compilerDone) { compilerDone = true; doneCompilers++; } compilerStats[idx] = stats; if(doneCompilers === this.compilers.length) { this.applyPlugins("done", new MultiStats(compilerStats)); } }.bind(this)); compiler.plugin("invalid", function() { if(compilerDone) { compilerDone = false; doneCompilers--; } this.applyPlugins("invalid"); }.bind(this)); }, this); }
n/a
function MultiCompiler(compilers) { Tapable.call(this); if(!Array.isArray(compilers)) { compilers = Object.keys(compilers).map(function(name) { compilers[name].name = name; return compilers[name]; }); } this.compilers = compilers; function delegateProperty(name) { Object.defineProperty(this, name, { configurable: false, get: function() { throw new Error("Cannot read " + name + " of a MultiCompiler"); }, set: function(value) { this.compilers.forEach(function(compiler) { compiler[name] = value; }); }.bind(this) }); } delegateProperty.call(this, "outputFileSystem"); delegateProperty.call(this, "inputFileSystem"); Object.defineProperty(this, "outputPath", { 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)) { commonPath = commonPath.replace(/[\/\\][^\/\\]*$/, ""); } } if(!commonPath && compilers[0].outputPath[0] === "/") return "/"; return commonPath; } }); var doneCompilers = 0; var compilerStats = []; this.compilers.forEach(function(compiler, idx) { var compilerDone = false; compiler.plugin("done", function(stats) { if(!compilerDone) { compilerDone = true; doneCompilers++; } compilerStats[idx] = stats; if(doneCompilers === this.compilers.length) { this.applyPlugins("done", new MultiStats(compilerStats)); } }.bind(this)); compiler.plugin("invalid", function() { if(compilerDone) { compilerDone = false; doneCompilers--; } this.applyPlugins("invalid"); }.bind(this)); }, this); }
n/a
purgeInputFileSystem = function () { this.compilers.forEach(function(compiler) { if(compiler.inputFileSystem && compiler.inputFileSystem.purge) compiler.inputFileSystem.purge(); }); }
...
profile: argv.profile
}));
}
function compilerCallback(err, stats) {
if(!options.watch || err) {
// Do not keep cache anymore
compiler.purgeInputFileSystem();
}
if(err) {
lastHash = null;
console.error(err.stack || err);
if(err.details) console.error(err.details);
process.exit(1); // eslint-disable-line
}
...
run = function (callback) { var allStats = this.compilers.map(function() { return null; }); runWithDependencies(this.compilers, function(compiler, callback) { var compilerIdx = this.compilers.indexOf(compiler); compiler.run(function(err, stats) { if(err) return callback(err); allStats[compilerIdx] = stats; callback(); }); }.bind(this), function(err) { if(err) return callback(err); callback(null, new MultiStats(allStats)); }); }
...
process.exit(0); // eslint-disable-line
});
process.stdin.resume();
}
compiler.watch(watchOptions, compilerCallback);
console.log("\nWebpack is watching the files…\n");
} else
compiler.run(compilerCallback);
}
processOptions(options);
...
watch = function (watchOptions, handler) { var watchings = []; var allStats = this.compilers.map(function() { return null; }); var compilerStatus = this.compilers.map(function() { return false; }); runWithDependencies(this.compilers, function(compiler, callback) { var compilerIdx = this.compilers.indexOf(compiler); var firstRun = true; var watching = compiler.watch(Array.isArray(watchOptions) ? watchOptions[compilerIdx] : watchOptions, function(err, stats) { if(err) handler(err); if(stats) { allStats[compilerIdx] = stats; compilerStatus[compilerIdx] = "new"; if(compilerStatus.every(Boolean)) { var freshStats = allStats.filter(function(s, idx) { return compilerStatus[idx] === "new"; }); compilerStatus.fill(true); var multiStats = new MultiStats(freshStats); handler(null, multiStats); } } if(firstRun && !err) { firstRun = false; callback(); } }); watchings.push(watching); }.bind(this), function() { // ignore }); return new MultiWatching(watchings, this); }
...
var watchOptions = firstOptions.watchOptions || firstOptions.watch || options.watch || {};
if(watchOptions.stdin) {
process.stdin.on("end", function() {
process.exit(0); // eslint-disable-line
});
process.stdin.resume();
}
compiler.watch(watchOptions, compilerCallback);
console.log("\nWebpack is watching the files…\n");
} else
compiler.run(compilerCallback);
}
processOptions(options);
...
function NodeMainTemplatePlugin(asyncChunkLoading) { this.asyncChunkLoading = asyncChunkLoading; }
n/a
apply = function (mainTemplate) { var self = this; mainTemplate.plugin("local-vars", function(source, chunk) { if(chunk.chunks.length > 0) { return this.asString([ source, "", "// object to store loaded chunks", "// \"0\" means \"already loaded\"", "var installedChunks = {", this.indent( chunk.ids.map(function(id) { return id + ": 0"; }).join(",\n") ), "};" ]); } return source; }); mainTemplate.plugin("require-extensions", function(source, chunk) { if(chunk.chunks.length > 0) { return this.asString([ source, "", "// uncatched error handler for webpack runtime", this.requireFn + ".oe = function(err) {", this.indent([ "process.nextTick(function() {", this.indent("throw err; // catch this error by using System.import().catch()"), "});" ]), "};" ]); } return source; }); mainTemplate.plugin("require-ensure", function(_, chunk, hash) { var chunkFilename = this.outputOptions.chunkFilename; var chunkMaps = chunk.getChunkMaps(); var insertMoreModules = [ "var moreModules = chunk.modules, chunkIds = chunk.ids;", "for(var moduleId in moreModules) {", this.indent(this.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")), "}" ]; if(self.asyncChunkLoading) { return this.asString([ "// \"0\" is the signal for \"already loaded\"", "if(installedChunks[chunkId] === 0)", this.indent([ "return Promise.resolve();" ]), "// array of [resolve, reject, promise] means \"currently loading\"", "if(installedChunks[chunkId])", this.indent([ "return installedChunks[chunkId][2];" ]), "// load the chunk and return promise to it", "var promise = new Promise(function(resolve, reject) {", this.indent([ "installedChunks[chunkId] = [resolve, reject];", "var filename = __dirname + " + 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) { 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) + \"" } }) + ";", "require('fs').readFile(filename, 'utf-8', function(err, content) {", this.indent([ "if(err) return reject(err);", "var chunk = {};", "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" + "(chunk, require, require('path').dirname(filename), filename);" ].concat(insertMoreModules).concat([ "var callbacks = [];", "for(var i = 0; i < chunkIds.length; i++) {", this.indent([ "if(installedChunks[chunkIds[i]])", this.indent([ "callbacks = callbacks.concat(installedChunks[chunkIds[i]][0]);" ]), "installedChunks[chunkIds[i]] = 0;" ]), "}", "for(i = 0; i < callbacks.length; i++)", this.indent("callbacks[i]();") ])), "});" ]), "});", "return installedChunks[chunkId][2] = promise;" ]); } else { var request = this.applyPluginsWaterfall("asset-path", JSON.stringify("./" + chunkFilename), { hash: "\" + " + this.renderCurrentHashCode(hash) + " + \"", hashWithLength: function(length) { return "\" + " + this.renderCurrentHashCode(hash, length) + " + \""; }.bind(this), ...
...
process.exit(1); // eslint-disable-line no-process-exit
}
throw e;
}
if(argv.progress) {
var ProgressPlugin = require("../lib/ProgressPlugin");
compiler.apply(new ProgressPlugin({
profile: argv.profile
}));
}
function compilerCallback(err, stats) {
if(!options.watch || err) {
// Do not keep cache anymore
...
function NodeSourcePlugin(options) { this.options = options; }
n/a
apply = function (compiler) { var options = this.options; 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"); return nodeLibsBrowser[module]; } else if(type === "mock") { return require.resolve("node-libs-browser/mock/" + module); } else if(type === "empty") { return require.resolve("node-libs-browser/mock/empty"); } else return module; } function addExpression(parser, name, module, type, suffix) { suffix = suffix || ""; parser.plugin("expression " + name, function() { if(this.state.module && this.state.module.resource === getPathToModule(module, type)) return; var mockModule = ParserHelpers.requireFileAsExpression(this.state.module.context, getPathToModule(module, type)); return ParserHelpers.addParsedVariableToModule(this, name, mockModule + suffix); }); } compiler.plugin("compilation", function(compilation, params) { params.normalModuleFactory.plugin("parser", function(parser, parserOptions) { if(parserOptions.node === false) return; var localOptions = options; if(parserOptions.node) localOptions = Object.assign({}, localOptions, parserOptions.node); if(localOptions.global) { parser.plugin("expression global", function() { var retrieveGlobalModule = ParserHelpers.requireFileAsExpression(this.state.module.context, require.resolve("../../buildin/ global.js")); return ParserHelpers.addParsedVariableToModule(this, "global", retrieveGlobalModule); }); } if(localOptions.process) { var processType = localOptions.process; addExpression(parser, "process", "process", processType); } if(localOptions.console) { var consoleType = localOptions.console; addExpression(parser, "console", "console", consoleType); } var bufferType = localOptions.Buffer; if(bufferType) { addExpression(parser, "Buffer", "buffer", bufferType, ".Buffer"); } if(localOptions.setImmediate) { var setImmediateType = localOptions.setImmediate; addExpression(parser, "setImmediate", "timers", setImmediateType, ".setImmediate"); addExpression(parser, "clearImmediate", "timers", setImmediateType, ".clearImmediate"); } }); }); compiler.plugin("after-resolvers", function(compiler) { Object.keys(nodeLibsBrowser).forEach(function(lib) { if(options[lib] !== false) { compiler.resolvers.normal.apply( new AliasPlugin("described-resolve", { name: lib, onlyModule: true, alias: getPathToModule(lib, options[lib]) }, "resolve") ); } }); }); }
...
process.exit(1); // eslint-disable-line no-process-exit
}
throw e;
}
if(argv.progress) {
var ProgressPlugin = require("../lib/ProgressPlugin");
compiler.apply(new ProgressPlugin({
profile: argv.profile
}));
}
function compilerCallback(err, stats) {
if(!options.watch || err) {
// Do not keep cache anymore
...
class NullDependency extends Dependency { get type() { return "null"; } isEqualResource() { return false; } updateHash() {} }
n/a
class NullDependencyTemplate { apply() {} }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
addParsedVariableToModule = function (parser, name, expression) { if(!parser.state.current.addVariable) return false; var deps = []; parser.parse(expression, { current: { addDependency: function(dep) { dep.userRequest = name; deps.push(dep); } }, module: parser.state.module }); parser.state.current.addVariable(name, expression, deps); return true; }
...
let expression = `require(${JSON.stringify(request[0])})`;
if(scopedName) {
nameIdentifier = `__webpack_provided_${name.replace(/\./g, "_dot_")}`;
}
if(request.length > 1) {
expression += request.slice(1).map(r => `[${JSON.stringify(r)}]`).join("");
}
if(!ParserHelpers.addParsedVariableToModule(this, nameIdentifier, expression)) {
return false;
}
if(scopedName) {
ParserHelpers.toConstantDependency(nameIdentifier).bind(this)(expr);
}
return true;
});
...
function approve() { return true; }
n/a
evaluateToBoolean = function (value) { return function booleanExpression(expr) { return new BasicEvaluatedExpression().setBoolean(value).setRange(expr.range); }; }
...
]);
});
params.normalModuleFactory.plugin("parser", function(parser, parserOptions) {
parser.plugin("expression __webpack_hash__", ParserHelpers.toConstantDependency("__webpack_require__.h()"));
parser.plugin("evaluate typeof __webpack_hash__", ParserHelpers.evaluateToString("string"));
parser.plugin("evaluate Identifier module.hot", function(expr) {
return ParserHelpers.evaluateToBoolean(!!this.state.compilation.hotUpdateChunkTemplate
)(expr);
});
parser.plugin("call module.hot.accept", function(expr) {
if(!this.state.compilation.hotUpdateChunkTemplate) return false;
if(expr.arguments.length >= 1) {
var arg = this.evaluateExpression(expr.arguments[0]);
var params = [],
requests = [];
...
evaluateToString = function (value) { return function stringExpression(expr) { return new BasicEvaluatedExpression().setString(value).setRange(expr.range); }; }
...
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES
[key]));
});
});
});
}
}
module.exports = APIPlugin;
...
expressionIsUnsupported = function (message) { return function unsupportedExpression(expr) { var dep = new ConstDependency("(void 0)", expr.range); dep.loc = expr.loc; this.state.current.addDependency(dep); if(!this.state.module) return; this.state.module.warnings.push(new UnsupportedFeatureWarning(this.state.module, message)); return true; }; }
...
parser.plugin("evaluate Identifier __dirname", function(expr) {
if(!this.state.module) return;
return ParserHelpers.evaluateToString(this.state.module.context)(expr);
});
parser.plugin("expression require.main", ParserHelpers.toConstantDependency("__webpack_require__.c[__webpack_require__
.s]"));
parser.plugin(
"expression require.extensions",
ParserHelpers.expressionIsUnsupported("require.extensions is not supported
by webpack. Use a loader instead.")
);
parser.plugin("expression module.loaded", ParserHelpers.toConstantDependency("module.l"));
parser.plugin("expression module.id", ParserHelpers.toConstantDependency("module.i"));
parser.plugin("expression module.exports", function() {
const module = this.state.module;
const isHarmony = module.meta && module.meta.harmonyModule;
if(!isHarmony)
...
requireFileAsExpression = function (context, pathToModule) { var moduleJsPath = path.relative(context, pathToModule); if(!/^[A-Z]:/i.test(moduleJsPath)) { moduleJsPath = "./" + moduleJsPath.replace(/\\/g, "/"); } return "require(" + JSON.stringify(moduleJsPath) + ")"; }
...
parser.plugin("typeof System", ParserHelpers.toConstantDependency(JSON.stringify("object")));
parser.plugin("evaluate typeof System", ParserHelpers.evaluateToString("object"));
setNotSupported("System.set");
setNotSupported("System.get");
setNotSupported("System.register");
parser.plugin("expression System", function() {
const systemPolyfillRequire = ParserHelpers.requireFileAsExpression(
this.state.module.context, require.resolve("../../buildin/system.js"));
return ParserHelpers.addParsedVariableToModule(this, "System", systemPolyfillRequire);
});
});
});
}
}
...
function skipTraversal() { return true; }
n/a
toConstantDependency = function (value) { return function constDependency(expr) { var dep = new ConstDependency(value, expr.range); dep.loc = expr.loc; this.state.current.addDependency(dep); return true; }; }
...
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS
[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
});
}
}
...
class RequireContextDependency extends ContextDependency { constructor(request, recursive, regExp, range) { super(request, recursive, regExp); this.range = range; } get type() { return "require.context"; } }
n/a
class ModuleDependencyTemplateAsRequireId { apply(dep, source, outputOptions, requestShortener) { if(!dep.range) return; const comment = outputOptions.pathinfo ? `/*! ${requestShortener.shorten(dep.request)} */ ` : ""; let content; if(dep.module) content = `__webpack_require__(${comment}${JSON.stringify(dep.module.id)})`; else content = require("./WebpackMissingModule").module(dep.request); source.replace(dep.range[0], dep.range[1] - 1, content); } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class RequireEnsureDependency extends NullDependency { constructor(block) { super(); this.block = block; } get type() { return "require.ensure"; } }
n/a
class RequireEnsureDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { const depBlock = dep.block; const wrapper = DepBlockHelpers.getLoadDepBlockWrapper(depBlock, outputOptions, requestShortener, "require.ensure"); const errorCallbackExists = depBlock.expr.arguments.length === 4 || (!depBlock.chunkName && depBlock.expr.arguments.length === 3); const startBlock = wrapper[0] + "("; const middleBlock = `).bind(null, __webpack_require__)${wrapper[1]}`; const endBlock = `${middleBlock}__webpack_require__.oe${wrapper[2]}`; source.replace(depBlock.expr.range[0], depBlock.expr.arguments[1].range[0] - 1, startBlock); if(errorCallbackExists) { source.replace(depBlock.expr.arguments[1].range[1], depBlock.expr.arguments[2].range[0] - 1, middleBlock); source.replace(depBlock.expr.arguments[2].range[1], depBlock.expr.range[1] - 1, wrapper[2]); } else { source.replace(depBlock.expr.arguments[1].range[1], depBlock.expr.range[1] - 1, endBlock); } } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class RequireEnsureItemDependency extends ModuleDependency { constructor(request) { super(request); } get type() { return "require.ensure item"; } }
n/a
class NullDependencyTemplate { apply() {} }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class RequireHeaderDependency extends NullDependency { constructor(range) { super(); if(!Array.isArray(range)) throw new Error("range must be valid"); this.range = range; } }
n/a
class RequireHeaderDependencyTemplate { apply(dep, source) { source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__"); } applyAsTemplateArgument(name, dep, source) { source.replace(dep.range[0], dep.range[1] - 1, "require"); } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class RequireIncludeDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; } get type() { return "require.include"; } }
n/a
class RequireIncludeDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { const comment = this.getOptionalComment(outputOptions.pathinfo && dep.module, requestShortener.shorten(dep.request)); source.replace(dep.range[0], dep.range[1] - 1, `undefined${comment}`); } getOptionalComment(shouldHaveComment, shortenedRequest) { if(shouldHaveComment) { return ""; } return `/*! require.include ${shortenedRequest} */`; } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class RequireResolveContextDependency extends ContextDependency { constructor(request, recursive, regExp, range, valueRange) { super(request, recursive, regExp); this.range = range; this.valueRange = valueRange; } get type() { return "amd require context"; } getWarnings() { if(!this.critical) { return; } return [ new CriticalDependencyWarning(this.critical) ]; } }
n/a
class ContextDependencyTemplateAsId { apply(dep, source, outputOptions, requestShortener) { const comment = outputOptions.pathinfo ? "/*! " + requestShortener.shorten(dep.request) + " */ " : ""; if(dep.module && dep.module.dependencies && dep.module.dependencies.length > 0) { if(dep.valueRange) { if(Array.isArray(dep.replaces)) { for(let i = 0; i < dep.replaces.length; i++) { const rep = dep.replaces[i]; source.replace(rep.range[0], rep.range[1] - 1, rep.value); } } 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 { source.replace(dep.range[0], dep.range[1] - 1, "__webpack_require__(" + comment + JSON.stringify(dep.module.id) + ").resolve "); } } else { const content = require("./WebpackMissingModule").module(dep.request); source.replace(dep.range[0], dep.range[1] - 1, content); } } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class RequireResolveDependency extends ModuleDependency { constructor(request, range) { super(request); this.range = range; } get type() { return "require.resolve"; } }
n/a
class ModuleDependencyTemplateAsId { apply(dep, source, outputOptions, requestShortener) { if(!dep.range) return; const comment = outputOptions.pathinfo ? `/*! ${requestShortener.shorten(dep.request)} */ ` : ""; let content; if(dep.module) content = comment + JSON.stringify(dep.module.id); else content = require("./WebpackMissingModule").module(dep.request); source.replace(dep.range[0], dep.range[1] - 1, content); } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
class RequireResolveHeaderDependency extends NullDependency { constructor(range) { super(); if(!Array.isArray(range)) throw new Error("range must be valid"); this.range = range; } }
n/a
class RequireResolveHeaderDependencyTemplate { apply(dep, source) { source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); } applyAsTemplateArgument(name, dep, source) { source.replace(dep.range[0], dep.range[1] - 1, "/*require.resolve*/"); } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
size => { if(size <= 0) { return "0 bytes"; } const abbreviations = ["bytes", "kB", "MB", "GB"]; const index = Math.floor(Math.log(size) / Math.log(1000)); return `${+(size / Math.pow(1000, index)).toPrecision(3)} ${abbreviations[index]}`; }
...
}]
];
obj.assets.forEach(asset => {
t.push([{
value: asset.name,
color: getAssetColor(asset, colors.green)
}, {
value: SizeFormatHelpers.formatSize(asset.size),
color: getAssetColor(asset, colors.normal)
}, {
value: asset.chunks.join(", "),
color: colors.bold
}, {
value: asset.emitted ? "[emitted]" : "",
color: colors.green
...
class UnsupportedDependency extends NullDependency { constructor(request, range) { super(); this.request = request; this.range = range; } }
n/a
class UnsupportedDependencyTemplate { apply(dep, source, outputOptions, requestShortener) { source.replace(dep.range[0], dep.range[1], webpackMissingModule(dep.request)); } }
...
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
...
request => `!(function webpackMissingModule() { ${exports.moduleCode(request)} }())`
n/a
(request) => { const errorCode = toErrorCode(`Cannot find module "${request}"`); return `${errorCode} throw e;`; }
...
}
source() {
const sourceModule = this.dependencies[0].module;
let str;
if(!sourceModule) {
str = WebpackMissingModule.moduleCode(this.sourceRequest);
} else {
str = `module.exports = (__webpack_require__(${sourceModule.id}))`;
switch(this.type) {
case "require":
str += `(${JSON.stringify(this.request)})`;
break;
...
(request) => { const errorCode = toErrorCode(`Cannot find module "${request}"`); return `Promise.reject(function webpackMissingModule() { ${errorCode}; return e; }())`; }
n/a
(context, identifier) => { return identifier .split(/([|! ])/) .map(str => looksLikeAbsolutePath(str) ? normalizePathSeparator(path.relative(context, str)) : str) .join(""); }
...
apply(compiler) {
compiler.plugin("compilation", compilation => {
compilation.plugin("record-modules", (modules, records) => {
if(!records.modules) records.modules = {};
if(!records.modules.byIdentifier) records.modules.byIdentifier = {};
if(!records.modules.usedIds) records.modules.usedIds = {};
modules.forEach(function(module) {
if(!module.portableId) module.portableId = identifierUtils.makePathsRelative(compiler
.context, module.identifier());
const identifier = module.portableId;
records.modules.byIdentifier[identifier] = module.id;
records.modules.usedIds[module.id] = module.id;
});
});
compilation.plugin("revive-modules", (modules, records) => {
if(!records.modules) return;
...
class AggressiveMergingPlugin { constructor(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 https ://webpack.js.org/plugins/"); } this.options = options || {}; } apply(compiler) { const options = this.options; const minSizeReduce = options.minSizeReduce || 1.5; function getParentsWeight(chunk) { return chunk.parents.map((p) => { return p.isInitial() ? options.entryChunkMultiplicator || 10 : 1; }).reduce((a, b) => { return a + b; }, 0); } compiler.plugin("compilation", (compilation) => { compilation.plugin("optimize-chunks-advanced", (chunks) => { let combinations = []; chunks.forEach((a, idx) => { if(a.isInitial()) return; for(let i = 0; i < idx; i++) { const b = chunks[i]; if(b.isInitial()) continue; combinations.push([b, a]); } }); combinations.forEach((pair) => { const a = pair[0].size({ chunkOverhead: 0 }); const b = pair[1].size({ chunkOverhead: 0 }); const ab = pair[0].integratedSize(pair[1], { chunkOverhead: 0 }); pair.push({ a: a, b: b, ab: ab }); let newSize; if(ab === false) { pair.unshift(false); } else if(options.moveToParents) { const aOnly = ab - b; const bOnly = ab - a; const common = a + b - ab; newSize = common + getParentsWeight(pair[0]) * aOnly + getParentsWeight(pair[1]) * bOnly; pair.push({ aOnly: aOnly, bOnly: bOnly, common: common, newSize: newSize }); } else { newSize = ab; } pair.unshift((a + b) / newSize); }); combinations = combinations.filter((pair) => { return pair[0] !== false; }); combinations.sort((a, b) => { return b[0] - a[0]; }); const pair = combinations[0]; if(!pair) return; if(pair[0] < minSizeReduce) return; if(options.moveToParents) { const commonModules = pair[1].modules.filter((m) => { return pair[2].modules.indexOf(m) >= 0; }); const aOnlyModules = pair[1].modules.filter((m) => { return commonModules.indexOf(m) < 0; }); const bOnlyModules = pair[2].modules.filter((m) => { return commonModules.indexOf(m) < 0; }); aOnlyModules.forEach((m) => { pair[1].removeModule(m); m.removeChunk(pair[1]); pair[1].parents.forEach((c) => { c.addModule(m); m.addChunk(c); }); }); bOnlyModules.forEach((m) => { pair[2].removeModule(m); m.removeChunk(pair[2]); pair[2].parents.forEach((c) => { c.addModule(m); m.addChunk(c); }); }); } if(pair[1].integrate(pair[2], "aggressive-merge")) { chunks.splice(chunks.indexOf(pair[2]), 1); return true; } }); }); } }
n/a
class AggressiveSplittingPlugin { constructor(options) { this.options = options || {}; if(typeof this.options.minSize !== "number") this.options.minSize = 30 * 1024; if(typeof this.options.maxSize !== "number") this.options.maxSize = 50 * 1024; if(typeof this.options.chunkOverhead !== "number") this.options.chunkOverhead = 0; if(typeof this.options.entryChunkMultiplicator !== "number") this.options.entryChunkMultiplicator = 1; } apply(compiler) { compiler.plugin("compilation", (compilation) => { compilation.plugin("optimize-chunks-advanced", (chunks) => { const savedSplits = compilation.records && compilation.records.aggressiveSplits || []; const usedSplits = compilation._aggressiveSplittingSplits ? savedSplits.concat(compilation._aggressiveSplittingSplits) : savedSplits; const minSize = this.options.minSize; const maxSize = this.options.maxSize; // 1. try to restore to recorded splitting for(let j = 0; j < usedSplits.length; j++) { const splitData = usedSplits[j]; for(let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; const chunkModuleNames = chunk.modules.map(m => identifierUtils.makePathsRelative(compiler.context, m.identifier())); if(chunkModuleNames.length < splitData.modules.length) continue; const moduleIndicies = splitData.modules.map(toIndexOf(chunkModuleNames)); const hasAllModules = moduleIndicies.every((idx) => { return idx >= 0; }); if(hasAllModules) { if(chunkModuleNames.length > splitData.modules.length) { const selectedModules = moduleIndicies.map(toChunkModuleIndices(chunk.modules)); const newChunk = compilation.addChunk(); selectedModules.forEach(moveModuleBetween(chunk, newChunk)); chunk.split(newChunk); chunk.name = null; newChunk._fromAggressiveSplitting = true; if(j < savedSplits.length) newChunk._fromAggressiveSplittingIndex = j; if(splitData.id !== null && splitData.id !== undefined) { newChunk.id = splitData.id; } newChunk.origins = chunk.origins.map(copyWithReason); chunk.origins = chunk.origins.map(copyWithReason); return true; } else { if(j < savedSplits.length) chunk._fromAggressiveSplittingIndex = j; chunk.name = null; if(splitData.id !== null && splitData.id !== undefined) { chunk.id = splitData.id; } } } } } // 2. for any other chunk which isn't splitted yet, split it for(let i = 0; i < chunks.length; i++) { const chunk = chunks[i]; const size = chunk.size(this.options); if(size > maxSize && chunk.modules.length > 1) { const newChunk = compilation.addChunk(); const modules = chunk.modules .filter(isNotAEntryModule(chunk.entryModule)) .sort((a, b) => { a = a.identifier(); b = b.identifier(); if(a > b) return 1; if(a < b) return -1; return 0; }); for(let k = 0; k < modules.length; k++) { chunk.moveModule(modules[k], newChunk); const newSize = newChunk.size(this.options); const chunkSize = chunk.size(this.options); // break early if it's fine if(chunkSize < maxSize && newSize < maxSize && newSize >= minSize && chunkSize >= minSize) break; if(newSize > maxSize && k === 0) { // break if there is a single module which is bigger than maxSize break; } if(newSize > maxSize || chunkSize < minSize) { // move it back newChunk.moveModule(modules[k], chunk); // check if it's fine now if(newSize < maxSize && newSize >= minSize && chunkSize >= minSize) break; } } if(newChunk.modules.length > 0) { chunk.split(newChunk); chunk.name = null; newChunk.origins = chunk.origins.map(copyWithReason); chunk.origins = chunk.origins.map(cop ...
n/a
class ChunkModuleIdRangePlugin { constructor(options) { this.options = options; } apply(compiler) { const options = this.options; compiler.plugin("compilation", (compilation) => { compilation.plugin("module-ids", (modules) => { const chunk = this.chunks.filter((chunk) => { return chunk.name === options.name; })[0]; if(!chunk) throw new Error("ChunkModuleIdRangePlugin: Chunk with name '" + options.name + "' was not found"); let currentId = options.start; let chunkModules; if(options.order) { chunkModules = chunk.modules.slice(); switch(options.order) { case "index": chunkModules.sort((a, b) => { return a.index - b.index; }); break; case "index2": chunkModules.sort((a, b) => { return a.index2 - b.index2; }); break; default: throw new Error("ChunkModuleIdRangePlugin: unexpected value of order"); } } else { chunkModules = modules.filter((m) => { return m.chunks.indexOf(chunk) >= 0; }); } for(let i = 0; i < chunkModules.length; i++) { const m = chunkModules[i]; if(m.id === null) { m.id = currentId++; } if(options.end && currentId > options.end) break; } }); }); } }
n/a
class CommonsChunkPlugin { constructor(options) { if(arguments.length > 1) { throw new Error(`Deprecation notice: CommonsChunkPlugin now only takes a single argument. Either an options object *or* the name of the chunk. Example: if your old code looked like this: new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js') You would change it to: new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js' }) The available options are: name: string names: string[] filename: string minChunks: number chunks: string[] children: boolean async: boolean minSize: number`); } const normalizedOptions = this.normalizeOptions(options); this.chunkNames = normalizedOptions.chunkNames; this.filenameTemplate = normalizedOptions.filenameTemplate; this.minChunks = normalizedOptions.minChunks; this.selectedChunks = normalizedOptions.selectedChunks; this.children = normalizedOptions.children; this.async = normalizedOptions.async; this.minSize = normalizedOptions.minSize; this.ident = __filename + (nextIdent++); } normalizeOptions(options) { if(Array.isArray(options)) { return { chunkNames: options, }; } if(typeof options === "string") { return { chunkNames: [options], }; } // options.children and options.chunk may not be used together if(options.children && options.chunks) { throw new Error("You can't and it does not make any sense to use \"children\" and \"chunk\" options together."); } /** * options.async and options.filename are also not possible together * as filename specifies how the chunk is called but "async" implies * that webpack will take care of loading this file. */ if(options.async && options.filename) { throw new Error(`You can not specify a filename if you use the \"async\" option. You can however specify the name of the async chunk by passing the desired string as the \"async\" option.`); } /** * Make sure this is either an array or undefined. * "name" can be a string and * "names" a string or an array */ const chunkNames = options.name || options.names ? [].concat(options.name || options.names) : undefined; return { chunkNames: chunkNames, filenameTemplate: options.filename, minChunks: options.minChunks, selectedChunks: options.chunks, children: options.children, async: options.async, minSize: options.minSize }; } apply(compiler) { compiler.plugin("this-compilation", (compilation) => { compilation.plugin(["optimize-chunks", "optimize-extracted-chunks"], (chunks) => { // only optimize once if(compilation[this.ident]) return; compilation[this.ident] = true; /** * Creates a list of "common"" chunks based on the options. * The list is made up of preexisting or newly created chunks. * - If chunk has the name as specified in the chunkNames it is put in the list * - If no chunk with the name as given in chunkNames exists a new chunk is created and added to the list * * These chunks are the "targets" for extracted modules. */ const targetChunks = this.getTargetChunks(chunks, compilation, this.chunkNames, this.children, this.async); // iterate over all our new chunks targetChunks.forEach((targetChunk, idx) => { /** * These chunks are subject to get "common" modules extracted and moved to the common chunk */ const affectedChunks = this.getAffectedChunks(compilation, chunks, targetChunk, targetChunks, idx, this.selectedChunks, this .async, this.children); // bail if no chunk is affected if(!affectedChunks) { return; } // If we are async create an async chunk now // override the "commonChunk" with the newly created async one and use it as commonChunk from now on let asyncChunk; if(this.async) { asyncChunk = this.createAsyncChunk(compilation, this.async, targetChunk); targetChunk = asyncChunk; } ...
...
let nextIdent = 0;
class CommonsChunkPlugin {
constructor(options) {
if(arguments.length > 1) {
throw new Error(`Deprecation notice: CommonsChunkPlugin now only takes a single argument. Either an options
object *or* the name of the chunk.
Example: if your old code looked like this:
new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js
x27;)
You would change it to:
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js' })
The available options are:
name: string
names: string[]
filename: string
minChunks: number
...
class DedupePlugin { apply(compiler) { compiler.plugin("compilation", (compilation) => { compilation.warnings.push(new Error("DedupePlugin: This plugin was removed from webpack. Remove it from your configuration.")); }); } }
n/a
class LimitChunkCountPlugin { constructor(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 https://webpack.js.org/plugins/"); } this.options = options || {}; } apply(compiler) { const options = this.options; compiler.plugin("compilation", (compilation) => { compilation.plugin("optimize-chunks-advanced", (chunks) => { const maxChunks = options.maxChunks; if(!maxChunks) return; if(maxChunks < 1) return; if(chunks.length <= maxChunks) return; if(chunks.length > maxChunks) { const sortedExtendedPairCombinations = chunks.reduce((combinations, a, idx) => { // create combination pairs for(let i = 0; i < idx; i++) { const b = chunks[i]; combinations.push([b, a]); } return combinations; }, []).map((pair) => { // extend combination pairs with size and integrated size const a = pair[0].size(options); const b = pair[1].size(options); const ab = pair[0].integratedSize(pair[1], options); return [a + b - ab, ab, pair[0], pair[1], a, b]; }).filter((extendedPair) => { // filter pairs that do not have an integratedSize // meaning they can NOT be integrated! return extendedPair[1] !== false; }).sort((a, b) => { // sadly javascript does an inplace sort here // sort them by size const diff = b[0] - a[0]; if(diff !== 0) return diff; return a[1] - b[1]; }); const pair = sortedExtendedPairCombinations[0]; if(pair && pair[2].integrate(pair[3], "limit")) { chunks.splice(chunks.indexOf(pair[3]), 1); return true; } } }); }); } }
n/a
class MinChunkSizePlugin { constructor(options) { if(typeof options !== "object" || Array.isArray(options)) { throw new Error("Argument should be an options object.\nFor more info on options, see https://webpack.js.org/plugins/"); } this.options = options; } apply(compiler) { const options = this.options; const minChunkSize = options.minChunkSize; compiler.plugin("compilation", (compilation) => { compilation.plugin("optimize-chunks-advanced", (chunks) => { const equalOptions = { chunkOverhead: 1, entryChunkMultiplicator: 1 }; const sortedSizeFilteredExtendedPairCombinations = chunks.reduce((combinations, a, idx) => { // create combination pairs for(let i = 0; i < idx; i++) { const b = chunks[i]; combinations.push([b, a]); } return combinations; }, []).filter((pair) => { // check if one of the chunks sizes is smaller than the minChunkSize const p0SmallerThanMinChunkSize = pair[0].size(equalOptions) < minChunkSize; const p1SmallerThanMinChunkSize = pair[1].size(equalOptions) < minChunkSize; return p0SmallerThanMinChunkSize || p1SmallerThanMinChunkSize; }).map((pair) => { // extend combination pairs with size and integrated size const a = pair[0].size(options); const b = pair[1].size(options); const ab = pair[0].integratedSize(pair[1], options); return [a + b - ab, ab, pair[0], pair[1]]; }).filter((pair) => { // filter pairs that do not have an integratedSize // meaning they can NOT be integrated! return pair[1] !== false; }).sort((a, b) => { // sadly javascript does an inplace sort here // sort by size const diff = b[0] - a[0]; if(diff !== 0) return diff; return a[1] - b[1]; }); if(sortedSizeFilteredExtendedPairCombinations.length === 0) return; const pair = sortedSizeFilteredExtendedPairCombinations[0]; pair[2].integrate(pair[3], "min-size"); chunks.splice(chunks.indexOf(pair[3]), 1); return true; }); }); } }
n/a
class OccurrenceOrderPlugin { constructor(preferEntry) { if(preferEntry !== undefined && typeof preferEntry !== "boolean") { throw new Error("Argument should be a boolean.\nFor more info on this plugin, see https://webpack.js.org/plugins/"); } this.preferEntry = preferEntry; } apply(compiler) { const preferEntry = this.preferEntry; compiler.plugin("compilation", (compilation) => { compilation.plugin("optimize-module-order", (modules) => { function entryChunks(m) { return m.chunks.map((c) => { const sum = (c.isInitial() ? 1 : 0) + (c.entryModule === m ? 1 : 0); return sum; }).reduce((a, b) => { return a + b; }, 0); } function occursInEntry(m) { if(typeof m.__OccurenceOrderPlugin_occursInEntry === "number") return m.__OccurenceOrderPlugin_occursInEntry; const result = m.reasons.map((r) => { if(!r.module) return 0; return entryChunks(r.module); }).reduce((a, b) => { return a + b; }, 0) + entryChunks(m); return m.__OccurenceOrderPlugin_occursInEntry = result; } function occurs(m) { if(typeof m.__OccurenceOrderPlugin_occurs === "number") return m.__OccurenceOrderPlugin_occurs; const result = m.reasons.map((r) => { if(!r.module) return 0; return r.module.chunks.length; }).reduce((a, b) => { return a + b; }, 0) + m.chunks.length + m.chunks.filter((c) => { return c.entryModule === m; }).length; return m.__OccurenceOrderPlugin_occurs = result; } modules.sort((a, b) => { if(preferEntry) { const aEntryOccurs = occursInEntry(a); const bEntryOccurs = occursInEntry(b); if(aEntryOccurs > bEntryOccurs) return -1; if(aEntryOccurs < bEntryOccurs) return 1; } const aOccurs = occurs(a); const 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; return 0; }); // TODO refactor to Map modules.forEach((m) => { m.__OccurenceOrderPlugin_occursInEntry = undefined; m.__OccurenceOrderPlugin_occurs = undefined; }); }); compilation.plugin("optimize-chunk-order", (chunks) => { function occursInEntry(c) { if(typeof c.__OccurenceOrderPlugin_occursInEntry === "number") return c.__OccurenceOrderPlugin_occursInEntry; const result = c.parents.filter((p) => { return p.isInitial(); }).length; return c.__OccurenceOrderPlugin_occursInEntry = result; } function occurs(c) { return c.blocks.length; } chunks.forEach((c) => { c.modules.sort((a, b) => { if(a.identifier() > b.identifier()) return 1; if(a.identifier() < b.identifier()) return -1; return 0; }); }); chunks.sort((a, b) => { const aEntryOccurs = occursInEntry(a); const bEntryOccurs = occursInEntry(b); if(aEntryOccurs > bEntryOccurs) return -1; if(aEntryOccurs < bEntryOccurs) return 1; const aOccurs = occurs(a); const 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(let 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; }); // TODO refactor to Map chunks.forEach((c) => { c.__OccurenceOrderPlugin_occursInEntry = undefined; }); }); }); } }
n/a
class UglifyJsPlugin { constructor(options) { if(typeof options !== "object" || Array.isArray(options)) options = {}; if(typeof options.compressor !== "undefined") options.compress = options.compressor; this.options = options; } apply(compiler) { const options = this.options; options.test = options.test || /\.js($|\?)/i; const warningsFilter = options.warningsFilter || (() => true); const requestShortener = new RequestShortener(compiler.context); compiler.plugin("compilation", (compilation) => { if(options.sourceMap) { compilation.plugin("build-module", (module) => { // to get detailed location info about errors module.useSourceMap = true; }); } compilation.plugin("optimize-chunk-assets", (chunks, callback) => { const files = []; chunks.forEach((chunk) => files.push.apply(files, chunk.files)); files.push.apply(files, compilation.additionalChunkAssets); const filterdFiles = files.filter(ModuleFilenameHelpers.matchObject.bind(undefined, options)); filterdFiles.forEach((file) => { const oldWarnFunction = uglify.AST_Node.warn_function; const warnings = []; let sourceMap; try { const asset = compilation.assets[file]; if(asset.__UglifyJsPlugin) { compilation.assets[file] = asset.__UglifyJsPlugin; return; } let input; let inputSourceMap; if(options.sourceMap) { if(asset.sourceAndMap) { const sourceAndMap = asset.sourceAndMap(); inputSourceMap = sourceAndMap.map; input = sourceAndMap.source; } else { inputSourceMap = asset.map(); input = asset.source(); } sourceMap = new SourceMapConsumer(inputSourceMap); uglify.AST_Node.warn_function = (warning) => { // eslint-disable-line camelcase const match = /\[.+:([0-9]+),([0-9]+)\]/.exec(warning); const line = +match[1]; const column = +match[2]; const original = sourceMap.originalPositionFor({ line: line, column: column }); if(!original || !original.source || original.source === file) return; if(!warningsFilter(original.source)) return; warnings.push(warning.replace(/\[.+:([0-9]+),([0-9]+)\]/, "") + "[" + requestShortener.shorten(original.source) + ":" + original.line + "," + original.column + "]"); }; } else { input = asset.source(); uglify.AST_Node.warn_function = (warning) => { // eslint-disable-line camelcase warnings.push(warning); }; } uglify.base54.reset(); let ast = uglify.parse(input, { filename: file }); if(options.compress !== false) { ast.figure_out_scope(); const compress = uglify.Compressor(options.compress || { warnings: false }); // eslint-disable-line new-cap ast = compress.compress(ast); } if(options.mangle !== false) { ast.figure_out_scope(options.mangle || {}); ast.compute_char_frequency(options.mangle || {}); ast.mangle_names(options.mangle || {}); if(options.mangle && options.mangle.props) { uglify.mangle_properties(ast, options.mangle.props); } } const output = {}; output.comments = Object.prototype.hasOwnProperty.call(options, "comments") ? options.comments : /^\**!|@preserve|@license /; output.beautify = options.beautify; for(let k in options.output) { output[k] = options.output[k]; } const extractedComments = []; if(options.extractComments) { const condition = {}; if(typeof options.extractComments === "string" || options.extractComments instanceof RegExp) { // extractComments specifies the extract condition and output.comments specifies the preserve condition condition.preserve = output.comments; condition.extract = options.extractComments; } else if(Object.prototype.hasOwnProperty.call(options.extractC ...
n/a
import = function () { throw new Error("System.import cannot be used indirectly"); }
...
return this.asString([
source,
"",
"// uncatched error handler for webpack runtime",
this.requireFn + ".oe = function(err) {",
this.indent([
"process.nextTick(function() {",
this.indent("throw err; // catch this error by using System.import().catch()
x22;),
"});"
]),
"};"
]);
}
return source;
});
...
function webpack(options, callback) { new WebpackOptionsDefaulter().process(options); const compiler = new Compiler(); compiler.options = options; compiler.options = new WebpackOptionsApply().process(options, compiler); new WebEnvironmentPlugin(options.inputFileSystem, options.outputFileSystem).apply(compiler); if(callback) { compiler.run(callback); } return compiler; }
n/a
function Compiler() { Tapable.call(this); this.outputPath = ""; this.outputFileSystem = null; this.inputFileSystem = null; this.recordsInputPath = null; this.recordsOutputPath = null; this.records = {}; this.fileTimestamps = {}; this.contextTimestamps = {}; this.resolvers = { normal: null, loader: null, context: null }; var deprecationReported = false; this.parser = { plugin: function(hook, fn) { if(!deprecationReported) { console.warn("webpack: Using compiler.parser is deprecated.\n" + "Use compiler.plugin(\"compilation\", function(compilation, data) {\n data.normalModuleFactory.plugin(\"parser\", function (parser, options) { parser.plugin(/* ... */); });\n}); instead. " + "It was called " + new Error().stack.split("\n")[2].trim() + "."); deprecationReported = true; } this.plugin("compilation", function(compilation, data) { data.normalModuleFactory.plugin("parser", function(parser) { parser.plugin(hook, fn); }); }); }.bind(this), apply: function() { var args = arguments; if(!deprecationReported) { console.warn("webpack: Using compiler.parser is deprecated.\n" + "Use compiler.plugin(\"compilation\", function(compilation, data) {\n data.normalModuleFactory.plugin(\"parser\", function (parser, options) { parser.apply(/* ... */); });\n}); instead. " + "It was called " + new Error().stack.split("\n")[2].trim() + "."); deprecationReported = true; } this.plugin("compilation", function(compilation, data) { data.normalModuleFactory.plugin("parser", function(parser) { parser.apply.apply(parser, args); }); }); }.bind(this) }; this.options = {}; }
n/a
class WebEnvironmentPlugin { constructor(inputFileSystem, outputFileSystem) { this.inputFileSystem = inputFileSystem; this.outputFileSystem = outputFileSystem; } apply(compiler) { compiler.outputFileSystem = this.outputFileSystem; } }
n/a
class WebpackOptionsApply extends OptionsApply { constructor() { super(); } process(options, compiler) { let ExternalsPlugin; compiler.outputPath = options.output.path; compiler.recordsInputPath = options.recordsInputPath || options.recordsPath; compiler.recordsOutputPath = options.recordsOutputPath || options.recordsPath; compiler.name = options.name; compiler.dependencies = options.dependencies; if(typeof options.target === "string") { let JsonpTemplatePlugin; let NodeSourcePlugin; let NodeTargetPlugin; let NodeTemplatePlugin; switch(options.target) { case "web": JsonpTemplatePlugin = require("./JsonpTemplatePlugin"); NodeSourcePlugin = require("./node/NodeSourcePlugin"); compiler.apply( new JsonpTemplatePlugin(options.output), new FunctionModulePlugin(options.output), new NodeSourcePlugin(options.node), new LoaderTargetPlugin("web") ); break; case "webworker": { let WebWorkerTemplatePlugin = require("./webworker/WebWorkerTemplatePlugin"); NodeSourcePlugin = require("./node/NodeSourcePlugin"); compiler.apply( new WebWorkerTemplatePlugin(), new FunctionModulePlugin(options.output), new NodeSourcePlugin(options.node), new LoaderTargetPlugin("webworker") ); break; } case "node": case "async-node": NodeTemplatePlugin = require("./node/NodeTemplatePlugin"); NodeTargetPlugin = require("./node/NodeTargetPlugin"); compiler.apply( new NodeTemplatePlugin({ asyncChunkLoading: options.target === "async-node" }), new FunctionModulePlugin(options.output), new NodeTargetPlugin(), new LoaderTargetPlugin("node") ); break; case "node-webkit": JsonpTemplatePlugin = require("./JsonpTemplatePlugin"); NodeTargetPlugin = require("./node/NodeTargetPlugin"); 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": case "electron-main": NodeTemplatePlugin = require("./node/NodeTemplatePlugin"); NodeTargetPlugin = require("./node/NodeTargetPlugin"); ExternalsPlugin = require("./ExternalsPlugin"); compiler.apply( new NodeTemplatePlugin({ asyncChunkLoading: true }), new FunctionModulePlugin(options.output), new NodeTargetPlugin(), new ExternalsPlugin("commonjs", [ "app", "auto-updater", "browser-window", "content-tracing", "dialog", "electron", "global-shortcut", "ipc", "ipc-main", "menu", "menu-item", "power-monitor", "power-save-blocker", "protocol", "session", "web-contents", "tray", "clipboard", "crash-reporter", "native-image", "screen", "shell" ]), new LoaderTargetPlugin(options.target) ); break; case "electron-renderer": JsonpTemplatePlugin = require("./JsonpTemplatePlugin"); NodeTargetPlugin = require("./node/NodeTargetPlugin"); ExternalsPlugin = require("./ExternalsPlugin"); compiler.apply( new JsonpTemplatePlugin(options.output), new FunctionModulePlugin(options.output), new NodeTargetPlugin(), new ExternalsPlugin("commonjs", [ "desktop-capturer", "electron", "ipc", "ipc-renderer", "remote", "web-frame", "clipboard", "crash-reporter", "native-image", "screen", "shell" ]), new LoaderTargetPlugin(options.target) ); break; default: throw new Error("Unsupported target '" + options.target + "'."); ...
n/a
class WebpackOptionsDefaulter extends OptionsDefaulter { constructor() { super(); this.set("devtool", false); this.set("cache", true); this.set("context", process.cwd()); this.set("target", "web"); this.set("module.unknownContextRequest", "."); this.set("module.unknownContextRegExp", false); this.set("module.unknownContextRecursive", true); this.set("module.unknownContextCritical", true); this.set("module.exprContextRequest", "."); this.set("module.exprContextRegExp", false); this.set("module.exprContextRecursive", true); this.set("module.exprContextCritical", true); this.set("module.wrappedContextRegExp", /.*/); this.set("module.wrappedContextRecursive", true); this.set("module.wrappedContextCritical", false); this.set("module.strictExportPresence", false); this.set("module.unsafeCache", true); this.set("output", "call", (value, options) => { if(typeof value === "string") { return { filename: value }; } else if(typeof value !== "object") { return {}; } else { return value; } }); this.set("output.filename", "[name].js"); this.set("output.chunkFilename", "make", (options) => { const filename = options.output.filename; return filename.indexOf("[name]") >= 0 ? filename.replace("[name]", "[id]") : "[id]." + filename; }); this.set("output.library", ""); this.set("output.hotUpdateFunction", "make", (options) => { return Template.toIdentifier("webpackHotUpdate" + options.output.library); }); this.set("output.jsonpFunction", "make", (options) => { return Template.toIdentifier("webpackJsonp" + options.output.library); }); this.set("output.libraryTarget", "var"); this.set("output.path", process.cwd()); this.set("output.sourceMapFilename", "[file].map[query]"); this.set("output.hotUpdateChunkFilename", "[id].[hash].hot-update.js"); this.set("output.hotUpdateMainFilename", "[hash].hot-update.json"); this.set("output.crossOriginLoading", false); this.set("output.hashFunction", "md5"); this.set("output.hashDigest", "hex"); this.set("output.hashDigestLength", 20); this.set("output.devtoolLineToLine", false); this.set("output.strictModuleExceptionHandling", false); this.set("node", {}); this.set("node.console", false); this.set("node.process", true); this.set("node.global", true); this.set("node.Buffer", true); this.set("node.setImmediate", true); this.set("node.__filename", "mock"); this.set("node.__dirname", "mock"); this.set("performance.maxAssetSize", 250000); this.set("performance.maxEntrypointSize", 250000); this.set("performance.hints", false); this.set("resolve", {}); this.set("resolve.unsafeCache", true); this.set("resolve.modules", ["node_modules"]); this.set("resolve.extensions", [".js", ".json"]); this.set("resolve.aliasFields", "make", (options) => { if(options.target === "web" || options.target === "webworker") return ["browser"]; else return []; }); this.set("resolve.mainFields", "make", (options) => { if(options.target === "web" || options.target === "webworker") return ["browser", "module", "main"]; else return ["module", "main"]; }); this.set("resolveLoader", {}); this.set("resolveLoader.unsafeCache", true); this.set("resolveLoader.mainFields", ["loader", "main"]); this.set("resolveLoader.extensions", [".js", ".json"]); } }
n/a