Completely updated React, fixed #11, (hopefully)

This commit is contained in:
2018-03-04 19:11:49 -05:00
parent 6e0afd6e2a
commit 34e5f5139a
13674 changed files with 333464 additions and 473223 deletions

View File

@@ -47,10 +47,12 @@ class BannerPlugin {
filename = filename.substr(0, querySplit);
}
if(filename.indexOf("/") < 0) {
const lastSlashIndex = filename.lastIndexOf("/");
if(lastSlashIndex === -1) {
basename = filename;
} else {
basename = filename.substr(filename.lastIndexOf("/") + 1);
basename = filename.substr(lastSlashIndex + 1);
}
const comment = compilation.getPath(banner, {

View File

@@ -404,14 +404,14 @@ class Chunk {
return this.addMultiplierAndOverhead(integratedModulesSize, options);
}
getChunkMaps(includeEntries, realHash) {
getChunkMaps(includeInitial, realHash) {
const chunksProcessed = [];
const chunkHashMap = {};
const chunkNameMap = {};
(function addChunk(chunk) {
if(chunksProcessed.indexOf(chunk) >= 0) return;
chunksProcessed.push(chunk);
if(!chunk.hasRuntime() || includeEntries) {
if(!chunk.isInitial() || includeInitial) {
chunkHashMap[chunk.id] = realHash ? chunk.hash : chunk.renderedHash;
if(chunk.name)
chunkNameMap[chunk.id] = chunk.name;

View File

@@ -34,7 +34,7 @@ function byId(a, b) {
function iterationBlockVariable(variables, fn) {
for(let indexVariable = 0; indexVariable < variables.length; indexVariable++) {
let varDep = variables[indexVariable].dependencies;
const varDep = variables[indexVariable].dependencies;
for(let indexVDep = 0; indexVDep < varDep.length; indexVDep++) {
fn(varDep[indexVDep]);
}
@@ -116,8 +116,8 @@ class Compilation extends Tapable {
cacheModule.disconnect();
this._modules[identifier] = cacheModule;
this.modules.push(cacheModule);
cacheModule.errors.forEach(err => this.errors.push(err), this);
cacheModule.warnings.forEach(err => this.warnings.push(err), this);
cacheModule.errors.forEach(err => this.errors.push(err));
cacheModule.warnings.forEach(err => this.warnings.push(err));
return cacheModule;
}
}
@@ -300,9 +300,7 @@ class Compilation extends Tapable {
iterationDependencies(dependencies);
if(_this.profile) {
if(!module.profile) {
module.profile = {};
}
module.profile = module.profile || {};
const time = Date.now() - start;
if(!module.profile.dependencies || time > module.profile.dependencies) {
module.profile.dependencies = time;
@@ -572,112 +570,111 @@ class Compilation extends Tapable {
}
seal(callback) {
const self = this;
self.applyPlugins0("seal");
self.nextFreeModuleIndex = 0;
self.nextFreeModuleIndex2 = 0;
self.preparedChunks.forEach(preparedChunk => {
this.applyPlugins0("seal");
this.nextFreeModuleIndex = 0;
this.nextFreeModuleIndex2 = 0;
this.preparedChunks.forEach(preparedChunk => {
const module = preparedChunk.module;
const chunk = self.addChunk(preparedChunk.name, module);
const entrypoint = self.entrypoints[chunk.name] = new Entrypoint(chunk.name);
const chunk = this.addChunk(preparedChunk.name, module);
const entrypoint = this.entrypoints[chunk.name] = new Entrypoint(chunk.name);
entrypoint.unshiftChunk(chunk);
chunk.addModule(module);
module.addChunk(chunk);
chunk.entryModule = module;
self.assignIndex(module);
self.assignDepth(module);
this.assignIndex(module);
this.assignDepth(module);
});
self.processDependenciesBlocksForChunks(self.chunks.slice());
self.sortModules(self.modules);
self.applyPlugins0("optimize");
this.processDependenciesBlocksForChunks(this.chunks.slice());
this.sortModules(this.modules);
this.applyPlugins0("optimize");
while(self.applyPluginsBailResult1("optimize-modules-basic", self.modules) ||
self.applyPluginsBailResult1("optimize-modules", self.modules) ||
self.applyPluginsBailResult1("optimize-modules-advanced", self.modules)) { /* empty */ }
self.applyPlugins1("after-optimize-modules", self.modules);
while(this.applyPluginsBailResult1("optimize-modules-basic", this.modules) ||
this.applyPluginsBailResult1("optimize-modules", this.modules) ||
this.applyPluginsBailResult1("optimize-modules-advanced", this.modules)) { /* empty */ }
this.applyPlugins1("after-optimize-modules", this.modules);
while(self.applyPluginsBailResult1("optimize-chunks-basic", self.chunks) ||
self.applyPluginsBailResult1("optimize-chunks", self.chunks) ||
self.applyPluginsBailResult1("optimize-chunks-advanced", self.chunks)) { /* empty */ }
self.applyPlugins1("after-optimize-chunks", self.chunks);
while(this.applyPluginsBailResult1("optimize-chunks-basic", this.chunks) ||
this.applyPluginsBailResult1("optimize-chunks", this.chunks) ||
this.applyPluginsBailResult1("optimize-chunks-advanced", this.chunks)) { /* empty */ }
this.applyPlugins1("after-optimize-chunks", this.chunks);
self.applyPluginsAsyncSeries("optimize-tree", self.chunks, self.modules, function sealPart2(err) {
this.applyPluginsAsyncSeries("optimize-tree", this.chunks, this.modules, (err) => {
if(err) {
return callback(err);
}
self.applyPlugins2("after-optimize-tree", self.chunks, self.modules);
this.applyPlugins2("after-optimize-tree", this.chunks, this.modules);
while(self.applyPluginsBailResult("optimize-chunk-modules-basic", self.chunks, self.modules) ||
self.applyPluginsBailResult("optimize-chunk-modules", self.chunks, self.modules) ||
self.applyPluginsBailResult("optimize-chunk-modules-advanced", self.chunks, self.modules)) { /* empty */ }
self.applyPlugins2("after-optimize-chunk-modules", self.chunks, self.modules);
while(this.applyPluginsBailResult("optimize-chunk-modules-basic", this.chunks, this.modules) ||
this.applyPluginsBailResult("optimize-chunk-modules", this.chunks, this.modules) ||
this.applyPluginsBailResult("optimize-chunk-modules-advanced", this.chunks, this.modules)) { /* empty */ }
this.applyPlugins2("after-optimize-chunk-modules", this.chunks, this.modules);
const shouldRecord = self.applyPluginsBailResult("should-record") !== false;
const shouldRecord = this.applyPluginsBailResult("should-record") !== false;
self.applyPlugins2("revive-modules", self.modules, self.records);
self.applyPlugins1("optimize-module-order", self.modules);
self.applyPlugins1("advanced-optimize-module-order", self.modules);
self.applyPlugins1("before-module-ids", self.modules);
self.applyPlugins1("module-ids", self.modules);
self.applyModuleIds();
self.applyPlugins1("optimize-module-ids", self.modules);
self.applyPlugins1("after-optimize-module-ids", self.modules);
this.applyPlugins2("revive-modules", this.modules, this.records);
this.applyPlugins1("optimize-module-order", this.modules);
this.applyPlugins1("advanced-optimize-module-order", this.modules);
this.applyPlugins1("before-module-ids", this.modules);
this.applyPlugins1("module-ids", this.modules);
this.applyModuleIds();
this.applyPlugins1("optimize-module-ids", this.modules);
this.applyPlugins1("after-optimize-module-ids", this.modules);
self.sortItemsWithModuleIds();
this.sortItemsWithModuleIds();
self.applyPlugins2("revive-chunks", self.chunks, self.records);
self.applyPlugins1("optimize-chunk-order", self.chunks);
self.applyPlugins1("before-chunk-ids", self.chunks);
self.applyChunkIds();
self.applyPlugins1("optimize-chunk-ids", self.chunks);
self.applyPlugins1("after-optimize-chunk-ids", self.chunks);
this.applyPlugins2("revive-chunks", this.chunks, this.records);
this.applyPlugins1("optimize-chunk-order", this.chunks);
this.applyPlugins1("before-chunk-ids", this.chunks);
this.applyChunkIds();
this.applyPlugins1("optimize-chunk-ids", this.chunks);
this.applyPlugins1("after-optimize-chunk-ids", this.chunks);
self.sortItemsWithChunkIds();
this.sortItemsWithChunkIds();
if(shouldRecord)
self.applyPlugins2("record-modules", self.modules, self.records);
this.applyPlugins2("record-modules", this.modules, this.records);
if(shouldRecord)
self.applyPlugins2("record-chunks", self.chunks, self.records);
this.applyPlugins2("record-chunks", this.chunks, this.records);
self.applyPlugins0("before-hash");
self.createHash();
self.applyPlugins0("after-hash");
this.applyPlugins0("before-hash");
this.createHash();
this.applyPlugins0("after-hash");
if(shouldRecord)
self.applyPlugins1("record-hash", self.records);
this.applyPlugins1("record-hash", this.records);
self.applyPlugins0("before-module-assets");
self.createModuleAssets();
if(self.applyPluginsBailResult("should-generate-chunk-assets") !== false) {
self.applyPlugins0("before-chunk-assets");
self.createChunkAssets();
this.applyPlugins0("before-module-assets");
this.createModuleAssets();
if(this.applyPluginsBailResult("should-generate-chunk-assets") !== false) {
this.applyPlugins0("before-chunk-assets");
this.createChunkAssets();
}
self.applyPlugins1("additional-chunk-assets", self.chunks);
self.summarizeDependencies();
this.applyPlugins1("additional-chunk-assets", this.chunks);
this.summarizeDependencies();
if(shouldRecord)
self.applyPlugins2("record", self, self.records);
this.applyPlugins2("record", this, this.records);
self.applyPluginsAsync("additional-assets", err => {
this.applyPluginsAsync("additional-assets", err => {
if(err) {
return callback(err);
}
self.applyPluginsAsync("optimize-chunk-assets", self.chunks, err => {
this.applyPluginsAsync("optimize-chunk-assets", this.chunks, err => {
if(err) {
return callback(err);
}
self.applyPlugins1("after-optimize-chunk-assets", self.chunks);
self.applyPluginsAsync("optimize-assets", self.assets, err => {
this.applyPlugins1("after-optimize-chunk-assets", this.chunks);
this.applyPluginsAsync("optimize-assets", this.assets, err => {
if(err) {
return callback(err);
}
self.applyPlugins1("after-optimize-assets", self.assets);
if(self.applyPluginsBailResult("need-additional-seal")) {
self.unseal();
return self.seal(callback);
this.applyPlugins1("after-optimize-assets", this.assets);
if(this.applyPluginsBailResult("need-additional-seal")) {
this.unseal();
return this.seal(callback);
}
return self.applyPluginsAsync("after-seal", callback);
return this.applyPluginsAsync("after-seal", callback);
});
});
});
@@ -685,11 +682,7 @@ class Compilation extends Tapable {
}
sortModules(modules) {
modules.sort((a, b) => {
if(a.index < b.index) return -1;
if(a.index > b.index) return 1;
return 0;
});
modules.sort(byId);
}
reportDependencyErrorsAndWarnings(module, blocks) {
@@ -1097,9 +1090,9 @@ class Compilation extends Tapable {
}
applyModuleIds() {
let unusedIds = [];
const unusedIds = [];
let nextFreeModuleId = 0;
let usedIds = [];
const usedIds = [];
// TODO consider Map when performance has improved https://gist.github.com/sokra/234c077e1299b7369461f1708519c392
const usedIdMap = Object.create(null);
if(this.usedModuleIds) {
@@ -1218,14 +1211,12 @@ class Compilation extends Tapable {
sortItemsWithChunkIds() {
this.chunks.sort(byId);
const modules = this.modules;
for(let indexModule = 0; indexModule < modules.length; indexModule++) {
modules[indexModule].sortItems(true);
for(let indexModule = 0; indexModule < this.modules.length; indexModule++) {
this.modules[indexModule].sortItems(true);
}
const chunks = this.chunks;
for(let indexChunk = 0; indexChunk < chunks.length; indexChunk++) {
chunks[indexChunk].sortItems();
for(let indexChunk = 0; indexChunk < this.chunks.length; indexChunk++) {
this.chunks[indexChunk].sortItems();
}
const byMessage = (a, b) => {
@@ -1253,18 +1244,16 @@ class Compilation extends Tapable {
this.contextDependencies = [];
this.missingDependencies = [];
const children = this.children;
for(let indexChildren = 0; indexChildren < children.length; indexChildren++) {
const child = children[indexChildren];
for(let indexChildren = 0; indexChildren < this.children.length; indexChildren++) {
const child = this.children[indexChildren];
this.fileDependencies = this.fileDependencies.concat(child.fileDependencies);
this.contextDependencies = this.contextDependencies.concat(child.contextDependencies);
this.missingDependencies = this.missingDependencies.concat(child.missingDependencies);
}
const modules = this.modules;
for(let indexModule = 0; indexModule < modules.length; indexModule++) {
const module = modules[indexModule];
for(let indexModule = 0; indexModule < this.modules.length; indexModule++) {
const module = this.modules[indexModule];
if(module.fileDependencies) {
const fileDependencies = module.fileDependencies;
@@ -1425,7 +1414,7 @@ class Compilation extends Tapable {
}
createChildCompiler(name, outputOptions, plugins) {
var idx = (this.childrenCounters[name] || 0);
const idx = (this.childrenCounters[name] || 0);
this.childrenCounters[name] = idx + 1;
return this.compiler.createChildCompiler(this, name, idx, outputOptions, plugins);
}

View File

@@ -6,6 +6,7 @@
const path = require("path");
const Tapable = require("tapable");
const util = require("util");
const Compilation = require("./Compilation");
const Stats = require("./Stats");
@@ -186,35 +187,30 @@ class Compiler extends Tapable {
loader: null,
context: null
};
let deprecationReported = false;
this.parser = {
plugin: (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", (compilation, data) => {
data.normalModuleFactory.plugin("parser", parser => {
parser.plugin(hook, fn);
plugin: util.deprecate(
(hook, fn) => {
this.plugin("compilation", (compilation, data) => {
data.normalModuleFactory.plugin("parser", parser => {
parser.plugin(hook, fn);
});
});
});
},
apply: () => {
const 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", (compilation, data) => {
data.normalModuleFactory.plugin("parser", parser => {
parser.apply.apply(parser, args);
},
"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. "
),
apply: util.deprecate(
() => {
const args = arguments;
this.plugin("compilation", (compilation, data) => {
data.normalModuleFactory.plugin("parser", parser => {
parser.apply.apply(parser, args);
});
});
});
}
},
"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. "
)
};
this.options = {};

View File

@@ -4,8 +4,8 @@
*/
"use strict";
var Tapable = require("tapable");
var DllModule = require("./DllModule");
const Tapable = require("tapable");
const DllModule = require("./DllModule");
class DllModuleFactory extends Tapable {
constructor() {

View File

@@ -42,7 +42,7 @@ class DllReferencePlugin {
manifest = params["dll reference " + manifest];
}
const name = this.options.name || manifest.name;
const sourceType = this.options.sourceType || "var";
const sourceType = this.options.sourceType || (manifest && manifest.type) || "var";
const externals = {};
const source = "dll-reference " + name;
externals[source] = name;

View File

@@ -7,6 +7,9 @@
const DefinePlugin = require("./DefinePlugin");
const needsEnvVarFix = ["8", "9"].indexOf(process.versions.node.split(".")[0]) >= 0 &&
process.platform === "win32";
class EnvironmentPlugin {
constructor(keys) {
if(Array.isArray(keys)) {
@@ -23,6 +26,13 @@ class EnvironmentPlugin {
apply(compiler) {
const definitions = this.keys.reduce((defs, key) => {
// TODO remove once the fix has made its way into Node 8.
// Work around https://github.com/nodejs/node/pull/18463,
// affecting Node 8 & 9 by performing an OS-level
// operation that always succeeds before reading
// environment variables:
if(needsEnvVarFix) require("os").cpus();
const value = process.env[key] !== undefined ? process.env[key] : this.defaultValues[key];
if(value === undefined) {

View File

@@ -55,7 +55,7 @@ class EvalSourceMapDevToolModuleTemplatePlugin {
sourceMap.sources = moduleFilenames;
if(sourceMap.sourcesContent) {
sourceMap.sourcesContent = sourceMap.sourcesContent.map(function(content, i) {
return `${content}\n\n\n${ModuleFilenameHelpers.createFooter(modules[i], this.requestShortener)}`;
return typeof content === "string" ? `${content}\n\n\n${ModuleFilenameHelpers.createFooter(modules[i], this.requestShortener)}` : null;
}, this);
}
sourceMap.sourceRoot = options.sourceRoot || "";

View File

@@ -4,7 +4,7 @@
*/
"use strict";
var ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin");
const ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin");
class ExternalsPlugin {
constructor(type, externals) {

View File

@@ -30,7 +30,7 @@ class FlagDependencyUsagePlugin {
else if(usedExports === true)
module.usedExports = true;
else if(Array.isArray(usedExports)) {
var old = module.usedExports ? module.usedExports.length : -1;
const old = module.usedExports ? module.usedExports.length : -1;
module.usedExports = addToSet(module.usedExports || [], usedExports);
if(module.usedExports.length === old)
return;

View File

@@ -25,6 +25,11 @@ module.exports = class HotModuleReplacementPlugin {
const requestTimeout = this.requestTimeout;
const hotUpdateChunkFilename = compiler.options.output.hotUpdateChunkFilename;
const hotUpdateMainFilename = compiler.options.output.hotUpdateMainFilename;
compiler.plugin("additional-pass", callback => {
if(multiStep)
return setTimeout(callback, fullBuildTimeout);
return callback();
});
compiler.plugin("compilation", (compilation, params) => {
const hotUpdateChunkTemplate = compilation.hotUpdateChunkTemplate;
if(!hotUpdateChunkTemplate) return;
@@ -88,11 +93,6 @@ module.exports = class HotModuleReplacementPlugin {
if(multiStep && !recompilation && !initialPass)
return true;
});
compiler.plugin("additional-pass", callback => {
if(multiStep)
return setTimeout(callback, fullBuildTimeout);
return callback();
});
compilation.plugin("additional-chunk-assets", function() {
const records = this.records;
if(records.hash === this.hash) return;

View File

@@ -29,6 +29,7 @@ class JsonpMainTemplatePlugin {
const chunkMaps = chunk.getChunkMaps();
const crossOriginLoading = this.outputOptions.crossOriginLoading;
const chunkLoadTimeout = this.outputOptions.chunkLoadTimeout;
const jsonpScriptType = this.outputOptions.jsonpScriptType;
const scriptSrcPath = this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), {
hash: `" + ${this.renderCurrentHashCode(hash)} + "`,
hashWithLength: length => `" + ${this.renderCurrentHashCode(hash, length)} + "`,
@@ -48,7 +49,7 @@ class JsonpMainTemplatePlugin {
});
return this.asString([
"var script = document.createElement('script');",
"script.type = 'text/javascript';",
`script.type = ${JSON.stringify(jsonpScriptType)};`,
"script.charset = 'utf-8';",
"script.async = true;",
`script.timeout = ${chunkLoadTimeout};`,
@@ -195,8 +196,8 @@ class JsonpMainTemplatePlugin {
function hotDisposeChunk(chunkId) {
delete installedChunks[chunkId];
}
var parentHotUpdateCallback = this[${JSON.stringify(hotUpdateFunction)}];
this[${JSON.stringify(hotUpdateFunction)}] = ${runtimeSource}`;
var parentHotUpdateCallback = window[${JSON.stringify(hotUpdateFunction)}];
window[${JSON.stringify(hotUpdateFunction)}] = ${runtimeSource}`;
});
mainTemplate.plugin("hash", function(hash) {
hash.update("jsonp");

View File

@@ -99,7 +99,9 @@ module.exports = class MainTemplate extends Template {
});
this.plugin("require-extensions", (source, chunk, hash) => {
const buf = [];
if(chunk.chunks.length > 0) {
const chunkMaps = chunk.getChunkMaps();
// Check if there are non initial chunks which need to be imported using require-ensure
if(Object.keys(chunkMaps.hash).length) {
buf.push("// This file contains only the entry chunk.");
buf.push("// The chunk loading function for additional chunks");
buf.push(`${this.requireFn}.e = function requireEnsure(chunkId) {`);

View File

@@ -7,12 +7,12 @@
class NoEmitOnErrorsPlugin {
apply(compiler) {
compiler.plugin("should-emit", (compilation) => {
if(compilation.errors.length > 0)
if(compilation.getStats().hasErrors())
return false;
});
compiler.plugin("compilation", (compilation) => {
compilation.plugin("should-record", () => {
if(compilation.errors.length > 0)
if(compilation.getStats().hasErrors())
return false;
});
});

View File

@@ -133,7 +133,9 @@ class NormalModuleFactory extends Tapable {
try {
loaders.forEach(item => {
if(typeof item.options === "string" && /^\?/.test(item.options)) {
item.options = this.ruleSet.findOptionsByIdent(item.options.substr(1));
const ident = item.options.substr(1);
item.options = this.ruleSet.findOptionsByIdent(ident);
item.ident = ident;
}
});
} catch(e) {

View File

@@ -6,7 +6,7 @@
function getProperty(obj, name) {
name = name.split(".");
for(var i = 0; i < name.length - 1; i++) {
for(let i = 0; i < name.length - 1; i++) {
obj = obj[name[i]];
if(typeof obj !== "object" || !obj) return;
}
@@ -15,7 +15,7 @@ function getProperty(obj, name) {
function setProperty(obj, name, value) {
name = name.split(".");
for(var i = 0; i < name.length - 1; i++) {
for(let i = 0; i < name.length - 1; i++) {
if(typeof obj[name[i]] !== "object" && typeof obj[name[i]] !== "undefined") return;
if(!obj[name[i]]) obj[name[i]] = {};
obj = obj[name[i]];

View File

@@ -174,6 +174,15 @@ class Parser extends Tapable {
res.setNumber(left.number / right.number);
res.setRange(expr.range);
return res;
} else if(expr.operator === "**") {
left = this.evaluateExpression(expr.left);
right = this.evaluateExpression(expr.right);
if(!left || !right) return;
if(!left.isNumber() || !right.isNumber()) return;
res = new BasicEvaluatedExpression();
res.setNumber(Math.pow(left.number, right.number));
res.setRange(expr.range);
return res;
} else if(expr.operator === "==" || expr.operator === "===") {
left = this.evaluateExpression(expr.left);
right = this.evaluateExpression(expr.right);
@@ -200,6 +209,60 @@ class Parser extends Tapable {
} else if(left.isBoolean() && right.isBoolean()) {
return res.setBoolean(left.bool !== right.bool);
}
} else if(expr.operator === "&") {
left = this.evaluateExpression(expr.left);
right = this.evaluateExpression(expr.right);
if(!left || !right) return;
if(!left.isNumber() || !right.isNumber()) return;
res = new BasicEvaluatedExpression();
res.setNumber(left.number & right.number);
res.setRange(expr.range);
return res;
} else if(expr.operator === "|") {
left = this.evaluateExpression(expr.left);
right = this.evaluateExpression(expr.right);
if(!left || !right) return;
if(!left.isNumber() || !right.isNumber()) return;
res = new BasicEvaluatedExpression();
res.setNumber(left.number | right.number);
res.setRange(expr.range);
return res;
} else if(expr.operator === "^") {
left = this.evaluateExpression(expr.left);
right = this.evaluateExpression(expr.right);
if(!left || !right) return;
if(!left.isNumber() || !right.isNumber()) return;
res = new BasicEvaluatedExpression();
res.setNumber(left.number ^ right.number);
res.setRange(expr.range);
return res;
} else if(expr.operator === ">>>") {
left = this.evaluateExpression(expr.left);
right = this.evaluateExpression(expr.right);
if(!left || !right) return;
if(!left.isNumber() || !right.isNumber()) return;
res = new BasicEvaluatedExpression();
res.setNumber(left.number >>> right.number);
res.setRange(expr.range);
return res;
} else if(expr.operator === ">>") {
left = this.evaluateExpression(expr.left);
right = this.evaluateExpression(expr.right);
if(!left || !right) return;
if(!left.isNumber() || !right.isNumber()) return;
res = new BasicEvaluatedExpression();
res.setNumber(left.number >> right.number);
res.setRange(expr.range);
return res;
} else if(expr.operator === "<<") {
left = this.evaluateExpression(expr.left);
right = this.evaluateExpression(expr.right);
if(!left || !right) return;
if(!left.isNumber() || !right.isNumber()) return;
res = new BasicEvaluatedExpression();
res.setNumber(left.number << right.number);
res.setRange(expr.range);
return res;
}
});
this.plugin("evaluate UnaryExpression", function(expr) {
@@ -242,6 +305,14 @@ class Parser extends Tapable {
} else if(argument.isNumber()) {
return new BasicEvaluatedExpression().setBoolean(!argument.number).setRange(expr.range);
}
} else if(expr.operator === "~") {
const argument = this.evaluateExpression(expr.argument);
if(!argument) return;
if(!argument.isNumber()) return;
const res = new BasicEvaluatedExpression();
res.setNumber(~argument.number);
res.setRange(expr.range);
return res;
}
});
this.plugin("evaluate typeof undefined", function(expr) {
@@ -1047,6 +1118,14 @@ class Parser extends Tapable {
}
walkNewExpression(expression) {
const callee = this.evaluateExpression(expression.callee);
if(callee.isIdentifier()) {
const result = this.applyPluginsBailResult("new " + callee.identifier, expression);
if(result === true) {
return;
}
}
this.walkExpression(expression.callee);
if(expression.arguments)
this.walkExpressions(expression.arguments);

View File

@@ -158,7 +158,7 @@ class SourceMapDevToolPlugin {
const moduleFilenames = modules.map(m => moduleToSourceNameMapping.get(m));
sourceMap.sources = moduleFilenames;
if(sourceMap.sourcesContent && !options.noSources) {
sourceMap.sourcesContent = sourceMap.sourcesContent.map((content, i) => `${content}\n\n\n${ModuleFilenameHelpers.createFooter(modules[i], requestShortener)}`);
sourceMap.sourcesContent = sourceMap.sourcesContent.map((content, i) => typeof content === "string" ? `${content}\n\n\n${ModuleFilenameHelpers.createFooter(modules[i], requestShortener)}` : null);
} else {
sourceMap.sourcesContent = undefined;
}
@@ -181,14 +181,14 @@ class SourceMapDevToolPlugin {
}
let sourceMapFile = compilation.getPath(sourceMapFilename, {
chunk,
filename,
filename: options.fileContext ? path.relative(options.fileContext, filename) : filename,
query,
basename: basename(filename)
});
if(sourceMapFile.indexOf("[contenthash]") !== -1) {
sourceMapFile = sourceMapFile.replace(/\[contenthash\]/g, crypto.createHash("md5").update(sourceMapString).digest("hex"));
}
const sourceMapUrl = path.relative(path.dirname(file), sourceMapFile).replace(/\\/g, "/");
const sourceMapUrl = options.publicPath ? options.publicPath + sourceMapFile.replace(/\\/g, "/") : path.relative(path.dirname(file), sourceMapFile).replace(/\\/g, "/");
if(currentSourceMappingURLComment !== false) {
asset.__SourceMapDevToolData[file] = compilation.assets[file] = new ConcatSource(new RawSource(source), currentSourceMappingURLComment.replace(/\[url\]/g, sourceMapUrl));
}

View File

@@ -50,11 +50,13 @@ class Stats {
}
hasWarnings() {
return this.compilation.warnings.length > 0;
return this.compilation.warnings.length > 0 ||
this.compilation.children.some(child => child.getStats().hasWarnings());
}
hasErrors() {
return this.compilation.errors.length > 0;
return this.compilation.errors.length > 0 ||
this.compilation.children.some(child => child.getStats().hasErrors());
}
// remove a prefixed "!" that can be specified to reverse sort order

View File

@@ -60,6 +60,10 @@ const replacePathVariables = (path, data) => {
const chunkHash = chunk && (chunk.renderedHash || chunk.hash);
const chunkHashWithLength = chunk && chunk.hashWithLength;
if(typeof path === "function") {
path = path(data);
}
if(data.noChunkHash && REGEXP_CHUNKHASH_FOR_TEST.test(path)) {
throw new Error(`Cannot use [chunkhash] for chunk in '${path}' (use [hash] instead)`);
}
@@ -101,9 +105,9 @@ class TemplatedPathPlugin {
const outputOptions = this.outputOptions;
const chunkFilename = outputOptions.chunkFilename || outputOptions.filename;
if(REGEXP_CHUNKHASH_FOR_TEST.test(chunkFilename))
hash.update(JSON.stringify(chunk.getChunkMaps(true, true).hash));
hash.update(JSON.stringify(chunk.getChunkMaps(false, true).hash));
if(REGEXP_NAME_FOR_TEST.test(chunkFilename))
hash.update(JSON.stringify(chunk.getChunkMaps(true, true).name));
hash.update(JSON.stringify(chunk.getChunkMaps(false, true).name));
});
});
}

View File

@@ -171,7 +171,7 @@ class UmdMainTemplatePlugin {
" for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" +
" }\n"
) +
"})(this, function(" + externalsArguments(externals) + ") {\nreturn ", "webpack/universalModuleDefinition"), source, ";\n})");
"})(typeof self !== 'undefined' ? self : this, function(" + externalsArguments(externals) + ") {\nreturn ", "webpack/universalModuleDefinition"), source, ";\n})");
});
mainTemplate.plugin("global-hash-paths", (paths) => {
if(this.names.root) paths = paths.concat(this.names.root);

View File

@@ -61,6 +61,7 @@ class WebpackOptionsDefaulter extends OptionsDefaulter {
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.jsonpScriptType", "text/javascript");
this.set("output.chunkLoadTimeout", 120000);
this.set("output.hashFunction", "md5");
this.set("output.hashDigest", "hex");

View File

@@ -35,10 +35,21 @@ const getSchemaPartText = (schemaPart, additionalPath) => {
while(schemaPart.$ref) schemaPart = getSchemaPart(schemaPart.$ref);
let schemaText = WebpackOptionsValidationError.formatSchema(schemaPart);
if(schemaPart.description)
schemaText += `\n${schemaPart.description}`;
schemaText += `\n-> ${schemaPart.description}`;
return schemaText;
};
const getSchemaPartDescription = schemaPart => {
while(schemaPart.$ref) schemaPart = getSchemaPart(schemaPart.$ref);
if(schemaPart.description)
return `\n-> ${schemaPart.description}`;
return "";
};
const filterChildren = children => {
return children.filter(err => err.keyword !== "anyOf" && err.keyword !== "allOf" && err.keyword !== "oneOf");
};
const indent = (str, prefix, firstLine) => {
if(firstLine) {
return prefix + str.replace(/\n(?!$)/g, "\n" + prefix);
@@ -143,8 +154,16 @@ class WebpackOptionsValidationError extends WebpackError {
return baseMessage;
} else if(err.keyword === "oneOf" || err.keyword === "anyOf") {
if(err.children && err.children.length > 0) {
if(err.schema.length === 1) {
const lastChild = err.children[err.children.length - 1];
const remainingChildren = err.children.slice(0, err.children.length - 1);
return WebpackOptionsValidationError.formatValidationError(Object.assign({}, lastChild, {
children: remainingChildren,
parentSchema: Object.assign({}, err.parentSchema, lastChild.parentSchema)
}));
}
return `${dataPath} should be one of these:\n${getSchemaPartText(err.parentSchema)}\n` +
`Details:\n${err.children.map(err => " * " + indent(WebpackOptionsValidationError.formatValidationError(err), " ", false)).join("\n")}`;
`Details:\n${filterChildren(err.children).map(err => " * " + indent(WebpackOptionsValidationError.formatValidationError(err), " ", false)).join("\n")}`;
}
return `${dataPath} should be one of these:\n${getSchemaPartText(err.parentSchema)}`;
@@ -158,29 +177,33 @@ class WebpackOptionsValidationError extends WebpackError {
} else if(err.keyword === "type") {
switch(err.params.type) {
case "object":
return `${dataPath} should be an object.`;
return `${dataPath} should be an object.${getSchemaPartDescription(err.parentSchema)}`;
case "string":
return `${dataPath} should be a string.`;
return `${dataPath} should be a string.${getSchemaPartDescription(err.parentSchema)}`;
case "boolean":
return `${dataPath} should be a boolean.`;
return `${dataPath} should be a boolean.${getSchemaPartDescription(err.parentSchema)}`;
case "number":
return `${dataPath} should be a number.`;
return `${dataPath} should be a number.${getSchemaPartDescription(err.parentSchema)}`;
case "array":
return `${dataPath} should be an array:\n${getSchemaPartText(err.parentSchema)}`;
}
return `${dataPath} should be ${err.params.type}:\n${getSchemaPartText(err.parentSchema)}`;
} else if(err.keyword === "instanceof") {
return `${dataPath} should be an instance of ${getSchemaPartText(err.parentSchema)}.`;
return `${dataPath} should be an instance of ${getSchemaPartText(err.parentSchema)}`;
} else if(err.keyword === "required") {
const missingProperty = err.params.missingProperty.replace(/^\./, "");
return `${dataPath} misses the property '${missingProperty}'.\n${getSchemaPartText(err.parentSchema, ["properties", missingProperty])}`;
} else if(err.keyword === "minLength" || err.keyword === "minItems") {
} else if(err.keyword === "minimum") {
return `${dataPath} ${err.message}.${getSchemaPartDescription(err.parentSchema)}`;
} else if(err.keyword === "uniqueItems") {
return `${dataPath} should not contain the item '${err.data[err.params.i]}' twice.${getSchemaPartDescription(err.parentSchema)}`;
} else if(err.keyword === "minLength" || err.keyword === "minItems" || err.keyword === "minProperties") {
if(err.params.limit === 1)
return `${dataPath} should not be empty.`;
return `${dataPath} should not be empty.${getSchemaPartDescription(err.parentSchema)}`;
else
return `${dataPath} ${err.message}`;
return `${dataPath} ${err.message}${getSchemaPartDescription(err.parentSchema)}`;
} else if(err.keyword === "absolutePath") {
const baseMessage = `${dataPath}: ${err.message}`;
const baseMessage = `${dataPath}: ${err.message}${getSchemaPartDescription(err.parentSchema)}`;
if(dataPath === "configuration.output.filename") {
return `${baseMessage}\n` +
"Please use output.path to specify absolute path and output.filename for the file name.";

View File

@@ -25,7 +25,7 @@ AMDDefineDependency.Template = class AMDDefineDependencyTemplate {
return {
f: [
"var __WEBPACK_AMD_DEFINE_RESULT__;",
`!(__WEBPACK_AMD_DEFINE_RESULT__ = #.call(exports, __webpack_require__, exports, module),
`!(__WEBPACK_AMD_DEFINE_RESULT__ = (#).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`
],
o: [
@@ -42,7 +42,7 @@ AMDDefineDependency.Template = class AMDDefineDependencyTemplate {
],
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_ARRAY__ = #, __WEBPACK_AMD_DEFINE_RESULT__ = (#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))`
],
ao: [
@@ -70,7 +70,7 @@ AMDDefineDependency.Template = class AMDDefineDependencyTemplate {
],
laf: [
"var __WEBPACK_AMD_DEFINE_ARRAY__, XXX;",
"!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, XXX = (#.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)))"
"!(__WEBPACK_AMD_DEFINE_ARRAY__ = #, XXX = ((#).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)))"
],
lao: [
"var XXX;",

View File

@@ -23,6 +23,18 @@ function isBoundFunctionExpression(expr) {
return true;
}
function isUnboundFunctionExpression(expr) {
if(expr.type === "FunctionExpression") return true;
if(expr.type === "ArrowFunctionExpression") return true;
return false;
}
function isCallable(expr) {
if(isUnboundFunctionExpression(expr)) return true;
if(isBoundFunctionExpression(expr)) return true;
return false;
}
class AMDDefineDependencyParserPlugin {
constructor(options) {
this.options = options;
@@ -38,7 +50,7 @@ class AMDDefineDependencyParserPlugin {
let array, fn, obj, namedModule;
switch(expr.arguments.length) {
case 1:
if(expr.arguments[0].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[0])) {
if(isCallable(expr.arguments[0])) {
// define(f() {...})
fn = expr.arguments[0];
} else if(expr.arguments[0].type === "ObjectExpression") {
@@ -54,7 +66,7 @@ class AMDDefineDependencyParserPlugin {
if(expr.arguments[0].type === "Literal") {
namedModule = expr.arguments[0].value;
// define("...", ...)
if(expr.arguments[1].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[1])) {
if(isCallable(expr.arguments[1])) {
// define("...", f() {...})
fn = expr.arguments[1];
} else if(expr.arguments[1].type === "ObjectExpression") {
@@ -67,7 +79,7 @@ class AMDDefineDependencyParserPlugin {
}
} else {
array = expr.arguments[0];
if(expr.arguments[1].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[1])) {
if(isCallable(expr.arguments[1])) {
// define([...], f() {})
fn = expr.arguments[1];
} else if(expr.arguments[1].type === "ObjectExpression") {
@@ -84,7 +96,7 @@ class AMDDefineDependencyParserPlugin {
// define("...", [...], f() {...})
namedModule = expr.arguments[0].value;
array = expr.arguments[1];
if(expr.arguments[2].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[2])) {
if(isCallable(expr.arguments[2])) {
// define("...", [...], f() {})
fn = expr.arguments[2];
} else if(expr.arguments[2].type === "ObjectExpression") {
@@ -102,7 +114,7 @@ class AMDDefineDependencyParserPlugin {
let fnParams = null;
let fnParamsOffset = 0;
if(fn) {
if(fn.type === "FunctionExpression") fnParams = fn.params;
if(isUnboundFunctionExpression(fn)) fnParams = fn.params;
else if(isBoundFunctionExpression(fn)) {
fnParams = fn.callee.object.params;
fnParamsOffset = fn.arguments.length - 1;
@@ -134,7 +146,7 @@ class AMDDefineDependencyParserPlugin {
});
}
let inTry;
if(fn && fn.type === "FunctionExpression") {
if(fn && isUnboundFunctionExpression(fn)) {
inTry = parser.scope.inTry;
parser.inScope(fnParams, () => {
parser.scope.renames = fnRenames;

View File

@@ -44,8 +44,8 @@ AMDRequireDependency.Template = class AMDRequireDependencyTemplate {
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.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;
@@ -57,8 +57,8 @@ AMDRequireDependency.Template = class AMDRequireDependencyTemplate {
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.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);
}
}

View File

@@ -9,7 +9,7 @@ const HarmonyCompatibilityDependency = require("./HarmonyCompatibilityDependency
module.exports = class HarmonyDetectionParserPlugin {
apply(parser) {
parser.plugin("program", (ast) => {
var isHarmony = ast.body.some(statement => {
const isHarmony = ast.body.some(statement => {
return /^(Import|Export).*Declaration$/.test(statement.type);
});
if(isHarmony) {
@@ -32,7 +32,7 @@ module.exports = class HarmonyDetectionParserPlugin {
module.exportsArgument = "__webpack_exports__";
}
});
var nonHarmonyIdentifiers = ["define", "exports"];
const nonHarmonyIdentifiers = ["define", "exports"];
nonHarmonyIdentifiers.forEach(identifer => {
parser.plugin(`evaluate typeof ${identifer}`, nullInHarmony);
parser.plugin(`typeof ${identifer}`, skipInHarmony);

View File

@@ -3,7 +3,7 @@
Author Tobias Koppers @sokra
*/
"use strict";
var ModuleDependency = require("./ModuleDependency");
const ModuleDependency = require("./ModuleDependency");
class HarmonyImportDependency extends ModuleDependency {
constructor(request, importedVar, range) {

View File

@@ -14,8 +14,8 @@ const lookup = (parent, mod) => {
segs = mod.split("/");
path.pop();
for(var i = 0; i < segs.length; i++) {
var seg = segs[i];
for(let i = 0; i < segs.length; i++) {
const seg = segs[i];
if(seg === "..") path.pop();
else if(seg !== ".") path.push(seg);
}
@@ -25,7 +25,7 @@ const lookup = (parent, mod) => {
LocalModulesHelpers.addLocalModule = (state, name) => {
if(!state.localModules) state.localModules = [];
var m = new LocalModule(state.module, name, state.localModules.length);
const m = new LocalModule(state.module, name, state.localModules.length);
state.localModules.push(m);
return m;
};
@@ -36,7 +36,7 @@ LocalModulesHelpers.getLocalModule = (state, name, namedModule) => {
// resolve dependency name relative to the defining named module
name = lookup(namedModule, name);
}
for(var i = 0; i < state.localModules.length; i++) {
for(let i = 0; i < state.localModules.length; i++) {
if(state.localModules[i].name === name)
return state.localModules[i];
}

View File

@@ -11,6 +11,14 @@ class RequireIncludeDependency extends ModuleDependency {
this.range = range;
}
getReference() {
if(!this.module) return null;
return {
module: this.module,
importedNames: [] // This doesn't use any export
};
}
get type() {
return "require.include";
}

View File

@@ -6,9 +6,11 @@
const ExternalsPlugin = require("../ExternalsPlugin");
const builtins = require("module").builtinModules || Object.keys(process.binding("natives"));
class NodeTargetPlugin {
apply(compiler) {
new ExternalsPlugin("commonjs", Object.keys(process.binding("natives"))).apply(compiler);
new ExternalsPlugin("commonjs", builtins).apply(compiler);
}
}

View File

@@ -7,6 +7,7 @@
const Module = require("../Module");
const Template = require("../Template");
const Parser = require("../Parser");
const crypto = require("crypto");
const acorn = require("acorn");
const escope = require("escope");
const ReplaceSource = require("webpack-sources/lib/ReplaceSource");
@@ -142,6 +143,7 @@ function getPathInAst(ast, node) {
}
function enterNode(n) {
if(!n) return undefined;
const r = n.range;
if(r) {
if(r[0] <= nr[0] && r[1] >= nr[1]) {
@@ -210,6 +212,7 @@ class ConcatenatedModule extends Module {
Object.assign(this.assets, m.assets);
}
}
this._identifier = this._createIdentifier();
}
get modules() {
@@ -219,12 +222,7 @@ class ConcatenatedModule extends Module {
}
identifier() {
return this._orderedConcatenationList.map(info => {
switch(info.type) {
case "concatenated":
return info.module.identifier();
}
}).filter(Boolean).join(" ");
return this._identifier;
}
readableIdentifier(requestShortener) {
@@ -297,6 +295,19 @@ class ConcatenatedModule extends Module {
return list;
}
_createIdentifier() {
let orderedConcatenationListIdentifiers = "";
for(let i = 0; i < this._orderedConcatenationList.length; i++) {
if(this._orderedConcatenationList[i].type === "concatenated") {
orderedConcatenationListIdentifiers += this._orderedConcatenationList[i].module.identifier();
orderedConcatenationListIdentifiers += " ";
}
}
const hash = crypto.createHash("md5");
hash.update(orderedConcatenationListIdentifiers);
return this.rootModule.identifier() + " " + hash.digest("hex");
}
source(dependencyTemplates, outputOptions, requestShortener) {
// Metainfo for each module
const modulesWithInfo = this._orderedConcatenationList.map((info, idx) => {

View File

@@ -82,8 +82,8 @@ class WebWorkerMainTemplatePlugin {
});
return source + "\n" +
`var parentHotUpdateCallback = this[${JSON.stringify(hotUpdateFunction)}];\n` +
`this[${JSON.stringify(hotUpdateFunction)}] = ` +
`var parentHotUpdateCallback = self[${JSON.stringify(hotUpdateFunction)}];\n` +
`self[${JSON.stringify(hotUpdateFunction)}] = ` +
Template.getFunctionContent(require("./WebWorkerMainTemplate.runtime.js"))
.replace(/\/\/\$semicolon/g, ";")
.replace(/\$require\$/g, this.requireFn)