Merge branch 'master' into webpack-2

Conflicts:
	hot/dev-server.js
	hot/only-dev-server.js
	hot/poll.js
	hot/signal.js
	lib/ChunkTemplate.js
	lib/HotModuleReplacement.runtime.js
	lib/HotModuleReplacementPlugin.js
	lib/JsonpMainTemplatePlugin.js
	lib/MainTemplate.js
	lib/NormalModule.js
	lib/Parser.js
	lib/RecordIdsPlugin.js
	lib/WebpackOptionsApply.js
	lib/dependencies/RequireEnsureDependency.js
	lib/node/OldNodeWatchFileSystem.js
	lib/optimize/OccurrenceOrderPlugin.js
	package.json
This commit is contained in:
Tobias Koppers 2015-07-17 09:30:37 +02:00
commit 431a4c791c
138 changed files with 1326 additions and 995 deletions

View File

@ -2,17 +2,27 @@
"env": { "env": {
"node": true "node": true
}, },
"plugins": [
"nodeca"
],
"rules": { "rules": {
"strict": 0, "strict": 0,
"camelcase": 0,
"curly": 0, "curly": 0,
"indent": [0, "tab"],
"nodeca/indent": [2, "tabs", 1 ],
"eol-last": 1, "eol-last": 1,
"no-shadow": 0, "no-shadow": 0,
"no-redeclare": 1, "no-redeclare": 1,
"no-extra-bind": 1, "no-extra-bind": 1,
"no-empty": 0,
"no-process-exit": 1,
"no-underscore-dangle": 0, "no-underscore-dangle": 0,
"no-use-before-define": 0, "no-use-before-define": 0,
"no-unused-vars": 0,
"consistent-return": 0, "consistent-return": 0,
"no-inner-declarations": 1, "no-inner-declarations": 1,
"no-loop-func": 1 "no-loop-func": 1,
"space-before-function-paren": [2, "never"]
} }
} }

1
.gitignore vendored
View File

@ -6,3 +6,4 @@
/examples/*/js /examples/*/js
/coverage /coverage
.DS_Store .DS_Store
*.log

25
.jsbeautifyrc Normal file
View File

@ -0,0 +1,25 @@
{
"js": {
"allowed_file_extensions": ["js", "json", "jshintrc", "jsbeautifyrc"],
"brace_style": "collapse",
"break_chained_methods": false,
"e4x": true,
"eval_code": false,
"end_with_newline": true,
"indent_char": "\t",
"indent_level": 0,
"indent_size": 1,
"indent_with_tabs": true,
"jslint_happy": false,
"jslint_happy_align_switch_case": true,
"space_after_anon_function": false,
"keep_array_indentation": false,
"keep_function_indentation": false,
"max_preserve_newlines": 2,
"preserve_newlines": true,
"space_before_conditional": false,
"space_in_paren": false,
"unescape_strings": false,
"wrap_line_length": 0
}
}

View File

@ -1,6 +1,22 @@
[![webpack](http://webpack.github.io/assets/logo.png)](http://webpack.github.io) [![webpack](http://webpack.github.io/assets/logo.png)](http://webpack.github.io)
[![NPM version][npm-image]][npm-url] [![Gitter chat][gitter-image]][gitter-url] [![Gittip donate button][gittip-image]][gittip-url]
[![NPM version][npm-image]][npm-url] [![Gitter chat][gitter-image]][gitter-url] [![Downloads][downloads-image]][downloads-url]
[![NPM][nodei-image]][nodei-url]
build
[![Build Status][travis-image]][travis-url] [![Appveyor Status][appveyor-image]][appveyor-url] [![Coverage Status][coveralls-image]][coveralls-url]
dependencies
[![Dependency Status][david-image]][david-url] [![devDependency Status][david-dev-image]][david-dev-url] [![peerDependency Status][david-peer-image]][david-peer-url]
donation
[![Gittip donate button][gittip-image]][gittip-url] [![Donate to sokra][donate-image]][donate-url]
[documentation](http://webpack.github.io/docs/?utm_source=github&utm_medium=readme&utm_campaign=top) [documentation](http://webpack.github.io/docs/?utm_source=github&utm_medium=readme&utm_campaign=top)
@ -97,6 +113,7 @@ Please see [Using Loaders](http://webpack.github.io/docs/using-loaders.html) for
**styling** **styling**
* [`style`](https://github.com/webpack/style-loader): Add exports of a module as style to DOM * [`style`](https://github.com/webpack/style-loader): Add exports of a module as style to DOM
* [`css`](https://github.com/webpack/css-loader): Loads css file with resolved imports and returns css code * [`css`](https://github.com/webpack/css-loader): Loads css file with resolved imports and returns css code
* [`cssnext`](https://github.com/cssnext/cssnext-loader): Loads and compiles a css file using [cssnext](http://cssnext.io/)
* [`less`](https://github.com/webpack/less-loader): Loads and compiles a less file * [`less`](https://github.com/webpack/less-loader): Loads and compiles a less file
* [`sass`](https://github.com/jtangelder/sass-loader): Loads and compiles a scss file * [`sass`](https://github.com/jtangelder/sass-loader): Loads and compiles a scss file
* [`stylus`](https://github.com/shama/stylus-loader): Loads and compiles a stylus file * [`stylus`](https://github.com/shama/stylus-loader): Loads and compiles a stylus file
@ -202,7 +219,7 @@ function loadTemplateAsync (name, callback) {
## Tests ## Tests
You can run the Node tests with `npm test`. [![Build status (linux)][travis-image]][travis-url] [![Build status (windows)][appveyor-image]][appveyor-url] [![Test coverage][coveralls-image]][coveralls-url] You can run the Node tests with `npm test`.
You can run the browser tests: You can run the browser tests:
@ -257,8 +274,6 @@ This is a free-time project. The time I invest in it fluctuates. If you use webp
I'm very thankful for every dollar. If you leave your username or email, I may show my thanks by giving you extra support. I'm very thankful for every dollar. If you leave your username or email, I may show my thanks by giving you extra support.
[![Donate to sokra][donate-image]][donate-url]
## Dependencies ## Dependencies
@ -272,7 +287,6 @@ I'm very thankful for every dollar. If you leave your username or email, I may s
* [mkdirp](https://github.com/substack/node-mkdirp) * [mkdirp](https://github.com/substack/node-mkdirp)
* [clone](https://github.com/pvorb/node-clone) * [clone](https://github.com/pvorb/node-clone)
[![Dependency status][david-image]][david-url]
[travis-url]: http://travis-ci.org/webpack/webpack [travis-url]: http://travis-ci.org/webpack/webpack
[travis-image]: https://img.shields.io/travis/webpack/webpack.svg [travis-image]: https://img.shields.io/travis/webpack/webpack.svg
@ -282,8 +296,16 @@ I'm very thankful for every dollar. If you leave your username or email, I may s
[coveralls-image]: https://img.shields.io/coveralls/webpack/webpack.svg [coveralls-image]: https://img.shields.io/coveralls/webpack/webpack.svg
[npm-url]: https://npmjs.org/package/webpack [npm-url]: https://npmjs.org/package/webpack
[npm-image]: https://img.shields.io/npm/v/webpack.svg [npm-image]: https://img.shields.io/npm/v/webpack.svg
[downloads-image]: http://img.shields.io/npm/dm/webpack.svg
[downloads-url]: http://badge.fury.io/js/webpack
[david-url]: https://david-dm.org/webpack/webpack [david-url]: https://david-dm.org/webpack/webpack
[david-image]: https://img.shields.io/david/webpack/webpack.svg [david-image]: https://img.shields.io/david/webpack/webpack.svg
[david-dev-url]: https://david-dm.org/webpack/webpack#info=devDependencies
[david-dev-image]: https://david-dm.org/webpack/webpack/dev-status.svg
[david-peer-url]: https://david-dm.org/webpack/webpack#info=peerDependencies
[david-peer-image]: https://david-dm.org/webpack/webpack/peer-status.svg
[nodei-image]: https://nodei.co/npm/webpack.png?downloads=true&downloadRank=true&stars=true
[nodei-url]: https://nodei.co/npm/webpack
[donate-url]: http://sokra.github.io/ [donate-url]: http://sokra.github.io/
[donate-image]: https://img.shields.io/badge/donate-sokra-brightgreen.svg [donate-image]: https://img.shields.io/badge/donate-sokra-brightgreen.svg
[gittip-url]: https://www.gittip.com/sokra/ [gittip-url]: https://www.gittip.com/sokra/

View File

@ -16,7 +16,7 @@ matrix:
install: install:
- ps: Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version) - ps: Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)
- npm install - npm install --msvs_version=2013
build: off build: off

View File

@ -25,148 +25,181 @@ function runTimes(compiler, times, deferred) {
} }
var tests = { var tests = {
"normal build": [[0, 1, 5, 10, 50, 100, 200], function(size, deferred) { "normal build": [
webpack({ [0, 1, 5, 10, 50, 100, 200],
context: fixtures, function(size, deferred) {
entry: "./" + size + ".js", webpack({
output: { context: fixtures,
path: outputPath, entry: "./" + size + ".js",
filename: "bundle.js" output: {
} path: outputPath,
}, function(err, stats) { filename: "bundle.js"
if(err) throw err; }
deferred.resolve(); }, function(err, stats) {
}); if(err) throw err;
}], deferred.resolve();
"eval dev build": [[0, 1, 2, 5, 10, 15], function(size, deferred) { });
webpack({ }
context: fixtures, ],
entry: "./" + size + ".big.js", "eval dev build": [
output: { [0, 1, 2, 5, 10, 15],
path: outputPath, function(size, deferred) {
filename: "bundle.js" webpack({
}, context: fixtures,
devtool: "eval" entry: "./" + size + ".big.js",
}, function(err, stats) { output: {
if(err) throw err; path: outputPath,
deferred.resolve(); filename: "bundle.js"
}) },
}], devtool: "eval"
"sourcemap build": [[0, 1, 2, 5, 10, 15], function(size, deferred) { }, function(err, stats) {
webpack({ if(err) throw err;
context: fixtures, deferred.resolve();
entry: "./" + size + ".big.js", })
output: { }
path: outputPath, ],
filename: "bundle.js" "sourcemap build": [
}, [0, 1, 2, 5, 10, 15],
devtool: "source-map" function(size, deferred) {
}, function(err, stats) { webpack({
if(err) throw err; context: fixtures,
deferred.resolve(); entry: "./" + size + ".big.js",
}) output: {
}], path: outputPath,
"cheap sourcemap build": [[0, 1, 2, 5, 10, 15], function(size, deferred) { filename: "bundle.js"
webpack({ },
context: fixtures, devtool: "source-map"
entry: "./" + size + ".big.js", }, function(err, stats) {
output: { if(err) throw err;
path: outputPath, deferred.resolve();
filename: "bundle.js" })
}, }
devtool: "cheap-source-map" ],
}, function(err, stats) { "cheap sourcemap build": [
if(err) throw err; [0, 1, 2, 5, 10, 15],
deferred.resolve(); function(size, deferred) {
}) webpack({
}], context: fixtures,
"build w/ chunks": [[0, 1, 5, 10, 50, 100, 200], function(size, deferred) { entry: "./" + size + ".big.js",
webpack({ output: {
context: fixtures, path: outputPath,
entry: "./" + size + ".async.js", filename: "bundle.js"
output: { },
path: outputPath, devtool: "cheap-source-map"
filename: "bundle.js" }, function(err, stats) {
} if(err) throw err;
}, function(err, stats) { deferred.resolve();
if(err) throw err; })
deferred.resolve(); }
}) ],
}], "build w/ chunks": [
"build w/ chunks": [[0, 1, 5, 10, 50, 100, 200], function(size, deferred) { [0, 1, 5, 10, 50, 100, 200],
webpack({ function(size, deferred) {
context: fixtures, webpack({
entry: "./" + size + ".async.js", context: fixtures,
output: { entry: "./" + size + ".async.js",
path: outputPath, output: {
filename: "bundle.js" path: outputPath,
} filename: "bundle.js"
}, function(err, stats) { }
if(err) throw err; }, function(err, stats) {
deferred.resolve(); if(err) throw err;
}) deferred.resolve();
}], })
"incremental": [[0, 1, 5, 10, 50, 100, 200], function(size, deferred) { }
var compiler = webpack({ ],
cache: true, "build w/ chunks": [
context: fixtures, [0, 1, 5, 10, 50, 100, 200],
entry: "./" + size + ".js", function(size, deferred) {
output: { webpack({
path: outputPath, context: fixtures,
filename: "bundle.js" entry: "./" + size + ".async.js",
} output: {
}); path: outputPath,
runTimes(compiler, 2, deferred); filename: "bundle.js"
}], }
"incremental cheap sourcemap": [[1, 2, 3, 4, 5, 6], function(size, deferred) { }, function(err, stats) {
var compiler = webpack({ if(err) throw err;
cache: true, deferred.resolve();
context: fixtures, })
entry: "./200.js", }
output: { ],
path: outputPath, "incremental": [
filename: "bundle.js" [0, 1, 5, 10, 50, 100, 200],
}, function(size, deferred) {
devtool: "cheap-source-map" var compiler = webpack({
}); cache: true,
runTimes(compiler, size, deferred); context: fixtures,
}], entry: "./" + size + ".js",
"incremental2": [[0, 1, 5, 10, 50, 100, 200], function(size, deferred) { output: {
var compiler = webpack({ path: outputPath,
cache: true, filename: "bundle.js"
context: fixtures, }
entry: "./" + size + ".js", });
output: { runTimes(compiler, 2, deferred);
path: outputPath, }
filename: "bundle.js" ],
} "incremental cheap sourcemap": [
}); [1, 2, 3, 4, 5, 6],
runTimes(compiler, 3, deferred); function(size, deferred) {
}], var compiler = webpack({
"incremental4": [[0, 1, 5, 10, 50, 100, 200], function(size, deferred) { cache: true,
var compiler = webpack({ context: fixtures,
cache: true, entry: "./200.js",
context: fixtures, output: {
entry: "./" + size + ".js", path: outputPath,
output: { filename: "bundle.js"
path: outputPath, },
filename: "bundle.js" devtool: "cheap-source-map"
} });
}); runTimes(compiler, size, deferred);
runTimes(compiler, 5, deferred); }
}], ],
"incremental16": [[0, 1, 5, 10, 50, 100, 200], function(size, deferred) { "incremental2": [
var compiler = webpack({ [0, 1, 5, 10, 50, 100, 200],
cache: true, function(size, deferred) {
context: fixtures, var compiler = webpack({
entry: "./" + size + ".js", cache: true,
output: { context: fixtures,
path: outputPath, entry: "./" + size + ".js",
filename: "bundle.js" output: {
} path: outputPath,
}); filename: "bundle.js"
runTimes(compiler, 17, deferred); }
}], });
runTimes(compiler, 3, deferred);
}
],
"incremental4": [
[0, 1, 5, 10, 50, 100, 200],
function(size, deferred) {
var compiler = webpack({
cache: true,
context: fixtures,
entry: "./" + size + ".js",
output: {
path: outputPath,
filename: "bundle.js"
}
});
runTimes(compiler, 5, deferred);
}
],
"incremental16": [
[0, 1, 5, 10, 50, 100, 200],
function(size, deferred) {
var compiler = webpack({
cache: true,
context: fixtures,
entry: "./" + size + ".js",
output: {
path: outputPath,
filename: "bundle.js"
}
});
runTimes(compiler, 17, deferred);
}
],
}; };
var suite = new Benchmark.Suite; var suite = new Benchmark.Suite;
@ -190,4 +223,6 @@ suite.on("cycle", function(event) {
console.log(b.name + "\t" + Math.floor(1000 * (b.stats.mean - b.stats.moe)) + "\t" + Math.floor(1000 * (b.stats.mean + b.stats.moe))); console.log(b.name + "\t" + Math.floor(1000 * (b.stats.mean - b.stats.moe)) + "\t" + Math.floor(1000 * (b.stats.mean + b.stats.moe)));
}); });
suite.run({ async: true }); suite.run({
async: true
});

View File

@ -3,19 +3,20 @@ var fs = require("fs");
var fixtures = path.join(__dirname, "fixtures"); var fixtures = path.join(__dirname, "fixtures");
try { fs.mkdirSync(fixtures); } catch(e) {} try {
fs.mkdirSync(fixtures);
} catch(e) {}
for(var i = 0; i < 1000; i++) { for(var i = 0; i < 1000; i++) {
var source = []; var source = [];
if(i > 8) if(i > 8)
source.push("require("+ JSON.stringify("./" + (i / 8 | 0) + ".js") + ");"); source.push("require(" + JSON.stringify("./" + (i / 8 | 0) + ".js") + ");");
if(i > 4) if(i > 4)
source.push("require("+ JSON.stringify("./" + (i / 4 | 0) + ".js") + ");"); source.push("require(" + JSON.stringify("./" + (i / 4 | 0) + ".js") + ");");
if(i > 2) if(i > 2)
source.push("require("+ JSON.stringify("./" + (i / 2 | 0) + ".js") + ");"); source.push("require(" + JSON.stringify("./" + (i / 2 | 0) + ".js") + ");");
if(i > 0) if(i > 0)
source.push("require("+ JSON.stringify("./" + (i - 1) + ".js") + ");"); source.push("require(" + JSON.stringify("./" + (i - 1) + ".js") + ");");
source.push("module.exports = " + i + ";"); source.push("module.exports = " + i + ";");
fs.writeFileSync(path.join(fixtures, i + ".js"), source.join("\n"), "utf-8"); fs.writeFileSync(path.join(fixtures, i + ".js"), source.join("\n"), "utf-8");
} }
@ -24,13 +25,13 @@ for(var i = 0; i < 1000; i++) {
var source = []; var source = [];
source.push("require.ensure([], function(require) {"); source.push("require.ensure([], function(require) {");
if(i > 8) if(i > 8)
source.push("require("+ JSON.stringify("./" + (i / 8 | 0) + ".async.js") + ");"); source.push("require(" + JSON.stringify("./" + (i / 8 | 0) + ".async.js") + ");");
if(i > 4) if(i > 4)
source.push("require("+ JSON.stringify("./" + (i / 4 | 0) + ".async.js") + ");"); source.push("require(" + JSON.stringify("./" + (i / 4 | 0) + ".async.js") + ");");
if(i > 2) if(i > 2)
source.push("require("+ JSON.stringify("./" + (i / 2 | 0) + ".async.js") + ");"); source.push("require(" + JSON.stringify("./" + (i / 2 | 0) + ".async.js") + ");");
if(i > 0) if(i > 0)
source.push("require("+ JSON.stringify("./" + (i - 1) + ".async.js") + ");"); source.push("require(" + JSON.stringify("./" + (i - 1) + ".async.js") + ");");
source.push("});"); source.push("});");
source.push("module.exports = " + i + ";"); source.push("module.exports = " + i + ";");
fs.writeFileSync(path.join(fixtures, i + ".async.js"), source.join("\n"), "utf-8"); fs.writeFileSync(path.join(fixtures, i + ".async.js"), source.join("\n"), "utf-8");
@ -39,13 +40,13 @@ for(var i = 0; i < 1000; i++) {
for(var i = 0; i < 100; i++) { for(var i = 0; i < 100; i++) {
var source = []; var source = [];
if(i > 8) if(i > 8)
source.push("require("+ JSON.stringify("./" + (i / 8 | 0) + ".big.js") + ");"); source.push("require(" + JSON.stringify("./" + (i / 8 | 0) + ".big.js") + ");");
if(i > 4) if(i > 4)
source.push("require("+ JSON.stringify("./" + (i / 4 | 0) + ".big.js") + ");"); source.push("require(" + JSON.stringify("./" + (i / 4 | 0) + ".big.js") + ");");
if(i > 2) if(i > 2)
source.push("require("+ JSON.stringify("./" + (i / 2 | 0) + ".big.js") + ");"); source.push("require(" + JSON.stringify("./" + (i / 2 | 0) + ".big.js") + ");");
if(i > 0) if(i > 0)
source.push("require("+ JSON.stringify("./" + (i - 1) + ".big.js") + ");"); source.push("require(" + JSON.stringify("./" + (i - 1) + ".big.js") + ");");
for(var j = 0; j < 300; j++) for(var j = 0; j < 300; j++)
source.push("if(Math.random())hello.world();test.a.b.c.d();x(1,2,3,4);var a,b,c,d,e,f;"); source.push("if(Math.random())hello.world();test.a.b.c.d();x(1,2,3,4);var a,b,c,d,e,f;");
source.push("module.exports = " + i + ";"); source.push("module.exports = " + i + ";");

View File

@ -265,6 +265,12 @@ module.exports = function(optimist, argv, convertOptions) {
}); });
ifArg("output-file", function(value) { ifArg("output-file", function(value) {
console.warn("output.file will be deprecated: Use 'output.filename' instead");
ensureObject(options, "output");
options.output.filename = value;
});
ifArg("output-filename", function(value) {
ensureObject(options, "output"); ensureObject(options, "output");
options.output.filename = value; options.output.filename = value;
}); });

View File

@ -28,7 +28,10 @@ if(module.hot) {
} }
}).catch(function(err) { }).catch(function(err) {
if(module.hot.status() in {abort: 1, fail: 1}) { if(module.hot.status() in {
abort: 1,
fail: 1
}) {
console.warn("[HMR] Cannot apply update. Need to do a full reload!"); console.warn("[HMR] Cannot apply update. Need to do a full reload!");
console.warn("[HMR] " + err.stack || err.message); console.warn("[HMR] " + err.stack || err.message);
window.location.reload(); window.location.reload();
@ -39,7 +42,7 @@ if(module.hot) {
}; };
var addEventListener = window.addEventListener ? function(eventName, listener) { var addEventListener = window.addEventListener ? function(eventName, listener) {
window.addEventListener(eventName, listener, false); window.addEventListener(eventName, listener, false);
} : function (eventName, listener) { } : function(eventName, listener) {
window.attachEvent("on" + eventName, listener); window.attachEvent("on" + eventName, listener);
}; };
addEventListener("message", function(event) { addEventListener("message", function(event) {

View File

@ -20,7 +20,10 @@ if(module.hot) {
ignoreUnaccepted: true ignoreUnaccepted: true
}, function(err, renewedModules) { }, function(err, renewedModules) {
if(err) { if(err) {
if(module.hot.status() in {abort: 1, fail: 1}) { if(module.hot.status() in {
abort: 1,
fail: 1
}) {
console.warn("[HMR] Cannot apply update. Need to do a full reload!"); console.warn("[HMR] Cannot apply update. Need to do a full reload!");
console.warn("[HMR] " + err.stack || err.message); console.warn("[HMR] " + err.stack || err.message);
} else { } else {
@ -40,7 +43,10 @@ if(module.hot) {
} }
}); });
}).catch(function(err) { }).catch(function(err) {
if(module.hot.status() in {abort: 1, fail: 1}) { if(module.hot.status() in {
abort: 1,
fail: 1
}) {
console.warn("[HMR] Cannot check for update. Need to do a full reload!"); console.warn("[HMR] Cannot check for update. Need to do a full reload!");
console.warn("[HMR] " + err.stack || err.message); console.warn("[HMR] " + err.stack || err.message);
} else { } else {
@ -50,7 +56,7 @@ if(module.hot) {
}; };
var addEventListener = window.addEventListener ? function(eventName, listener) { var addEventListener = window.addEventListener ? function(eventName, listener) {
window.addEventListener(eventName, listener, false); window.addEventListener(eventName, listener, false);
} : function (eventName, listener) { } : function(eventName, listener) {
window.attachEvent("on" + eventName, listener); window.attachEvent("on" + eventName, listener);
}; };
addEventListener("message", function(event) { addEventListener("message", function(event) {

View File

@ -5,6 +5,7 @@
/*globals __resourceQuery */ /*globals __resourceQuery */
if(module.hot) { if(module.hot) {
var hotPollInterval = +(__resourceQuery.substr(1)) || (10 * 60 * 1000); var hotPollInterval = +(__resourceQuery.substr(1)) || (10 * 60 * 1000);
function checkForUpdate(fromUpdate) { function checkForUpdate(fromUpdate) {
if(module.hot.status() === "idle") { if(module.hot.status() === "idle") {
module.hot.check(true).then(function(updatedModules) { module.hot.check(true).then(function(updatedModules) {
@ -15,7 +16,10 @@ if(module.hot) {
require("./log-apply-result")(updatedModules, updatedModules); require("./log-apply-result")(updatedModules, updatedModules);
checkForUpdate(true); checkForUpdate(true);
}).catch(function(err) { }).catch(function(err) {
if(module.hot.status() in {abort: 1, fail: 1}) { if(module.hot.status() in {
abort: 1,
fail: 1
}) {
console.warn("[HMR] Cannot apply update."); console.warn("[HMR] Cannot apply update.");
console.warn("[HMR] " + err.stack || err.message); console.warn("[HMR] " + err.stack || err.message);
console.warn("[HMR] You need to restart the application!"); console.warn("[HMR] You need to restart the application!");

View File

@ -18,7 +18,10 @@ if(module.hot) {
ignoreUnaccepted: true ignoreUnaccepted: true
}, function(err, renewedModules) { }, function(err, renewedModules) {
if(err) { if(err) {
if(module.hot.status() in {abort: 1, fail: 1}) { if(module.hot.status() in {
abort: 1,
fail: 1
}) {
console.warn("[HMR] Cannot apply update (Need to do a full reload!)"); console.warn("[HMR] Cannot apply update (Need to do a full reload!)");
console.warn("[HMR] " + err.stack || err.message); console.warn("[HMR] " + err.stack || err.message);
console.warn("[HMR] You need to restart the application!"); console.warn("[HMR] You need to restart the application!");
@ -33,7 +36,10 @@ if(module.hot) {
checkForUpdate(true); checkForUpdate(true);
}); });
}).catch(function(err) { }).catch(function(err) {
if(module.hot.status() in {abort: 1, fail: 1}) { if(module.hot.status() in {
abort: 1,
fail: 1
}) {
console.warn("[HMR] Cannot apply update."); console.warn("[HMR] Cannot apply update.");
console.warn("[HMR] " + err.stack || err.message); console.warn("[HMR] " + err.stack || err.message);
console.warn("[HMR] You need to restart the application!"); console.warn("[HMR] You need to restart the application!");

View File

@ -7,8 +7,7 @@ var BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
var NullFactory = require("./NullFactory"); var NullFactory = require("./NullFactory");
function APIPlugin() { function APIPlugin() {}
}
module.exports = APIPlugin; module.exports = APIPlugin;
var REPLACEMENTS = { var REPLACEMENTS = {
@ -25,8 +24,7 @@ var REPLACEMENT_TYPES = {
__webpack_modules__: "object", // eslint-disable-line camelcase __webpack_modules__: "object", // eslint-disable-line camelcase
__webpack_chunk_load__: "function" // eslint-disable-line camelcase __webpack_chunk_load__: "function" // eslint-disable-line camelcase
}; };
var IGNORES = [ var IGNORES = [];
];
APIPlugin.prototype.apply = function(compiler) { APIPlugin.prototype.apply = function(compiler) {
compiler.plugin("compilation", function(compilation) { compiler.plugin("compilation", function(compilation) {
compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyFactories.set(ConstDependency, new NullFactory());
@ -48,4 +46,4 @@ APIPlugin.prototype.apply = function(compiler) {
return true; return true;
}); });
}); });
}; };

View File

@ -33,7 +33,7 @@ AmdMainTemplatePlugin.prototype.apply = function(compilation) {
} }
}.bind(this)); }.bind(this));
mainTemplate.plugin("global-hash-paths", function(paths) { mainTemplate.plugin("global-hash-paths", function(paths) {
if (this.name) paths.push(this.name); if(this.name) paths.push(this.name);
return paths; return paths;
}.bind(this)); }.bind(this));
mainTemplate.plugin("hash", function(hash) { mainTemplate.plugin("hash", function(hash) {

View File

@ -6,8 +6,7 @@ var async = require("async");
var PrefetchDependency = require("./dependencies/PrefetchDependency"); var PrefetchDependency = require("./dependencies/PrefetchDependency");
var NormalModule = require("./NormalModule"); var NormalModule = require("./NormalModule");
function AutomaticPrefetchPlugin() { function AutomaticPrefetchPlugin() {}
}
module.exports = AutomaticPrefetchPlugin; module.exports = AutomaticPrefetchPlugin;
AutomaticPrefetchPlugin.prototype.apply = function(compiler) { AutomaticPrefetchPlugin.prototype.apply = function(compiler) {
compiler.plugin("compilation", function(compilation, params) { compiler.plugin("compilation", function(compilation, params) {

View File

@ -138,6 +138,3 @@ BasicEvaluatedExpression.prototype.setRange = function(range) {
this.range = range; this.range = range;
return this; return this;
}; };

View File

@ -40,4 +40,4 @@ CachePlugin.prototype.apply = function(compiler) {
callback(); callback();
}); });
} }
}; };

View File

@ -73,7 +73,11 @@ Chunk.prototype.addBlock = function(block) {
}; };
Chunk.prototype.addOrigin = function(module, loc) { Chunk.prototype.addOrigin = function(module, loc) {
this.origins.push({module: module, loc: loc, name: this.name}); this.origins.push({
module: module,
loc: loc,
name: this.name
});
}; };
Chunk.prototype.remove = function(reason) { Chunk.prototype.remove = function(reason) {
@ -123,6 +127,7 @@ Chunk.prototype.integrate = function(other, reason) {
m.rewriteChunkInReasons(other, [this]); m.rewriteChunkInReasons(other, [this]);
}, this); }, this);
other.modules.length = 0; other.modules.length = 0;
function moveChunks(chunks, kind, onChunk) { function moveChunks(chunks, kind, onChunk) {
chunks.forEach(function(c) { chunks.forEach(function(c) {
var idx = c[kind].indexOf(other); var idx = c[kind].indexOf(other);
@ -164,7 +169,7 @@ Chunk.prototype.integrate = function(other, reason) {
}; };
Chunk.prototype.isEmpty = function() { Chunk.prototype.isEmpty = function() {
return (this.modules.length === 0); return this.modules.length === 0;
}; };
Chunk.prototype.updateHash = function(hash) { Chunk.prototype.updateHash = function(hash) {

View File

@ -17,8 +17,8 @@ ChunkTemplate.prototype.render = function(chunk, moduleTemplate, dependencyTempl
var core = this.applyPluginsWaterfall("modules", modules, chunk, moduleTemplate, dependencyTemplates); var core = this.applyPluginsWaterfall("modules", modules, chunk, moduleTemplate, dependencyTemplates);
var source = this.applyPluginsWaterfall("render", core, chunk, moduleTemplate, dependencyTemplates); var source = this.applyPluginsWaterfall("render", core, chunk, moduleTemplate, dependencyTemplates);
if(chunk.modules.some(function(module) { if(chunk.modules.some(function(module) {
return (module.entry); return module.entry;
})) { })) {
source = this.applyPluginsWaterfall("render-with-entry", source, chunk); source = this.applyPluginsWaterfall("render-with-entry", source, chunk);
} }
chunk.rendered = true; chunk.rendered = true;

View File

@ -9,8 +9,7 @@ var ModuleAliasPlugin = require("enhanced-resolve/lib/ModuleAliasPlugin");
var NullFactory = require("./NullFactory"); var NullFactory = require("./NullFactory");
function CompatibilityPlugin() { function CompatibilityPlugin() {}
}
module.exports = CompatibilityPlugin; module.exports = CompatibilityPlugin;
CompatibilityPlugin.prototype.apply = function(compiler) { CompatibilityPlugin.prototype.apply = function(compiler) {

View File

@ -114,6 +114,7 @@ Compilation.prototype.buildModule = function(module, thisCallback) {
this.applyPlugins("build-module", module); this.applyPlugins("build-module", module);
if(module.building) return module.building.push(thisCallback); if(module.building) return module.building.push(thisCallback);
var building = module.building = [thisCallback]; var building = module.building = [thisCallback];
function callback(err) { function callback(err) {
module.building = undefined; module.building = undefined;
building.forEach(function(cb) { building.forEach(function(cb) {
@ -140,6 +141,7 @@ Compilation.prototype.buildModule = function(module, thisCallback) {
Compilation.prototype.processModuleDependencies = function(module, callback) { Compilation.prototype.processModuleDependencies = function(module, callback) {
var dependencies = []; var dependencies = [];
function addDependency(dep) { function addDependency(dep) {
for(var i = 0; i < dependencies.length; i++) { for(var i = 0; i < dependencies.length; i++) {
if(dep.isEqualResource(dependencies[i][0])) { if(dep.isEqualResource(dependencies[i][0])) {
@ -148,6 +150,7 @@ Compilation.prototype.processModuleDependencies = function(module, callback) {
} }
dependencies.push([dep]); dependencies.push([dep]);
} }
function addDependenciesBlock(block) { function addDependenciesBlock(block) {
if(block.dependencies) { if(block.dependencies) {
block.dependencies.forEach(addDependency); block.dependencies.forEach(addDependency);
@ -211,6 +214,7 @@ Compilation.prototype.addModuleDependencies = function(module, dependencies, bai
return !d.optional; return !d.optional;
}).length === 0; }).length === 0;
} }
function errorOrWarningAndCallback(err) { function errorOrWarningAndCallback(err) {
if(isOptional()) { if(isOptional()) {
return warningAndCallback(err); return warningAndCallback(err);
@ -446,6 +450,7 @@ Compilation.prototype.rebuildModule = function(module, thisCallback) {
return module.rebuilding.push(thisCallback); return module.rebuilding.push(thisCallback);
} }
var rebuilding = module.rebuilding = [thisCallback]; var rebuilding = module.rebuilding = [thisCallback];
function callback(err) { function callback(err) {
module.rebuilding = undefined; module.rebuilding = undefined;
rebuilding.forEach(function(cb) { rebuilding.forEach(function(cb) {
@ -624,6 +629,7 @@ Compilation.prototype.processDependenciesBlockForChunk = function processDepende
this.processDependenciesBlockForChunk(b, c); this.processDependenciesBlockForChunk(b, c);
}, this); }, this);
} }
function iteratorDependency(d) { function iteratorDependency(d) {
if(!d.module) { if(!d.module) {
return; return;
@ -656,6 +662,7 @@ Compilation.prototype.removeChunkFromDependencies = function removeChunkFromDepe
this.removeChunkFromDependencies(b, c); this.removeChunkFromDependencies(b, c);
}, this); }, this);
}, this); }, this);
function iteratorDependency(d) { function iteratorDependency(d) {
if(!d.module) { if(!d.module) {
return; return;
@ -817,7 +824,7 @@ Compilation.prototype.createChunkAssets = function createChunkAssets() {
var chunkHash = chunk.hash; var chunkHash = chunk.hash;
var source; var source;
var file; var file;
var filenameTemplate = chunk.filenameTemplate ? chunk.filenameTemplate : var filenameTemplate = chunk.filenameTemplate ? chunk.filenameTemplate :
chunk.initial ? filename : chunk.initial ? filename :
chunkFilename; chunkFilename;
try { try {
@ -853,7 +860,7 @@ Compilation.prototype.createChunkAssets = function createChunkAssets() {
} }
}; };
Compilation.prototype.getPath = function (filename, data) { Compilation.prototype.getPath = function(filename, data) {
data = data || {}; data = data || {};
data.hash = data.hash || this.hash; data.hash = data.hash || this.hash;
return this.mainTemplate.applyPluginsWaterfall("asset-path", filename, data); return this.mainTemplate.applyPluginsWaterfall("asset-path", filename, data);

View File

@ -124,7 +124,7 @@ Watching.prototype.invalidate = function() {
}; };
Watching.prototype.close = function(callback) { Watching.prototype.close = function(callback) {
if(callback === undefined) callback = function(){}; if(callback === undefined) callback = function() {};
if(this.watcher) { if(this.watcher) {
this.watcher.close(); this.watcher.close();
@ -272,6 +272,7 @@ Compiler.prototype.emitAssets = function(compilation, callback) {
var dir = path.dirname(targetFile); var dir = path.dirname(targetFile);
this.outputFileSystem.mkdirp(this.outputFileSystem.join(outputPath, dir), writeOut.bind(this)); this.outputFileSystem.mkdirp(this.outputFileSystem.join(outputPath, dir), writeOut.bind(this));
} else writeOut.call(this); } else writeOut.call(this);
function writeOut(err) { function writeOut(err) {
if(err) return callback(err); if(err) return callback(err);
var targetPath = this.outputFileSystem.join(outputPath, targetFile); var targetPath = this.outputFileSystem.join(outputPath, targetFile);

View File

@ -7,8 +7,7 @@ var BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
var NullFactory = require("./NullFactory"); var NullFactory = require("./NullFactory");
function ConstPlugin() { function ConstPlugin() {}
}
module.exports = ConstPlugin; module.exports = ConstPlugin;
ConstPlugin.prototype.apply = function(compiler) { ConstPlugin.prototype.apply = function(compiler) {
@ -52,4 +51,4 @@ ConstPlugin.prototype.apply = function(compiler) {
this.state.current.addVariable("__resourceQuery", JSON.stringify(this.state.module.splitQuery(this.state.module.resource)[1])); this.state.current.addVariable("__resourceQuery", JSON.stringify(this.state.module.splitQuery(this.state.module.resource)[1]));
return true; return true;
}); });
}; };

View File

@ -152,8 +152,8 @@ ContextModule.prototype.source = function() {
"\t\tthrow new Error(\"Cannot find module '\" + req + \"'.\");\n", "\t\tthrow new Error(\"Cannot find module '\" + req + \"'.\");\n",
"\treturn ", "\treturn ",
hasMultipleChunks ? hasMultipleChunks ?
"Promise.all(ids.slice(1).map(__webpack_require__.e))" : "Promise.all(ids.slice(1).map(__webpack_require__.e))" :
"__webpack_require__.e(ids[1])", "__webpack_require__.e(ids[1])",
".then(function() {\n", ".then(function() {\n",
"\t\treturn __webpack_require__(ids[0]);\n", "\t\treturn __webpack_require__(ids[0]);\n",
"\t});\n", "\t});\n",
@ -185,5 +185,7 @@ ContextModule.prototype.source = function() {
ContextModule.prototype.size = function() { ContextModule.prototype.size = function() {
return this.dependencies.map(function(dep) { return this.dependencies.map(function(dep) {
return dep.userRequest.length + 5; return dep.userRequest.length + 5;
}).reduce(function(a, b) { return a + b; }, 160); }).reduce(function(a, b) {
return a + b;
}, 160);
}; };

View File

@ -123,7 +123,9 @@ ContextModuleFactory.prototype.resolveDependencies = function resolveDependencie
if(!result) return callback(null, []); if(!result) return callback(null, []);
callback(null, result.filter(function(i) { return !!i; }).reduce(function(a, i) { callback(null, result.filter(function(i) {
return !!i;
}).reduce(function(a, i) {
return a.concat(i); return a.concat(i);
}, [])); }, []));
}); });

View File

@ -53,7 +53,7 @@ ContextReplacementPlugin.prototype.apply = function(compiler) {
if(typeof newContentCallback === "function") { if(typeof newContentCallback === "function") {
var origResource = result.resource; var origResource = result.resource;
newContentCallback(result); newContentCallback(result);
if (result.resource !== origResource) { if(result.resource !== origResource) {
result.resource = path.resolve(origResource, result.resource); result.resource = path.resolve(origResource, result.resource);
} }
} else { } else {

View File

@ -28,12 +28,14 @@ DefinePlugin.prototype.apply = function(compiler) {
applyDefine(prefix + key, code); applyDefine(prefix + key, code);
}); });
}(this.definitions, "")); }(this.definitions, ""));
function stringifyObj(obj) { function stringifyObj(obj) {
return "{" + Object.keys(obj).map(function(key) { return "{" + Object.keys(obj).map(function(key) {
var code = obj[key]; var code = obj[key];
return JSON.stringify(key) + ":" + toCode(code); return JSON.stringify(key) + ":" + toCode(code);
}).join(",") + "}"; }).join(",") + "}";
} }
function toCode(code) { function toCode(code) {
if(code === null) return "null"; if(code === null) return "null";
else if(code === undefined) return "undefined"; else if(code === undefined) return "undefined";
@ -42,13 +44,17 @@ DefinePlugin.prototype.apply = function(compiler) {
else if(typeof code === "object") return stringifyObj(code); else if(typeof code === "object") return stringifyObj(code);
else return code + ""; else return code + "";
} }
function applyDefineKey(prefix, key) { function applyDefineKey(prefix, key) {
var splittedKey = key.split("."); var splittedKey = key.split(".");
splittedKey.slice(1).forEach(function(_, i) { splittedKey.slice(1).forEach(function(_, i) {
var fullKey = prefix + splittedKey.slice(0, i + 1).join("."); var fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
compiler.parser.plugin("can-rename " + fullKey, function() { return true; }); compiler.parser.plugin("can-rename " + fullKey, function() {
return true;
});
}); });
} }
function applyDefine(key, code) { function applyDefine(key, code) {
var isTypeof = /^typeof\s+/.test(key); var isTypeof = /^typeof\s+/.test(key);
if(isTypeof) key = key.replace(/^typeof\s+/, ""); if(isTypeof) key = key.replace(/^typeof\s+/, "");
@ -92,6 +98,7 @@ DefinePlugin.prototype.apply = function(compiler) {
return true; return true;
}); });
} }
function applyObjectDefine(key, obj) { function applyObjectDefine(key, obj) {
var code = stringifyObj(obj); var code = stringifyObj(obj);
compiler.parser.plugin("can-rename " + key, function() { compiler.parser.plugin("can-rename " + key, function() {

View File

@ -8,7 +8,7 @@ function Dependency() {
} }
module.exports = Dependency; module.exports = Dependency;
Dependency.prototype.isEqualResource = function(/* other */) { Dependency.prototype.isEqualResource = function( /* other */ ) {
return false; return false;
}; };

View File

@ -13,7 +13,7 @@ EnvironmentPlugin.prototype.apply = function(compiler) {
compiler.apply(new DefinePlugin(this.keys.reduce(function(definitions, key) { compiler.apply(new DefinePlugin(this.keys.reduce(function(definitions, key) {
var value = process.env[key]; var value = process.env[key];
if (value === undefined) { if(value === undefined) {
compiler.plugin("this-compilation", function(compilation) { compiler.plugin("this-compilation", function(compilation) {
var error = new Error(key + " environment variable is undefined."); var error = new Error(key + " environment variable is undefined.");
error.name = "EnvVariableNotDefinedError"; error.name = "EnvVariableNotDefinedError";

View File

@ -14,4 +14,4 @@ EvalDevToolModulePlugin.prototype.apply = function(compiler) {
compiler.plugin("compilation", function(compilation) { compiler.plugin("compilation", function(compilation) {
compilation.moduleTemplate.apply(new EvalDevToolModuleTemplatePlugin(self.sourceUrlComment, self.moduleFilenameTemplate)); compilation.moduleTemplate.apply(new EvalDevToolModuleTemplatePlugin(self.sourceUrlComment, self.moduleFilenameTemplate));
}); });
}; };

View File

@ -20,7 +20,7 @@ EvalDevToolModuleTemplatePlugin.prototype.apply = function(moduleTemplate) {
ModuleFilenameHelpers.createFooter(module, this.requestShortener), ModuleFilenameHelpers.createFooter(module, this.requestShortener),
self.sourceUrlComment.replace(/\[url\]/g, encodeURI(str).replace(/%2F/g, "/").replace(/%20/g, "_").replace(/%5E/g, "^").replace(/%5C/g, "\\").replace(/^\//, "")) self.sourceUrlComment.replace(/\[url\]/g, encodeURI(str).replace(/%2F/g, "/").replace(/%20/g, "_").replace(/%5E/g, "^").replace(/%5C/g, "\\").replace(/^\//, ""))
].join("\n"); ].join("\n");
return new RawSource("eval(" + JSON.stringify(content + footer) + ");" ); return new RawSource("eval(" + JSON.stringify(content + footer) + ");");
}); });
moduleTemplate.plugin("hash", function(hash) { moduleTemplate.plugin("hash", function(hash) {
hash.update("EvalDevToolModuleTemplatePlugin"); hash.update("EvalDevToolModuleTemplatePlugin");

View File

@ -58,7 +58,7 @@ EvalSourceMapDevToolModuleTemplatePlugin.prototype.apply = function(moduleTempla
sourceMap.sourceRoot = ""; sourceMap.sourceRoot = "";
sourceMap.file = module.id + ".js"; sourceMap.file = module.id + ".js";
var footer = self.sourceMapComment.replace(/\[url\]/g, "data:application/json;base64," + new Buffer(JSON.stringify(sourceMap)).toString("base64")); var footer = self.sourceMapComment.replace(/\[url\]/g, "data:application/json;base64," + new Buffer(JSON.stringify(sourceMap)).toString("base64"));
source.__EvalSourceMapDevToolData = new RawSource("eval(" + JSON.stringify(content + footer) + ");" ); source.__EvalSourceMapDevToolData = new RawSource("eval(" + JSON.stringify(content + footer) + ");");
return source.__EvalSourceMapDevToolData; return source.__EvalSourceMapDevToolData;
}); });
moduleTemplate.plugin("hash", function(hash) { moduleTemplate.plugin("hash", function(hash) {

View File

@ -7,8 +7,7 @@ var BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
var NullFactory = require("./NullFactory"); var NullFactory = require("./NullFactory");
function ExtendedAPIPlugin() { function ExtendedAPIPlugin() {}
}
module.exports = ExtendedAPIPlugin; module.exports = ExtendedAPIPlugin;
var REPLACEMENTS = { var REPLACEMENTS = {
@ -43,4 +42,4 @@ ExtendedAPIPlugin.prototype.apply = function(compiler) {
return new BasicEvaluatedExpression().setString(REPLACEMENT_TYPES[key]).setRange(expr.range); return new BasicEvaluatedExpression().setString(REPLACEMENT_TYPES[key]).setRange(expr.range);
}); });
}); });
}; };

View File

@ -41,41 +41,41 @@ ExternalModule.prototype.source = function() {
var request = this.request; var request = this.request;
if(typeof request === "object") request = request[this.type]; if(typeof request === "object") request = request[this.type];
switch(this.type) { switch(this.type) {
case "this": case "this":
case "window": case "window":
case "global": case "global":
if(Array.isArray(request)) { if(Array.isArray(request)) {
str = "(function() { module.exports = " + this.type + request.map(function(r) { str = "(function() { module.exports = " + this.type + request.map(function(r) {
return "[" + JSON.stringify(r) + "]"; return "[" + JSON.stringify(r) + "]";
}).join("") + "; }());"; }).join("") + "; }());";
} else } else
str = "(function() { module.exports = " + this.type + "[" + JSON.stringify(request) + "]; }());"; str = "(function() { module.exports = " + this.type + "[" + JSON.stringify(request) + "]; }());";
break; break;
case "commonjs": case "commonjs":
case "commonjs2": case "commonjs2":
if(Array.isArray(request)) { if(Array.isArray(request)) {
str = "module.exports = require(" + JSON.stringify(request[0]) + ")" + request.slice(1).map(function(r) { str = "module.exports = require(" + JSON.stringify(request[0]) + ")" + request.slice(1).map(function(r) {
return "[" + JSON.stringify(r) + "]"; return "[" + JSON.stringify(r) + "]";
}).join("") + ";"; }).join("") + ";";
} else } else
str = "module.exports = require(" + JSON.stringify(request) + ");"; str = "module.exports = require(" + JSON.stringify(request) + ");";
break; break;
case "amd": case "amd":
case "umd": case "umd":
case "umd2": case "umd2":
str = ""; str = "";
if(this.optional) { if(this.optional) {
str += "if(typeof __WEBPACK_EXTERNAL_MODULE_" + this.id + "__ === 'undefined') {" + WebpackMissingModule.moduleCode(request) + "}\n"; str += "if(typeof __WEBPACK_EXTERNAL_MODULE_" + this.id + "__ === 'undefined') {" + WebpackMissingModule.moduleCode(request) + "}\n";
} }
str += "module.exports = __WEBPACK_EXTERNAL_MODULE_" + this.id + "__;"; str += "module.exports = __WEBPACK_EXTERNAL_MODULE_" + this.id + "__;";
break; break;
default: default:
str = ""; str = "";
if(this.optional) { if(this.optional) {
str += "if(typeof " + request + " === 'undefined') {" + WebpackMissingModule.moduleCode(request) + "}\n"; str += "if(typeof " + request + " === 'undefined') {" + WebpackMissingModule.moduleCode(request) + "}\n";
} }
str += "module.exports = " + request + ";"; str += "module.exports = " + request + ";";
break; break;
} }
if(this.useSourceMap) { if(this.useSourceMap) {
return new OriginalSource(str, this.identifier()); return new OriginalSource(str, this.identifier());

View File

@ -16,6 +16,7 @@ ExternalModuleFactoryPlugin.prototype.apply = function(normalModuleFactory) {
return function(data, callback) { return function(data, callback) {
var context = data.context; var context = data.context;
var dependency = data.dependency; var dependency = data.dependency;
function handleExternal(value, type, callback) { function handleExternal(value, type, callback) {
if(typeof type === "function") { if(typeof type === "function") {
callback = type; callback = type;
@ -53,7 +54,7 @@ ExternalModuleFactoryPlugin.prototype.apply = function(normalModuleFactory) {
} }
callback(null, module); callback(null, module);
}); });
} while(!async); } while (!async);
async = false; async = false;
}()); }());
return; return;

View File

@ -15,4 +15,4 @@ FunctionModulePlugin.prototype.apply = function(compiler) {
compilation.moduleTemplate.requestShortener = this.requestShortener || new RequestShortener(compiler.context); compilation.moduleTemplate.requestShortener = this.requestShortener || new RequestShortener(compiler.context);
compilation.moduleTemplate.apply(new FunctionModuleTemplatePlugin()); compilation.moduleTemplate.apply(new FunctionModuleTemplatePlugin());
}.bind(this)); }.bind(this));
}; };

View File

@ -5,8 +5,7 @@
var ConcatSource = require("webpack-core/lib/ConcatSource"); var ConcatSource = require("webpack-core/lib/ConcatSource");
var PrefixSource = require("webpack-core/lib/PrefixSource"); var PrefixSource = require("webpack-core/lib/PrefixSource");
function FunctionModuleTemplatePlugin() { function FunctionModuleTemplatePlugin() {}
}
module.exports = FunctionModuleTemplatePlugin; module.exports = FunctionModuleTemplatePlugin;
FunctionModuleTemplatePlugin.prototype.apply = function(moduleTemplate) { FunctionModuleTemplatePlugin.prototype.apply = function(moduleTemplate) {

View File

@ -40,6 +40,7 @@ module.exports = function() {
finishChunkLoading(); finishChunkLoading();
throw err; throw err;
}); });
function finishChunkLoading() { function finishChunkLoading() {
hotChunksLoading--; hotChunksLoading--;
if(hotStatus === "prepare") { if(hotStatus === "prepare") {
@ -72,8 +73,8 @@ module.exports = function() {
else if(typeof dep === "function") else if(typeof dep === "function")
hot._selfAccepted = dep; hot._selfAccepted = dep;
else if(typeof dep === "object") else if(typeof dep === "object")
for(var i = 0; i < dep.length; i++) for(var i = 0; i < dep.length; i++)
hot._acceptedDependencies[dep[i]] = callback; hot._acceptedDependencies[dep[i]] = callback;
else else
hot._acceptedDependencies[dep] = callback; hot._acceptedDependencies[dep] = callback;
}, },
@ -82,8 +83,9 @@ module.exports = function() {
hot._selfDeclined = true; hot._selfDeclined = true;
else if(typeof dep === "number") else if(typeof dep === "number")
hot._declinedDependencies[dep] = true; hot._declinedDependencies[dep] = true;
else for(var i = 0; i < dep.length; i++) else
hot._declinedDependencies[dep[i]] = true; for(var i = 0; i < dep.length; i++)
hot._declinedDependencies[dep[i]] = true;
}, },
dispose: function(callback) { dispose: function(callback) {
hot._disposeHandlers.push(callback); hot._disposeHandlers.push(callback);
@ -138,7 +140,8 @@ module.exports = function() {
var hotUpdate, hotUpdateNewHash; var hotUpdate, hotUpdateNewHash;
function toModuleId(id) { function toModuleId(id) {
return (+id) + "" === id ? +id : id; var isNumber = (+id) + "" === id;
return isNumber ? +id : id;
} }
function hotCheck(apply) { function hotCheck(apply) {
@ -166,7 +169,8 @@ module.exports = function() {
}; };
}); });
hotUpdate = {}; hotUpdate = {};
/*foreachInstalledChunks*/ { // eslint-disable-line no-lone-blocks /*foreachInstalledChunks*/
{ // eslint-disable-line no-lone-blocks
/*globals chunkId */ /*globals chunkId */
hotEnsureUpdateChunk(chunkId); hotEnsureUpdateChunk(chunkId);
} }
@ -240,6 +244,9 @@ module.exports = function() {
if(module.hot._selfDeclined) { if(module.hot._selfDeclined) {
return new Error("Aborted because of self decline: " + moduleId); return new Error("Aborted because of self decline: " + moduleId);
} }
if($require$.s === moduleId) {
return;
}
for(var i = 0; i < module.parents.length; i++) { for(var i = 0; i < module.parents.length; i++) {
var parentId = module.parents[i]; var parentId = module.parents[i];
var parent = installedModules[parentId]; var parent = installedModules[parentId];
@ -261,6 +268,7 @@ module.exports = function() {
return [outdatedModules, outdatedDependencies]; return [outdatedModules, outdatedDependencies];
} }
function addAllToSet(a, b) { function addAllToSet(a, b) {
for(var i = 0; i < b.length; i++) { for(var i = 0; i < b.length; i++) {
var item = b[i]; var item = b[i];

View File

@ -51,7 +51,9 @@ HotModuleReplacementPlugin.prototype.apply = function(compiler) {
}); });
records.chunkModuleIds = {}; records.chunkModuleIds = {};
this.chunks.forEach(function(chunk) { this.chunks.forEach(function(chunk) {
records.chunkModuleIds[chunk.id] = chunk.modules.map(function(m) { return m.id; }); records.chunkModuleIds[chunk.id] = chunk.modules.map(function(m) {
return m.id;
});
}); });
}); });
var initialPass = false; var initialPass = false;
@ -150,9 +152,9 @@ HotModuleReplacementPlugin.prototype.apply = function(compiler) {
source, source,
"", "",
hotInitCode hotInitCode
.replace(/\$require\$/g, this.requireFn) .replace(/\$require\$/g, this.requireFn)
.replace(/\$hash\$/g, JSON.stringify(hash)) .replace(/\$hash\$/g, JSON.stringify(hash))
.replace(/\/\*foreachInstalledChunks\*\//g, chunk.chunks.length > 0 ? "for(var chunkId in installedChunks)" : "var chunkId = " + chunk.id + ";") .replace(/\/\*foreachInstalledChunks\*\//g, chunk.chunks.length > 0 ? "for(var chunkId in installedChunks)" : "var chunkId = " + chunk.id + ";")
]); ]);
}); });

View File

@ -12,7 +12,10 @@ module.exports = HotUpdateChunkTemplate;
HotUpdateChunkTemplate.prototype = Object.create(Template.prototype); HotUpdateChunkTemplate.prototype = Object.create(Template.prototype);
HotUpdateChunkTemplate.prototype.render = function(id, modules, hash, moduleTemplate, dependencyTemplates) { HotUpdateChunkTemplate.prototype.render = function(id, modules, hash, moduleTemplate, dependencyTemplates) {
var modulesSource = this.renderChunkModules({ id: id, modules: modules }, moduleTemplate, dependencyTemplates); var modulesSource = this.renderChunkModules({
id: id,
modules: modules
}, moduleTemplate, dependencyTemplates);
var core = this.applyPluginsWaterfall("modules", modulesSource, modules, moduleTemplate, dependencyTemplates); var core = this.applyPluginsWaterfall("modules", modulesSource, modules, moduleTemplate, dependencyTemplates);
var source = this.applyPluginsWaterfall("render", core, modules, hash, id, moduleTemplate, dependencyTemplates); var source = this.applyPluginsWaterfall("render", core, modules, hash, id, moduleTemplate, dependencyTemplates);
return source; return source;
@ -22,4 +25,4 @@ HotUpdateChunkTemplate.prototype.updateHash = function(hash) {
hash.update("HotUpdateChunkTemplate"); hash.update("HotUpdateChunkTemplate");
hash.update("1"); hash.update("1");
this.applyPlugins("hash", hash); this.applyPlugins("hash", hash);
}; };

View File

@ -29,4 +29,4 @@ IgnorePlugin.prototype.apply = function(compiler) {
return callback(null, result); return callback(null, result);
}); });
}); });
}; };

View File

@ -5,8 +5,7 @@
var ConcatSource = require("webpack-core/lib/ConcatSource"); var ConcatSource = require("webpack-core/lib/ConcatSource");
var Template = require("./Template"); var Template = require("./Template");
function JsonpChunkTemplatePlugin() { function JsonpChunkTemplatePlugin() {}
}
module.exports = JsonpChunkTemplatePlugin; module.exports = JsonpChunkTemplatePlugin;
JsonpChunkTemplatePlugin.prototype.apply = function(chunkTemplate) { JsonpChunkTemplatePlugin.prototype.apply = function(chunkTemplate) {

View File

@ -18,7 +18,7 @@ JsonpExportMainTemplatePlugin.prototype.apply = function(compilation) {
return new ConcatSource(name + "(", source, ");"); return new ConcatSource(name + "(", source, ");");
}.bind(this)); }.bind(this));
mainTemplate.plugin("global-hash-paths", function(paths) { mainTemplate.plugin("global-hash-paths", function(paths) {
if (this.name) paths.push(this.name); if(this.name) paths.push(this.name);
return paths; return paths;
}.bind(this)); }.bind(this));
mainTemplate.plugin("hash", function(hash) { mainTemplate.plugin("hash", function(hash) {

View File

@ -5,9 +5,7 @@
var ConcatSource = require("webpack-core/lib/ConcatSource"); var ConcatSource = require("webpack-core/lib/ConcatSource");
var Template = require("./Template"); var Template = require("./Template");
function JsonpHotUpdateChunkTemplatePlugin() {}
function JsonpHotUpdateChunkTemplatePlugin() {
}
module.exports = JsonpHotUpdateChunkTemplatePlugin; module.exports = JsonpHotUpdateChunkTemplatePlugin;
JsonpHotUpdateChunkTemplatePlugin.prototype.apply = function(hotUpdateChunkTemplate) { JsonpHotUpdateChunkTemplatePlugin.prototype.apply = function(hotUpdateChunkTemplate) {

View File

@ -4,8 +4,7 @@
*/ */
var Template = require("./Template"); var Template = require("./Template");
function JsonpMainTemplatePlugin() { function JsonpMainTemplatePlugin() {}
}
module.exports = JsonpMainTemplatePlugin; module.exports = JsonpMainTemplatePlugin;
JsonpMainTemplatePlugin.prototype.constructor = JsonpMainTemplatePlugin; JsonpMainTemplatePlugin.prototype.constructor = JsonpMainTemplatePlugin;
@ -52,25 +51,25 @@ JsonpMainTemplatePlugin.prototype.apply = function(mainTemplate) {
"script.async = true;", "script.async = true;",
crossOriginLoading ? "script.crossOrigin = '" + crossOriginLoading + "';" : "", crossOriginLoading ? "script.crossOrigin = '" + crossOriginLoading + "';" : "",
"script.src = " + this.requireFn + ".p + " + "script.src = " + this.requireFn + ".p + " +
this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), { this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), {
hash: "\" + " + this.renderCurrentHashCode(hash) + " + \"", 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) { hashWithLength: function(length) {
return "\" + " + this.renderCurrentHashCode(hash, length) + " + \""; var shortChunkHashMap = {};
}.bind(this), Object.keys(chunkMaps.hash).forEach(function(chunkId) {
chunk: { if(typeof chunkMaps.hash[chunkId] === "string")
id: "\" + chunkId + \"", shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr(0, length);
hash: "\" + " + JSON.stringify(chunkMaps.hash) + "[chunkId] + \"", });
hashWithLength: function(length) { return "\" + " + JSON.stringify(shortChunkHashMap) + "[chunkId] + \"";
var shortChunkHashMap = {}; },
Object.keys(chunkMaps.hash).forEach(function(chunkId) { name: "\" + (" + JSON.stringify(chunkMaps.name) + "[chunkId]||chunkId) + \""
if(typeof chunkMaps.hash[chunkId] === "string") }
shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr(0, length); }) + ";",
});
return "\" + " + JSON.stringify(shortChunkHashMap) + "[chunkId] + \"";
},
name: "\" + (" + JSON.stringify(chunkMaps.name) + "[chunkId]||chunkId) + \""
}
}) + ";",
"head.appendChild(script);", "head.appendChild(script);",
"", "",
"var promise = new Promise(function(resolve, reject) {", "var promise = new Promise(function(resolve, reject) {",
@ -107,8 +106,7 @@ JsonpMainTemplatePlugin.prototype.apply = function(mainTemplate) {
"}", "}",
"if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules);", "if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules);",
"while(resolves.length)", "while(resolves.length)",
this.indent("resolves.shift()();"), this.indent("resolves.shift()();"), (this.entryPointInChildren(chunk) ? [
(this.entryPointInChildren(chunk) ? [
"if(executeModule + 1) { // typeof executeModule === \"number\"", "if(executeModule + 1) { // typeof executeModule === \"number\"",
this.indent([ this.indent([
"return " + this.requireFn + "(executeModule);" "return " + this.requireFn + "(executeModule);"

View File

@ -6,8 +6,7 @@ var JsonpMainTemplatePlugin = require("./JsonpMainTemplatePlugin");
var JsonpChunkTemplatePlugin = require("./JsonpChunkTemplatePlugin"); var JsonpChunkTemplatePlugin = require("./JsonpChunkTemplatePlugin");
var JsonpHotUpdateChunkTemplatePlugin = require("./JsonpHotUpdateChunkTemplatePlugin"); var JsonpHotUpdateChunkTemplatePlugin = require("./JsonpHotUpdateChunkTemplatePlugin");
function JsonpTemplatePlugin() { function JsonpTemplatePlugin() {}
}
module.exports = JsonpTemplatePlugin; module.exports = JsonpTemplatePlugin;
JsonpTemplatePlugin.prototype.apply = function(compiler) { JsonpTemplatePlugin.prototype.apply = function(compiler) {
compiler.plugin("this-compilation", function(compilation) { compiler.plugin("this-compilation", function(compilation) {
@ -15,4 +14,4 @@ JsonpTemplatePlugin.prototype.apply = function(compiler) {
compilation.chunkTemplate.apply(new JsonpChunkTemplatePlugin()); compilation.chunkTemplate.apply(new JsonpChunkTemplatePlugin());
compilation.hotUpdateChunkTemplate.apply(new JsonpHotUpdateChunkTemplatePlugin()); compilation.hotUpdateChunkTemplate.apply(new JsonpHotUpdateChunkTemplatePlugin());
}); });
}; };

View File

@ -30,44 +30,44 @@ module.exports = LibraryTemplatePlugin;
LibraryTemplatePlugin.prototype.apply = function(compiler) { LibraryTemplatePlugin.prototype.apply = function(compiler) {
compiler.plugin("this-compilation", function(compilation) { compiler.plugin("this-compilation", function(compilation) {
switch(this.target) { switch(this.target) {
case "var": case "var":
compilation.apply(new SetVarMainTemplatePlugin("var " + accessorAccess(false, this.name))); compilation.apply(new SetVarMainTemplatePlugin("var " + accessorAccess(false, this.name)));
break; break;
case "assign": case "assign":
compilation.apply(new SetVarMainTemplatePlugin(accessorAccess(undefined, this.name))); compilation.apply(new SetVarMainTemplatePlugin(accessorAccess(undefined, this.name)));
break; break;
case "this": case "this":
case "window": case "window":
case "global": case "global":
if(this.name) if(this.name)
compilation.apply(new SetVarMainTemplatePlugin(accessorAccess(this.target, this.name))); compilation.apply(new SetVarMainTemplatePlugin(accessorAccess(this.target, this.name)));
else else
compilation.apply(new SetVarMainTemplatePlugin(this.target, true)); compilation.apply(new SetVarMainTemplatePlugin(this.target, true));
break; break;
case "commonjs": case "commonjs":
if(this.name) if(this.name)
compilation.apply(new SetVarMainTemplatePlugin(accessorAccess("exports", this.name))); compilation.apply(new SetVarMainTemplatePlugin(accessorAccess("exports", this.name)));
else else
compilation.apply(new SetVarMainTemplatePlugin("exports", true)); compilation.apply(new SetVarMainTemplatePlugin("exports", true));
break; break;
case "commonjs2": case "commonjs2":
compilation.apply(new SetVarMainTemplatePlugin("module.exports")); compilation.apply(new SetVarMainTemplatePlugin("module.exports"));
break; break;
case "amd": case "amd":
var AmdMainTemplatePlugin = require("./AmdMainTemplatePlugin"); var AmdMainTemplatePlugin = require("./AmdMainTemplatePlugin");
compilation.apply(new AmdMainTemplatePlugin(this.name)); compilation.apply(new AmdMainTemplatePlugin(this.name));
break; break;
case "umd": case "umd":
case "umd2": case "umd2":
var UmdMainTemplatePlugin = require("./UmdMainTemplatePlugin"); var UmdMainTemplatePlugin = require("./UmdMainTemplatePlugin");
compilation.apply(new UmdMainTemplatePlugin(this.name, this.target === "umd2")); compilation.apply(new UmdMainTemplatePlugin(this.name, this.target === "umd2"));
break; break;
case "jsonp": case "jsonp":
var JsonpExportMainTemplatePlugin = require("./JsonpExportMainTemplatePlugin"); var JsonpExportMainTemplatePlugin = require("./JsonpExportMainTemplatePlugin");
compilation.apply(new JsonpExportMainTemplatePlugin(this.name)); compilation.apply(new JsonpExportMainTemplatePlugin(this.name));
break; break;
default: default:
throw new Error(this.target + " is not a valid Library target"); throw new Error(this.target + " is not a valid Library target");
} }
}.bind(this)); }.bind(this));
}; };

View File

@ -38,7 +38,7 @@ function MainTemplate(outputOptions) {
source.add(")"); source.add(")");
return source; return source;
}); });
this.plugin("local-vars", function(source/*, chunk, hash*/) { this.plugin("local-vars", function(source /*, chunk, hash*/ ) {
return this.asString([ return this.asString([
source, source,
"// The module cache", "// The module cache",
@ -67,7 +67,7 @@ function MainTemplate(outputOptions) {
"return module.exports;" "return module.exports;"
]); ]);
}); });
this.plugin("module-obj", function(/*source, chunk, hash, varModuleId*/) { this.plugin("module-obj", function( /*source, chunk, hash, varModuleId*/ ) {
return this.asString([ return this.asString([
"exports: {},", "exports: {},",
"id: moduleId,", "id: moduleId,",
@ -122,8 +122,8 @@ MainTemplate.prototype.render = function(hash, chunk, moduleTemplate, dependency
buf.push(this.asString(this.applyPluginsWaterfall("startup", "", chunk, hash))); buf.push(this.asString(this.applyPluginsWaterfall("startup", "", chunk, hash)));
var source = this.applyPluginsWaterfall("render", new OriginalSource(this.prefix(buf, " \t") + "\n", "webpack/bootstrap " + hash), chunk, hash, moduleTemplate, dependencyTemplates); var source = this.applyPluginsWaterfall("render", new OriginalSource(this.prefix(buf, " \t") + "\n", "webpack/bootstrap " + hash), chunk, hash, moduleTemplate, dependencyTemplates);
if(chunk.modules.some(function(module) { if(chunk.modules.some(function(module) {
return (module.entry); return module.entry;
})) { })) {
source = this.applyPluginsWaterfall("render-with-entry", source, chunk, hash); source = this.applyPluginsWaterfall("render-with-entry", source, chunk, hash);
} }
if(!source) throw new Error("Compiler error: MainTemplate plugin 'render' should return something"); if(!source) throw new Error("Compiler error: MainTemplate plugin 'render' should return something");
@ -145,15 +145,16 @@ MainTemplate.prototype.renderCurrentHashCode = function(hash, length) {
}; };
MainTemplate.prototype.entryPointInChildren = function(chunk) { MainTemplate.prototype.entryPointInChildren = function(chunk) {
return (function checkChildren(chunk, alreadyCheckedChunks) { function checkChildren(chunk, alreadyCheckedChunks) {
return chunk.chunks.some(function(child) { return chunk.chunks.some(function(child) {
if(alreadyCheckedChunks.indexOf(child) >= 0) return; if(alreadyCheckedChunks.indexOf(child) >= 0) return;
alreadyCheckedChunks.push(child); alreadyCheckedChunks.push(child);
return child.modules.some(function(module) { return child.modules.some(function(module) {
return (module.entry); return module.entry;
}) || checkChildren(child, alreadyCheckedChunks); }) || checkChildren(child, alreadyCheckedChunks);
}); });
}(chunk, [])); }
return checkChildren(chunk, []);
}; };
MainTemplate.prototype.getPublicPath = function(options) { MainTemplate.prototype.getPublicPath = function(options) {

View File

@ -6,6 +6,7 @@ var DependenciesBlock = require("./DependenciesBlock");
var ModuleReason = require("./ModuleReason"); var ModuleReason = require("./ModuleReason");
var debugId = 1000; var debugId = 1000;
function Module() { function Module() {
DependenciesBlock.call(this); DependenciesBlock.call(this);
this.context = null; this.context = null;
@ -99,7 +100,7 @@ Module.prototype.toString = function() {
return "Module[" + (this.id || this.debugId) + "]"; return "Module[" + (this.id || this.debugId) + "]";
}; };
Module.prototype.needRebuild = function(/* fileTimestamps, contextTimestamps */) { Module.prototype.needRebuild = function( /* fileTimestamps, contextTimestamps */ ) {
return true; return true;
}; };

View File

@ -66,7 +66,20 @@ ModuleFilenameHelpers.createFilename = function createFilename(module, moduleFil
var allLoaders = getBefore(identifier, "!"); var allLoaders = getBefore(identifier, "!");
var query = getAfter(resource, "?"); var query = getAfter(resource, "?");
var resourcePath = resource.substr(0, resource.length - query.length); var resourcePath = resource.substr(0, resource.length - query.length);
return (moduleFilenameTemplate 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_ALL_LOADERS_RESOURCE, identifier)
.replace(ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE, shortIdentifier) .replace(ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE, shortIdentifier)
.replace(ModuleFilenameHelpers.REGEXP_RESOURCE, resource) .replace(ModuleFilenameHelpers.REGEXP_RESOURCE, resource)
@ -76,8 +89,7 @@ ModuleFilenameHelpers.createFilename = function createFilename(module, moduleFil
.replace(ModuleFilenameHelpers.REGEXP_LOADERS, loaders) .replace(ModuleFilenameHelpers.REGEXP_LOADERS, loaders)
.replace(ModuleFilenameHelpers.REGEXP_QUERY, query) .replace(ModuleFilenameHelpers.REGEXP_QUERY, query)
.replace(ModuleFilenameHelpers.REGEXP_ID, moduleId) .replace(ModuleFilenameHelpers.REGEXP_ID, moduleId)
.replace(ModuleFilenameHelpers.REGEXP_HASH, hash) .replace(ModuleFilenameHelpers.REGEXP_HASH, hash);
);
}; };
ModuleFilenameHelpers.createFooter = function createFooter(module, requestShortener) { ModuleFilenameHelpers.createFooter = function createFooter(module, requestShortener) {
@ -93,7 +105,9 @@ ModuleFilenameHelpers.createFooter = function createFooter(module, requestShorte
" ** WEBPACK FOOTER", " ** WEBPACK FOOTER",
" ** " + module.readableIdentifier(requestShortener), " ** " + module.readableIdentifier(requestShortener),
" ** module id = " + module.id, " ** module id = " + module.id,
" ** module chunks = " + module.chunks.map(function(c) { return c.id; }).join(" "), " ** module chunks = " + module.chunks.map(function(c) {
return c.id;
}).join(" "),
" **/" " **/"
].join("\n"); ].join("\n");
} }
@ -121,7 +135,6 @@ ModuleFilenameHelpers.replaceDuplicates = function replaceDuplicates(array, fn,
}); });
}; };
ModuleFilenameHelpers.matchPart = function matchPart(str, test) { ModuleFilenameHelpers.matchPart = function matchPart(str, test) {
if(!test) return true; if(!test) return true;
test = asRegExp(test); test = asRegExp(test);

View File

@ -122,13 +122,17 @@ function MultiStats(stats) {
MultiStats.prototype.hasErrors = function() { MultiStats.prototype.hasErrors = function() {
return this.stats.map(function(stat) { return this.stats.map(function(stat) {
return stat.hasErrors(); return stat.hasErrors();
}).reduce(function(a, b) { return a || b; }, false); }).reduce(function(a, b) {
return a || b;
}, false);
}; };
MultiStats.prototype.hasWarnings = function() { MultiStats.prototype.hasWarnings = function() {
return this.stats.map(function(stat) { return this.stats.map(function(stat) {
return stat.hasWarnings(); return stat.hasWarnings();
}).reduce(function(a, b) { return a || b; }, false); }).reduce(function(a, b) {
return a || b;
}, false);
}; };
MultiStats.prototype.toJson = function(options, forToString) { MultiStats.prototype.toJson = function(options, forToString) {
@ -158,4 +162,4 @@ MultiStats.prototype.toJson = function(options, forToString) {
return obj; return obj;
}; };
MultiStats.prototype.toString = Stats.prototype.toString; MultiStats.prototype.toString = Stats.prototype.toString;

View File

@ -2,8 +2,7 @@
MIT License http://www.opensource.org/licenses/mit-license.php MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra Author Tobias Koppers @sokra
*/ */
function NewWatchingPlugin() { function NewWatchingPlugin() {}
}
module.exports = NewWatchingPlugin; module.exports = NewWatchingPlugin;
NewWatchingPlugin.prototype.apply = function(compiler) { NewWatchingPlugin.prototype.apply = function(compiler) {

View File

@ -2,8 +2,7 @@
MIT License http://www.opensource.org/licenses/mit-license.php MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra Author Tobias Koppers @sokra
*/ */
function NoErrorsPlugin() { function NoErrorsPlugin() {}
}
module.exports = NoErrorsPlugin; module.exports = NoErrorsPlugin;
NoErrorsPlugin.prototype.apply = function(compiler) { NoErrorsPlugin.prototype.apply = function(compiler) {
compiler.plugin("should-emit", function(compilation) { compiler.plugin("should-emit", function(compilation) {

View File

@ -19,13 +19,18 @@ NodeStuffPlugin.prototype.apply = function(compiler) {
compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
}); });
function ignore() { return true; }
function ignore() {
return true;
}
function setConstant(expressionName, value) { function setConstant(expressionName, value) {
compiler.parser.plugin("expression " + expressionName, function() { compiler.parser.plugin("expression " + expressionName, function() {
this.state.current.addVariable(expressionName, JSON.stringify(value)); this.state.current.addVariable(expressionName, JSON.stringify(value));
return true; return true;
}); });
} }
function setModuleConstant(expressionName, fn) { function setModuleConstant(expressionName, fn) {
compiler.parser.plugin("expression " + expressionName, function() { compiler.parser.plugin("expression " + expressionName, function() {
this.state.current.addVariable(expressionName, JSON.stringify(fn(this.state.module))); this.state.current.addVariable(expressionName, JSON.stringify(fn(this.state.module)));
@ -84,4 +89,4 @@ NodeStuffPlugin.prototype.apply = function(compiler) {
compiler.parser.plugin("expression module", function() { compiler.parser.plugin("expression module", function() {
return ModuleParserHelpers.addParsedVariable(this, "module", "require(" + JSON.stringify(path.join(__dirname, "..", "buildin", "module.js")) + ")(module)"); return ModuleParserHelpers.addParsedVariable(this, "module", "require(" + JSON.stringify(path.join(__dirname, "..", "buildin", "module.js")) + ")(module)");
}); });
}; };

View File

@ -89,13 +89,13 @@ NormalModule.prototype.build = function build(options, compilation, resolver, fs
if(options.module && options.module.noParse) { if(options.module && options.module.noParse) {
if(Array.isArray(options.module.noParse)) { if(Array.isArray(options.module.noParse)) {
if(options.module.noParse.some(function(regExp) { if(options.module.noParse.some(function(regExp) {
return typeof regExp === "string" ? return typeof regExp === "string" ?
this.request.indexOf(regExp) === 0 : this.request.indexOf(regExp) === 0 :
regExp.test(this.request); regExp.test(this.request);
}, this)) return callback(); }, this)) return callback();
} else if(typeof options.module.noParse === "string" ? } else if(typeof options.module.noParse === "string" ?
this.request.indexOf(options.module.noParse) === 0 : this.request.indexOf(options.module.noParse) === 0 :
options.module.noParse.test(this.request)) { options.module.noParse.test(this.request)) {
return callback(); return callback();
} }
} }
@ -125,21 +125,30 @@ NormalModule.prototype.source = function(dependencyTemplates, outputOptions, req
var _source = this._source; var _source = this._source;
if(!_source) return new RawSource("throw new Error('No source available');"); if(!_source) return new RawSource("throw new Error('No source available');");
var source = new ReplaceSource(_source); var source = new ReplaceSource(_source);
this._cachedSource = { source: source, hash: hash }; this._cachedSource = {
source: source,
hash: hash
};
var topLevelBlock = this; var topLevelBlock = this;
function doDep(dep) { function doDep(dep) {
var template = dependencyTemplates.get(dep.Class); var template = dependencyTemplates.get(dep.Class);
if(!template) throw new Error("No template for dependency: " + dep.Class.name); if(!template) throw new Error("No template for dependency: " + dep.Class.name);
template.apply(dep, source, outputOptions, requestShortener, dependencyTemplates); template.apply(dep, source, outputOptions, requestShortener, dependencyTemplates);
} }
function doVariable(availableVars, vars, variable) { function doVariable(availableVars, vars, variable) {
var name = variable.name; var name = variable.name;
var expr = variable.expressionSource(dependencyTemplates, outputOptions, requestShortener); var expr = variable.expressionSource(dependencyTemplates, outputOptions, requestShortener);
if(availableVars.some(function(v) { if(availableVars.some(function(v) {
return v.name === name && v.expression.source() === expr.source(); return v.name === name && v.expression.source() === expr.source();
})) return; })) return;
vars.push({name: name, expression: expr}); vars.push({
name: name,
expression: expr
});
} }
function doBlock(availableVars, block) { function doBlock(availableVars, block) {
block.dependencies.forEach(doDep); block.dependencies.forEach(doDep);
var vars = []; var vars = [];
@ -149,6 +158,7 @@ NormalModule.prototype.source = function(dependencyTemplates, outputOptions, req
var varExpressions = []; var varExpressions = [];
var varStartCode = ""; var varStartCode = "";
var varEndCode = ""; var varEndCode = "";
function emitFunction() { function emitFunction() {
if(varNames.length === 0) return; if(varNames.length === 0) return;
@ -218,13 +228,16 @@ NormalModule.prototype.getSourceHash = function() {
NormalModule.prototype.getAllModuleDependencies = function() { NormalModule.prototype.getAllModuleDependencies = function() {
var list = []; var list = [];
function doDep(dep) { function doDep(dep) {
if(dep.module && list.indexOf(dep.module) < 0) if(dep.module && list.indexOf(dep.module) < 0)
list.push(dep.module); list.push(dep.module);
} }
function doVariable(variable) { function doVariable(variable) {
variable.dependencies.forEach(doDep); variable.dependencies.forEach(doDep);
} }
function doBlock(block) { function doBlock(block) {
block.variables.forEach(doVariable); block.variables.forEach(doVariable);
block.dependencies.forEach(doDep); block.dependencies.forEach(doDep);
@ -260,6 +273,7 @@ NormalModule.prototype.createTemplate = function(keepModules, roots) {
return array.join("|"); return array.join("|");
}; };
var args = template.arguments = []; var args = template.arguments = [];
function doDeps(deps) { function doDeps(deps) {
return deps.map(function(dep) { return deps.map(function(dep) {
if(dep.module && keepModules.indexOf(dep.module) < 0) { if(dep.module && keepModules.indexOf(dep.module) < 0) {
@ -271,6 +285,7 @@ NormalModule.prototype.createTemplate = function(keepModules, roots) {
} }
}); });
} }
function doBlock(block, newBlock) { function doBlock(block, newBlock) {
block.variables.forEach(function(variable) { block.variables.forEach(function(variable) {
var newDependencies = doDeps(variable.dependencies); var newDependencies = doDeps(variable.dependencies);
@ -289,13 +304,16 @@ NormalModule.prototype.createTemplate = function(keepModules, roots) {
NormalModule.prototype.getTemplateArguments = function(keepModules) { NormalModule.prototype.getTemplateArguments = function(keepModules) {
var list = []; var list = [];
function doDep(dep) { function doDep(dep) {
if(dep.module && keepModules.indexOf(dep.module) < 0) if(dep.module && keepModules.indexOf(dep.module) < 0)
list.push(dep.module); list.push(dep.module);
} }
function doVariable(variable) { function doVariable(variable) {
variable.dependencies.forEach(doDep); variable.dependencies.forEach(doDep);
} }
function doBlock(block) { function doBlock(block) {
block.variables.forEach(doVariable); block.variables.forEach(doVariable);
block.dependencies.forEach(doDep); block.dependencies.forEach(doDep);

View File

@ -119,6 +119,7 @@ function NormalModuleFactory(context, resolvers, parser, options) {
onDoneResolving.call(this); onDoneResolving.call(this);
}.bind(this)); }.bind(this));
} }
function onDoneResolving() { function onDoneResolving() {
callback(null, { callback(null, {
context: context, context: context,

View File

@ -4,6 +4,7 @@
*/ */
var path = require("path"); var path = require("path");
function NormalModuleReplacementPlugin(resourceRegExp, newResource) { function NormalModuleReplacementPlugin(resourceRegExp, newResource) {
this.resourceRegExp = resourceRegExp; this.resourceRegExp = resourceRegExp;
this.newResource = newResource; this.newResource = newResource;
@ -16,7 +17,7 @@ NormalModuleReplacementPlugin.prototype.apply = function(compiler) {
nmf.plugin("before-resolve", function(result, callback) { nmf.plugin("before-resolve", function(result, callback) {
if(!result) return callback(); if(!result) return callback();
if(resourceRegExp.test(result.request)) { if(resourceRegExp.test(result.request)) {
if (typeof newResource === "function") { if(typeof newResource === "function") {
newResource(result); newResource(result);
} else { } else {
result.request = newResource; result.request = newResource;
@ -27,7 +28,7 @@ NormalModuleReplacementPlugin.prototype.apply = function(compiler) {
nmf.plugin("after-resolve", function(result, callback) { nmf.plugin("after-resolve", function(result, callback) {
if(!result) return callback(); if(!result) return callback();
if(resourceRegExp.test(result.resource)) { if(resourceRegExp.test(result.resource)) {
if (typeof newResource === "function") { if(typeof newResource === "function") {
newResource(result); newResource(result);
} else { } else {
result.resource = path.resolve(path.dirname(result.resource), newResource); result.resource = path.resolve(path.dirname(result.resource), newResource);

View File

@ -2,8 +2,7 @@
MIT License http://www.opensource.org/licenses/mit-license.php MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra Author Tobias Koppers @sokra
*/ */
function NullFactory() { function NullFactory() {}
}
module.exports = NullFactory; module.exports = NullFactory;
NullFactory.prototype.create = function(context, dependency, callback) { NullFactory.prototype.create = function(context, dependency, callback) {

View File

@ -4,8 +4,7 @@
*/ */
var OldNodeWatchFileSystem = require("./node/OldNodeWatchFileSystem"); var OldNodeWatchFileSystem = require("./node/OldNodeWatchFileSystem");
function OldWatchingPlugin() { function OldWatchingPlugin() {}
}
module.exports = OldWatchingPlugin; module.exports = OldWatchingPlugin;
OldWatchingPlugin.prototype.apply = function(compiler) { OldWatchingPlugin.prototype.apply = function(compiler) {

View File

@ -2,10 +2,9 @@
MIT License http://www.opensource.org/licenses/mit-license.php MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra Author Tobias Koppers @sokra
*/ */
function OptionsApply() { function OptionsApply() {}
}
module.exports = OptionsApply; module.exports = OptionsApply;
OptionsApply.prototype.process = function(/* options, compiler */) { OptionsApply.prototype.process = function( /* options, compiler */ ) {
}; };

View File

@ -2,4 +2,4 @@
MIT License http://www.opensource.org/licenses/mit-license.php MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra Author Tobias Koppers @sokra
*/ */
module.exports = require("webpack-core/lib/OriginalSource"); module.exports = require("webpack-core/lib/OriginalSource");

View File

@ -15,8 +15,6 @@ module.exports = Parser;
// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API // Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API
Parser.prototype = Object.create(Tapable.prototype); Parser.prototype = Object.create(Tapable.prototype);
Parser.prototype.initializeEvaluating = function() { Parser.prototype.initializeEvaluating = function() {
function joinRanges(startRange, endRange) { function joinRanges(startRange, endRange) {
@ -26,12 +24,12 @@ Parser.prototype.initializeEvaluating = function() {
} }
this.plugin("evaluate Literal", function(expr) { this.plugin("evaluate Literal", function(expr) {
switch(typeof expr.value) { switch(typeof expr.value) {
case "number": case "number":
return new BasicEvaluatedExpression().setNumber(expr.value).setRange(expr.range); return new BasicEvaluatedExpression().setNumber(expr.value).setRange(expr.range);
case "string": case "string":
return new BasicEvaluatedExpression().setString(expr.value).setRange(expr.range); return new BasicEvaluatedExpression().setString(expr.value).setRange(expr.range);
case "boolean": case "boolean":
return new BasicEvaluatedExpression().setBoolean(expr.value).setRange(expr.range); return new BasicEvaluatedExpression().setBoolean(expr.value).setRange(expr.range);
} }
if(expr.value === null) if(expr.value === null)
return new BasicEvaluatedExpression().setNull().setRange(expr.range); return new BasicEvaluatedExpression().setNull().setRange(expr.range);
@ -69,8 +67,8 @@ Parser.prototype.initializeEvaluating = function() {
} else if(right.isWrapped() && right.prefix && right.prefix.isString()) { } else if(right.isWrapped() && right.prefix && right.prefix.isString()) {
res.setWrapped( res.setWrapped(
new BasicEvaluatedExpression() new BasicEvaluatedExpression()
.setString(left.string + right.prefix.string) .setString(left.string + right.prefix.string)
.setRange(joinRanges(left.range, right.prefix.range)), .setRange(joinRanges(left.range, right.prefix.range)),
right.postfix); right.postfix);
} else { } else {
res.setWrapped(left, null); res.setWrapped(left, null);
@ -85,22 +83,22 @@ Parser.prototype.initializeEvaluating = function() {
if(left.postfix && left.postfix.isString() && right.isString()) { if(left.postfix && left.postfix.isString() && right.isString()) {
res.setWrapped(left.prefix, res.setWrapped(left.prefix,
new BasicEvaluatedExpression() new BasicEvaluatedExpression()
.setString(left.postfix.string + right.string) .setString(left.postfix.string + right.string)
.setRange(joinRanges(left.postfix.range, right.range)) .setRange(joinRanges(left.postfix.range, right.range))
); );
} else if(left.postfix && left.postfix.isString() && right.isNumber()) { } else if(left.postfix && left.postfix.isString() && right.isNumber()) {
res.setWrapped(left.prefix, res.setWrapped(left.prefix,
new BasicEvaluatedExpression() new BasicEvaluatedExpression()
.setString(left.postfix.string + right.number) .setString(left.postfix.string + right.number)
.setRange(joinRanges(left.postfix.range, right.range)) .setRange(joinRanges(left.postfix.range, right.range))
); );
} else if(right.isString()) { } else if(right.isString()) {
res.setWrapped(left.prefix, right); res.setWrapped(left.prefix, right);
} else if(right.isNumber()) { } else if(right.isNumber()) {
res.setWrapped(left.prefix, res.setWrapped(left.prefix,
new BasicEvaluatedExpression() new BasicEvaluatedExpression()
.setString(right.number + "") .setString(right.number + "")
.setRange(right.range)); .setRange(right.range));
} else { } else {
res.setWrapped(left.prefix, new BasicEvaluatedExpression()); res.setWrapped(left.prefix, new BasicEvaluatedExpression());
} }
@ -269,20 +267,20 @@ Parser.prototype.initializeEvaluating = function() {
if(!param.isString()) return; if(!param.isString()) return;
var result, str = param.string; var result, str = param.string;
switch(expr.arguments.length) { switch(expr.arguments.length) {
case 1: case 1:
var arg1 = this.evaluateExpression(expr.arguments[0]); var arg1 = this.evaluateExpression(expr.arguments[0]);
if(!arg1.isNumber()) return; if(!arg1.isNumber()) return;
result = str[fn](arg1.number); result = str[fn](arg1.number);
break; break;
case 2: case 2:
var arg1 = this.evaluateExpression(expr.arguments[0]); var arg1 = this.evaluateExpression(expr.arguments[0]);
var arg2 = this.evaluateExpression(expr.arguments[1]); var arg2 = this.evaluateExpression(expr.arguments[1]);
if(!arg1.isNumber()) return; if(!arg1.isNumber()) return;
if(!arg2.isNumber()) return; if(!arg2.isNumber()) return;
result = str[fn](arg1.number, arg2.number); result = str[fn](arg1.number, arg2.number);
break; break;
default: default:
return; return;
} }
return new BasicEvaluatedExpression().setString(result).setRange(expr.range); return new BasicEvaluatedExpression().setString(result).setRange(expr.range);
}); });
@ -325,7 +323,9 @@ Parser.prototype.initializeEvaluating = function() {
var items = expr.elements.map(function(element) { var items = expr.elements.map(function(element) {
return element !== null && this.evaluateExpression(element); return element !== null && this.evaluateExpression(element);
}, this); }, this);
if(items.filter(function(i) { return !i; }).length > 0) return; if(items.filter(function(i) {
return !i;
}).length > 0) return;
return new BasicEvaluatedExpression().setItems(items).setRange(expr.range); return new BasicEvaluatedExpression().setItems(items).setRange(expr.range);
}); });
}; };
@ -390,10 +390,10 @@ Parser.prototype.walkSwitchStatement = function walkSwitchStatement(statement) {
}; };
Parser.prototype.walkReturnStatement = Parser.prototype.walkReturnStatement =
Parser.prototype.walkThrowStatement = function walkArgumentStatement(statement) { Parser.prototype.walkThrowStatement = function walkArgumentStatement(statement) {
if(statement.argument) if(statement.argument)
this.walkExpression(statement.argument); this.walkExpression(statement.argument);
}; };
Parser.prototype.walkTryStatement = function walkTryStatement(statement) { Parser.prototype.walkTryStatement = function walkTryStatement(statement) {
if(this.scope.inTry) { if(this.scope.inTry) {
@ -410,10 +410,10 @@ Parser.prototype.walkTryStatement = function walkTryStatement(statement) {
}; };
Parser.prototype.walkWhileStatement = Parser.prototype.walkWhileStatement =
Parser.prototype.walkDoWhileStatement = function walkLoopStatement(statement) { Parser.prototype.walkDoWhileStatement = function walkLoopStatement(statement) {
this.walkExpression(statement.test); this.walkExpression(statement.test);
this.walkStatement(statement.body); this.walkStatement(statement.body);
}; };
Parser.prototype.walkForStatement = function walkForStatement(statement) { Parser.prototype.walkForStatement = function walkForStatement(statement) {
if(statement.init) { if(statement.init) {
@ -467,15 +467,15 @@ Parser.prototype.walkImportDeclaration = function walkImportDeclaration(statemen
this.scope.renames["$" + name] = undefined; this.scope.renames["$" + name] = undefined;
this.scope.definitions.push(name); this.scope.definitions.push(name);
switch(specifier.type) { switch(specifier.type) {
case "ImportDefaultSpecifier": case "ImportDefaultSpecifier":
this.applyPluginsBailResult("import specifier", statement, source, "default", name); this.applyPluginsBailResult("import specifier", statement, source, "default", name);
break; break;
case "ImportSpecifier": case "ImportSpecifier":
this.applyPluginsBailResult("import specifier", statement, source, specifier.imported.name, name); this.applyPluginsBailResult("import specifier", statement, source, specifier.imported.name, name);
break; break;
case "ImportNamespaceSpecifier": case "ImportNamespaceSpecifier":
this.applyPluginsBailResult("import specifier", statement, source, null, name); this.applyPluginsBailResult("import specifier", statement, source, null, name);
break; break;
} }
}, this); }, this);
}; };
@ -504,13 +504,13 @@ Parser.prototype.walkExportNamedDeclaration = function walkExportNamedDeclaratio
if(statement.specifiers) { if(statement.specifiers) {
statement.specifiers.forEach(function(specifier) { statement.specifiers.forEach(function(specifier) {
switch(specifier.type) { switch(specifier.type) {
case "ExportSpecifier": case "ExportSpecifier":
var name = specifier.exported.name; var name = specifier.exported.name;
if(source) if(source)
this.applyPluginsBailResult("export import specifier", statement, source, specifier.local.name, name); this.applyPluginsBailResult("export import specifier", statement, source, specifier.local.name, name);
else else
this.applyPluginsBailResult("export specifier", statement, specifier.local.name, name); this.applyPluginsBailResult("export specifier", statement, specifier.local.name, name);
break; break;
} }
}, this); }, this);
} }
@ -565,26 +565,26 @@ Parser.prototype.walkCatchClause = function walkCatchClause(catchClause) {
Parser.prototype.walkVariableDeclarators = function walkVariableDeclarators(declarators) { Parser.prototype.walkVariableDeclarators = function walkVariableDeclarators(declarators) {
declarators.forEach(function(declarator) { declarators.forEach(function(declarator) {
switch(declarator.type) { switch(declarator.type) {
case "VariableDeclarator": case "VariableDeclarator":
var renameIdentifier = declarator.init && this.getRenameIdentifier(declarator.init); var renameIdentifier = declarator.init && this.getRenameIdentifier(declarator.init);
if(renameIdentifier && declarator.id.type === "Identifier" && this.applyPluginsBailResult("can-rename " + renameIdentifier, declarator.init)) { if(renameIdentifier && declarator.id.type === "Identifier" && this.applyPluginsBailResult("can-rename " + renameIdentifier, declarator.init)) {
// renaming with "var a = b;" // renaming with "var a = b;"
if(!this.applyPluginsBailResult("rename " + renameIdentifier, declarator.init)) { if(!this.applyPluginsBailResult("rename " + renameIdentifier, declarator.init)) {
this.scope.renames["$" + declarator.id.name] = this.scope.renames["$" + renameIdentifier] || renameIdentifier; this.scope.renames["$" + declarator.id.name] = this.scope.renames["$" + renameIdentifier] || renameIdentifier;
var idx = this.scope.definitions.indexOf(declarator.id.name); var idx = this.scope.definitions.indexOf(declarator.id.name);
if(idx >= 0) this.scope.definitions.splice(idx, 1); if(idx >= 0) this.scope.definitions.splice(idx, 1);
}
} else if(declarator.id.type === "Identifier" && !this.applyPluginsBailResult("var " + declarator.id.name, declarator)) {
this.scope.renames["$" + declarator.id.name] = undefined;
this.scope.definitions.push(declarator.id.name);
if(declarator.init)
this.walkExpression(declarator.init);
} else {
this.walkExpression(declarator.id);
if(declarator.init)
this.walkExpression(declarator.init);
} }
} else if(declarator.id.type === "Identifier" && !this.applyPluginsBailResult("var " + declarator.id.name, declarator)) { break;
this.scope.renames["$" + declarator.id.name] = undefined;
this.scope.definitions.push(declarator.id.name);
if(declarator.init)
this.walkExpression(declarator.init);
} else {
this.walkExpression(declarator.id);
if(declarator.init)
this.walkExpression(declarator.init);
}
break;
} }
}, this); }, this);
}; };
@ -650,10 +650,10 @@ Parser.prototype.walkUnaryExpression = function walkUnaryExpression(expression)
}; };
Parser.prototype.walkBinaryExpression = Parser.prototype.walkBinaryExpression =
Parser.prototype.walkLogicalExpression = function walkLeftRightExpression(expression) { Parser.prototype.walkLogicalExpression = function walkLeftRightExpression(expression) {
this.walkExpression(expression.left); this.walkExpression(expression.left);
this.walkExpression(expression.right); this.walkExpression(expression.right);
}; };
Parser.prototype.walkAssignmentExpression = function walkAssignmentExpression(expression) { Parser.prototype.walkAssignmentExpression = function walkAssignmentExpression(expression) {
var renameIdentifier = this.getRenameIdentifier(expression.right); var renameIdentifier = this.getRenameIdentifier(expression.right);
@ -804,69 +804,95 @@ Parser.prototype.evaluateExpression = function evaluateExpression(expression) {
Parser.prototype.parseString = function parseString(expression) { Parser.prototype.parseString = function parseString(expression) {
switch(expression.type) { switch(expression.type) {
case "BinaryExpression": case "BinaryExpression":
if(expression.operator === "+") if(expression.operator === "+")
return this.parseString(expression.left) + this.parseString(expression.right); return this.parseString(expression.left) + this.parseString(expression.right);
break; break;
case "Literal": case "Literal":
return expression.value + ""; return expression.value + "";
} }
throw new Error(expression.type + " is not supported as parameter for require"); throw new Error(expression.type + " is not supported as parameter for require");
}; };
Parser.prototype.parseCalculatedString = function parseCalculatedString(expression) { Parser.prototype.parseCalculatedString = function parseCalculatedString(expression) {
switch(expression.type) { switch(expression.type) {
case "BinaryExpression": case "BinaryExpression":
if(expression.operator === "+") { if(expression.operator === "+") {
var left = this.parseCalculatedString(expression.left); var left = this.parseCalculatedString(expression.left);
var right = this.parseCalculatedString(expression.right); var right = this.parseCalculatedString(expression.right);
if(left.code) { if(left.code) {
return {range: left.range, value: left.value, code: true}; return {
} else if(right.code) { range: left.range,
return {range: [left.range[0], right.range ? right.range[1] : left.range[1]], value: left.value + right.value, code: true}; value: left.value,
} else { code: true
return {range: [left.range[0], right.range[1]], value: left.value + right.value}; };
} else if(right.code) {
return {
range: [left.range[0], right.range ? right.range[1] : left.range[1]],
value: left.value + right.value,
code: true
};
} else {
return {
range: [left.range[0], right.range[1]],
value: left.value + right.value
};
}
} }
} break;
break; case "ConditionalExpression":
case "ConditionalExpression": var consequent = this.parseCalculatedString(expression.consequent);
var consequent = this.parseCalculatedString(expression.consequent); var alternate = this.parseCalculatedString(expression.alternate);
var alternate = this.parseCalculatedString(expression.alternate); var items = [];
var items = []; if(consequent.conditional)
if(consequent.conditional) Array.prototype.push.apply(items, consequent.conditional);
Array.prototype.push.apply(items, consequent.conditional); else if(!consequent.code)
else if(!consequent.code) items.push(consequent);
items.push(consequent); else break;
else break; if(alternate.conditional)
if(alternate.conditional) Array.prototype.push.apply(items, alternate.conditional);
Array.prototype.push.apply(items, alternate.conditional); else if(!alternate.code)
else if(!alternate.code) items.push(alternate);
items.push(alternate); else break;
else break; return {
return {value: "", code: true, conditional: items}; value: "",
case "Literal": code: true,
return {range: expression.range, value: expression.value + ""}; conditional: items
};
case "Literal":
return {
range: expression.range,
value: expression.value + ""
};
} }
return {value: "", code: true}; return {
value: "",
code: true
};
}; };
["parseString", "parseCalculatedString"].forEach(function(fn) { ["parseString", "parseCalculatedString"].forEach(function(fn) {
Parser.prototype[fn + "Array"] = function parseXXXArray(expression) { Parser.prototype[fn + "Array"] = function parseXXXArray(expression) {
switch(expression.type) { switch(expression.type) {
case "ArrayExpression": case "ArrayExpression":
var arr = []; var arr = [];
if(expression.elements) if(expression.elements)
expression.elements.forEach(function(expr) { expression.elements.forEach(function(expr) {
arr.push(this[fn](expr)); arr.push(this[fn](expr));
}, this); }, this);
return arr; return arr;
} }
return [this[fn](expression)]; return [this[fn](expression)];
}; };
}); });
Parser.prototype.parse = function parse(source, initialState) { Parser.prototype.parse = function parse(source, initialState) {
var ast = acorn.parse(source, {ranges: true, locations: true, ecmaVersion: 6, sourceType: "module"}); var ast = acorn.parse(source, {
ranges: true,
locations: true,
ecmaVersion: 6,
sourceType: "module"
});
if(!ast || typeof ast !== "object") if(!ast || typeof ast !== "object")
throw new Error("Source couldn't be parsed"); throw new Error("Source couldn't be parsed");
var oldScope = this.scope; var oldScope = this.scope;
@ -885,7 +911,12 @@ Parser.prototype.parse = function parse(source, initialState) {
}; };
Parser.prototype.evaluate = function evaluate(source) { Parser.prototype.evaluate = function evaluate(source) {
var ast = acorn.parse("(" + source + ")", {ranges: true, locations: true, ecmaVersion: 6, sourceType: "module"}); var ast = acorn.parse("(" + source + ")", {
ranges: true,
locations: true,
ecmaVersion: 6,
sourceType: "module"
});
if(!ast || typeof ast !== "object" || ast.type !== "Program") if(!ast || typeof ast !== "object" || ast.type !== "Program")
throw new Error("evaluate: Source couldn't be parsed"); throw new Error("evaluate: Source couldn't be parsed");
if(ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement") if(ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement")

View File

@ -22,4 +22,4 @@ PrefetchPlugin.prototype.apply = function(compiler) {
compiler.plugin("make", function(compilation, callback) { compiler.plugin("make", function(compilation, callback) {
compilation.prefetch(this.context || compiler.context, new PrefetchDependency(this.request), callback); compilation.prefetch(this.context || compiler.context, new PrefetchDependency(this.request), callback);
}.bind(this)); }.bind(this));
}; };

View File

@ -27,6 +27,7 @@ ProgressPlugin.prototype.apply = function(compiler) {
var lastModulesCount = 0; var lastModulesCount = 0;
var moduleCount = 1; var moduleCount = 1;
var doneModules = 0; var doneModules = 0;
function update() { function update() {
handler(0.1 + (doneModules / Math.max(lastModulesCount, moduleCount)) * 0.6, doneModules + "/" + moduleCount + " build modules"); handler(0.1 + (doneModules / Math.max(lastModulesCount, moduleCount)) * 0.6, doneModules + "/" + moduleCount + " build modules");
} }

View File

@ -22,7 +22,9 @@ ProvidePlugin.prototype.apply = function(compiler) {
if(splittedName.length > 0) { if(splittedName.length > 0) {
splittedName.slice(1).forEach(function(_, i) { splittedName.slice(1).forEach(function(_, i) {
var name = splittedName.slice(0, i + 1).join("."); var name = splittedName.slice(0, i + 1).join(".");
compiler.parser.plugin("can-rename " + name, function() { return true; }); compiler.parser.plugin("can-rename " + name, function() {
return true;
});
}); });
} }
compiler.parser.plugin("expression " + name, function(expr) { compiler.parser.plugin("expression " + name, function(expr) {
@ -43,4 +45,4 @@ ProvidePlugin.prototype.apply = function(compiler) {
return true; return true;
}); });
}, this); }, this);
}; };

View File

@ -2,4 +2,4 @@
MIT License http://www.opensource.org/licenses/mit-license.php MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra Author Tobias Koppers @sokra
*/ */
module.exports = require("webpack-core/lib/RawSource"); module.exports = require("webpack-core/lib/RawSource");

View File

@ -4,8 +4,7 @@
*/ */
var path = require("path"); var path = require("path");
function RecordIdsPlugin() { function RecordIdsPlugin() {}
}
module.exports = RecordIdsPlugin; module.exports = RecordIdsPlugin;
function makeRelative(compiler, identifier) { function makeRelative(compiler, identifier) {

View File

@ -6,14 +6,14 @@ var ConstDependency = require("./dependencies/ConstDependency");
var NullFactory = require("./NullFactory"); var NullFactory = require("./NullFactory");
function RequireJsStuffPlugin() { function RequireJsStuffPlugin() {}
}
module.exports = RequireJsStuffPlugin; module.exports = RequireJsStuffPlugin;
RequireJsStuffPlugin.prototype.apply = function(compiler) { RequireJsStuffPlugin.prototype.apply = function(compiler) {
compiler.plugin("compilation", function(compilation) { compiler.plugin("compilation", function(compilation) {
compilation.dependencyFactories.set(ConstDependency, new NullFactory()); compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template()); compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
}); });
function remove(expr) { function remove(expr) {
var dep = new ConstDependency(";", expr.range); var dep = new ConstDependency(";", expr.range);
dep.loc = expr.loc; dep.loc = expr.loc;
@ -35,4 +35,4 @@ RequireJsStuffPlugin.prototype.apply = function(compiler) {
this.state.current.addDependency(dep); this.state.current.addDependency(dep);
return true; return true;
}); });
}; };

View File

@ -24,8 +24,8 @@ SetVarMainTemplatePlugin.prototype.apply = function(compilation) {
return new ConcatSource(prefix, source); return new ConcatSource(prefix, source);
} }
}.bind(this)); }.bind(this));
mainTemplate.plugin("global-hash-paths", function (paths) { mainTemplate.plugin("global-hash-paths", function(paths) {
if (this.varExpression) paths.push(this.varExpression); if(this.varExpression) paths.push(this.varExpression);
return paths; return paths;
}); });
mainTemplate.plugin("hash", function(hash) { mainTemplate.plugin("hash", function(hash) {

View File

@ -2,4 +2,4 @@
MIT License http://www.opensource.org/licenses/mit-license.php MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra Author Tobias Koppers @sokra
*/ */
module.exports = require("webpack-core/lib/Source"); module.exports = require("webpack-core/lib/Source");

View File

@ -127,7 +127,8 @@ SourceMapDevToolPlugin.prototype.apply = function(compiler) {
currentSourceMappingURLComment = currentSourceMappingURLComment.replace(/^\n\/\/(.*)$/, "\n/*$1*/"); currentSourceMappingURLComment = currentSourceMappingURLComment.replace(/^\n\/\/(.*)$/, "\n/*$1*/");
} }
if(sourceMapFilename) { if(sourceMapFilename) {
var filename = file, query = ""; var filename = file,
query = "";
var idx = filename.indexOf("?"); var idx = filename.indexOf("?");
if(idx >= 0) { if(idx >= 0) {
query = filename.substr(idx); query = filename.substr(idx);
@ -165,4 +166,3 @@ function basename(name) {
if(name.indexOf("/") < 0) return name; if(name.indexOf("/") < 0) return name;
return name.substr(name.lastIndexOf("/") + 1); return name.substr(name.lastIndexOf("/") + 1);
} }

View File

@ -2,4 +2,4 @@
MIT License http://www.opensource.org/licenses/mit-license.php MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra Author Tobias Koppers @sokra
*/ */
module.exports = require("webpack-core/lib/SourceMapSource"); module.exports = require("webpack-core/lib/SourceMapSource");

View File

@ -20,7 +20,10 @@ Stats.prototype.hasErrors = function() {
Stats.prototype.toJson = function toJson(options, forToString) { Stats.prototype.toJson = function toJson(options, forToString) {
if(!options) options = {}; if(!options) options = {};
function d(v, def) { return v === undefined ? def : v; }
function d(v, def) {
return v === undefined ? def : v;
}
var compilation = this.compilation; var compilation = this.compilation;
var requestShortener = new RequestShortener(d(options.context, process.cwd())); var requestShortener = new RequestShortener(d(options.context, process.cwd()));
var showHash = d(options.hash, true); var showHash = d(options.hash, true);
@ -59,23 +62,28 @@ Stats.prototype.toJson = function toJson(options, forToString) {
} }
function sortByField(field) { function sortByField(field) {
if(!field) return function() { return 0; }; if(!field) return function() {
return 0;
};
if(field[0] === "!") { if(field[0] === "!") {
field = field.substr(1); field = field.substr(1);
return function(a, b) { return function(a, b) {
if(a[field] === b[field]) return 0; if(a[field] === b[field]) return 0;
return (a[field] < b[field]) ? 1 : -1; return a[field] < b[field] ? 1 : -1;
}; };
} }
return function(a, b) { return function(a, b) {
if(a[field] === b[field]) return 0; if(a[field] === b[field]) return 0;
return (a[field] < b[field]) ? -1 : 1; return a[field] < b[field] ? -1 : 1;
}; };
} }
function formatError(e) { function formatError(e) {
var text = ""; var text = "";
if(typeof e === "string") if(typeof e === "string")
e = {message: e}; e = {
message: e
};
if(e.chunk) { if(e.chunk) {
text += "chunk " + (e.chunk.name || e.chunk.id) + text += "chunk " + (e.chunk.name || e.chunk.id) +
(e.chunk.entry ? " [entry]" : e.chunk.initial ? " [initial]" : "") + "\n"; (e.chunk.entry ? " [entry]" : e.chunk.initial ? " [initial]" : "") + "\n";
@ -159,6 +167,7 @@ Stats.prototype.toJson = function toJson(options, forToString) {
}); });
obj.assets.sort(sortByField(sortAssets)); obj.assets.sort(sortByField(sortAssets));
} }
function fnModule(module) { function fnModule(module) {
var obj = { var obj = {
id: module.id, id: module.id,
@ -192,7 +201,9 @@ Stats.prototype.toJson = function toJson(options, forToString) {
userRequest: reason.dependency.userRequest userRequest: reason.dependency.userRequest
}; };
var dep = reason.dependency; var dep = reason.dependency;
if(dep.templateModules) obj.templateModules = dep.templateModules.map(function(module) { return module.id; }); if(dep.templateModules) obj.templateModules = dep.templateModules.map(function(module) {
return module.id;
});
if(typeof dep.loc === "object") obj.loc = dep.loc.start.line + ":" + dep.loc.start.column + "-" + if(typeof dep.loc === "object") obj.loc = dep.loc.start.line + ":" + dep.loc.start.column + "-" +
(dep.loc.start.line !== dep.loc.end.line ? dep.loc.end.line + ":" : "") + dep.loc.end.column; (dep.loc.start.line !== dep.loc.end.line ? dep.loc.end.line + ":" : "") + dep.loc.end.column;
return obj; return obj;
@ -213,7 +224,9 @@ Stats.prototype.toJson = function toJson(options, forToString) {
initial: !!chunk.initial, initial: !!chunk.initial,
entry: !!chunk.entry, entry: !!chunk.entry,
extraAsync: !!chunk.extraAsync, extraAsync: !!chunk.extraAsync,
size: chunk.modules.reduce(function(size, module) { return size + module.size(); }, 0), size: chunk.modules.reduce(function(size, module) {
return size + module.size();
}, 0),
names: chunk.name ? [chunk.name] : [], names: chunk.name ? [chunk.name] : [],
files: chunk.files.slice(), files: chunk.files.slice(),
hash: chunk.renderedHash, hash: chunk.renderedHash,
@ -263,7 +276,10 @@ Stats.prototype.toJson = function toJson(options, forToString) {
Stats.prototype.toString = function toString(options) { Stats.prototype.toString = function toString(options) {
if(!options) options = {}; if(!options) options = {};
function d(v, def) { return v === undefined ? def : v; }
function d(v, def) {
return v === undefined ? def : v;
}
var useColors = d(options.colors, false); var useColors = d(options.colors, false);
var obj = this.toJson(options, true); var obj = this.toJson(options, true);
@ -273,39 +289,47 @@ Stats.prototype.toString = function toString(options) {
Stats.jsonToString = function jsonToString(obj, useColors) { Stats.jsonToString = function jsonToString(obj, useColors) {
var buf = []; var buf = [];
function normal(str) { function normal(str) {
buf.push(str); buf.push(str);
} }
function bold(str) { function bold(str) {
if(useColors) buf.push("\u001b[1m"); if(useColors) buf.push("\u001b[1m");
buf.push(str); buf.push(str);
if(useColors) buf.push("\u001b[22m"); if(useColors) buf.push("\u001b[22m");
} }
function yellow(str) { function yellow(str) {
if(useColors) buf.push("\u001b[1m\u001b[33m"); if(useColors) buf.push("\u001b[1m\u001b[33m");
buf.push(str); buf.push(str);
if(useColors) buf.push("\u001b[39m\u001b[22m"); if(useColors) buf.push("\u001b[39m\u001b[22m");
} }
function red(str) { function red(str) {
if(useColors) buf.push("\u001b[1m\u001b[31m"); if(useColors) buf.push("\u001b[1m\u001b[31m");
buf.push(str); buf.push(str);
if(useColors) buf.push("\u001b[39m\u001b[22m"); if(useColors) buf.push("\u001b[39m\u001b[22m");
} }
function green(str) { function green(str) {
if(useColors) buf.push("\u001b[1m\u001b[32m"); if(useColors) buf.push("\u001b[1m\u001b[32m");
buf.push(str); buf.push(str);
if(useColors) buf.push("\u001b[39m\u001b[22m"); if(useColors) buf.push("\u001b[39m\u001b[22m");
} }
function cyan(str) { function cyan(str) {
if(useColors) buf.push("\u001b[1m\u001b[36m"); if(useColors) buf.push("\u001b[1m\u001b[36m");
buf.push(str); buf.push(str);
if(useColors) buf.push("\u001b[39m\u001b[22m"); if(useColors) buf.push("\u001b[39m\u001b[22m");
} }
function magenta(str) { function magenta(str) {
if(useColors) buf.push("\u001b[1m\u001b[35m"); if(useColors) buf.push("\u001b[1m\u001b[35m");
buf.push(str); buf.push(str);
if(useColors) buf.push("\u001b[39m\u001b[22m"); if(useColors) buf.push("\u001b[39m\u001b[22m");
} }
function coloredTime(time) { function coloredTime(time) {
var times = [800, 400, 200, 100]; var times = [800, 400, 200, 100];
if(obj.time) { if(obj.time) {
@ -322,9 +346,11 @@ Stats.jsonToString = function jsonToString(obj, useColors) {
else else
red(time + "ms"); red(time + "ms");
} }
function newline() { function newline() {
buf.push("\n"); buf.push("\n");
} }
function table(array, formats, align, splitter) { function table(array, formats, align, splitter) {
var rows = array.length; var rows = array.length;
var cols = array[0].length; var cols = array[0].length;
@ -356,6 +382,7 @@ Stats.jsonToString = function jsonToString(obj, useColors) {
newline(); newline();
} }
} }
function formatSize(size) { function formatSize(size) {
if(size <= 0) return "0 bytes"; if(size <= 0) return "0 bytes";
@ -388,7 +415,9 @@ Stats.jsonToString = function jsonToString(obj, useColors) {
newline(); newline();
} }
if(obj.assets && obj.assets.length > 0) { if(obj.assets && obj.assets.length > 0) {
var t = [["Asset", "Size", "Chunks", "", "Chunk Names"]]; var t = [
["Asset", "Size", "Chunks", "", "Chunk Names"]
];
obj.assets.forEach(function(asset) { obj.assets.forEach(function(asset) {
t.push([ t.push([
asset.name, asset.name,
@ -414,10 +443,12 @@ Stats.jsonToString = function jsonToString(obj, useColors) {
} }
}); });
} }
function processProfile(module) { function processProfile(module) {
if(module.profile) { if(module.profile) {
normal(" "); normal(" ");
var sum = 0, allowSum = true; var sum = 0,
allowSum = true;
var path = []; var path = [];
var current = module; var current = module;
while(current.issuer) { while(current.issuer) {
@ -453,6 +484,7 @@ Stats.jsonToString = function jsonToString(obj, useColors) {
newline(); newline();
} }
} }
function processModuleAttributes(module) { function processModuleAttributes(module) {
normal(" "); normal(" ");
normal(formatSize(module.size)); normal(formatSize(module.size));

View File

@ -28,7 +28,8 @@ Template.prototype.indent = function indent(str) {
} else { } else {
str = str.trimRight(); str = str.trimRight();
if(!str) return ""; if(!str) return "";
return (str[0] === "\n" ? "" : "\t") + str.replace(/\n([^\n])/g, "\n\t$1"); var ind = (str[0] === "\n" ? "" : "\t");
return ind + str.replace(/\n([^\n])/g, "\n\t$1");
} }
}; };
@ -38,7 +39,8 @@ Template.prototype.prefix = function(str, prefix) {
} }
str = str.trim(); str = str.trim();
if(!str) return ""; if(!str) return "";
return (str[0] === "\n" ? "" : prefix) + str.replace(/\n([^\n])/g, "\n" + prefix + "$1"); var ind = (str[0] === "\n" ? "" : prefix);
return ind + str.replace(/\n([^\n])/g, "\n" + prefix + "$1");
}; };
Template.prototype.asString = function(str) { Template.prototype.asString = function(str) {
@ -50,8 +52,8 @@ Template.prototype.asString = function(str) {
Template.prototype.getModulesArrayBounds = function(modules) { Template.prototype.getModulesArrayBounds = function(modules) {
if(modules.some(function(module) { if(modules.some(function(module) {
return typeof module.id !== "number"; return typeof module.id !== "number";
})) }))
return false; return false;
var maxId = -Infinity; var maxId = -Infinity;
var minId = Infinity; var minId = Infinity;
@ -64,8 +66,11 @@ Template.prototype.getModulesArrayBounds = function(modules) {
minId = 0; minId = 0;
} }
var objectOverhead = modules.map(function(module) { var objectOverhead = modules.map(function(module) {
return (module.id + "").length + 2; var idLength = (module.id + "").length;
}).reduce(function(a, b) { return a + b; }, -1); return idLength + 2;
}).reduce(function(a, b) {
return a + b;
}, -1);
var arrayOverhead = minId === 0 ? maxId : 16 + ("" + minId).length + maxId; var arrayOverhead = minId === 0 ? maxId : 16 + ("" + minId).length + maxId;
return arrayOverhead < objectOverhead ? [minId, maxId] : false; return arrayOverhead < objectOverhead ? [minId, maxId] : false;
}; };

View File

@ -32,7 +32,7 @@ function TemplatedPathPlugin() {}
module.exports = TemplatedPathPlugin; module.exports = TemplatedPathPlugin;
function withHashLength(replacer, handlerFn) { function withHashLength(replacer, handlerFn) {
return function (_, hashLength) { return function(_, hashLength) {
var length = hashLength && parseInt(hashLength, 10); var length = hashLength && parseInt(hashLength, 10);
if(length && handlerFn) { if(length && handlerFn) {
return handlerFn(length); return handlerFn(length);
@ -43,11 +43,11 @@ function withHashLength(replacer, handlerFn) {
} }
function getReplacer(value, allowEmpty) { function getReplacer(value, allowEmpty) {
return function (match) { return function(match) {
// last argument in replacer is the entire input string // last argument in replacer is the entire input string
var input = arguments[arguments.length - 1]; var input = arguments[arguments.length - 1];
if (value == null) { if(value == null) {
if (!allowEmpty) throw new Error("Path variable " + match + " not implemented in this context: " + input); if(!allowEmpty) throw new Error("Path variable " + match + " not implemented in this context: " + input);
return ""; return "";
} else { } else {
return "" + value; return "" + value;

View File

@ -31,7 +31,8 @@ UmdMainTemplatePlugin.prototype.apply = function(compilation) {
var externals = chunk.modules.filter(function(m) { var externals = chunk.modules.filter(function(m) {
return m.external; return m.external;
}); });
var optionalExternals = [], requiredExternals = []; var optionalExternals = [],
requiredExternals = [];
if(this.optionalAmdExternalAsGlobal) { if(this.optionalAmdExternalAsGlobal) {
externals.forEach(function(m) { externals.forEach(function(m) {
if(m.optional) { if(m.optional) {
@ -51,11 +52,13 @@ UmdMainTemplatePlugin.prototype.apply = function(compilation) {
chunk: chunk chunk: chunk
}); });
} }
function externalsDepsArray(modules) { function externalsDepsArray(modules) {
return "[" + replaceKeys(modules.map(function(m) { return "[" + replaceKeys(modules.map(function(m) {
return JSON.stringify(typeof m.request === "object" ? m.request.amd : m.request); return JSON.stringify(typeof m.request === "object" ? m.request.amd : m.request);
}).join(", ")) + "]"; }).join(", ")) + "]";
} }
function externalsRootArray(modules) { function externalsRootArray(modules) {
return replaceKeys(modules.map(function(m) { return replaceKeys(modules.map(function(m) {
var request = m.request; var request = m.request;
@ -63,6 +66,7 @@ UmdMainTemplatePlugin.prototype.apply = function(compilation) {
return "root" + accessorToObjectAccess([].concat(request)); return "root" + accessorToObjectAccess([].concat(request));
}).join(", ")); }).join(", "));
} }
function externalsRequireArray(type) { function externalsRequireArray(type) {
return replaceKeys(externals.map(function(m) { return replaceKeys(externals.map(function(m) {
var request = m.request; var request = m.request;
@ -77,6 +81,7 @@ UmdMainTemplatePlugin.prototype.apply = function(compilation) {
return expr; return expr;
}).join(", ")); }).join(", "));
} }
function externalsArguments(modules) { function externalsArguments(modules) {
return modules.map(function(m) { return modules.map(function(m) {
return "__WEBPACK_EXTERNAL_MODULE_" + m.id + "__"; return "__WEBPACK_EXTERNAL_MODULE_" + m.id + "__";
@ -84,12 +89,12 @@ UmdMainTemplatePlugin.prototype.apply = function(compilation) {
} }
if(optionalExternals.length > 0) { if(optionalExternals.length > 0) {
var amdFactory = "function webpackLoadOptionalExternalModuleAmd(" + externalsArguments(requiredExternals) + ") {\n" + var amdFactory = "function webpackLoadOptionalExternalModuleAmd(" + externalsArguments(requiredExternals) + ") {\n" +
" return factory(" + ( " return factory(" + (
requiredExternals.length > 0 ? requiredExternals.length > 0 ?
externalsArguments(requiredExternals) + ", " + externalsRootArray(optionalExternals) : externalsArguments(requiredExternals) + ", " + externalsRootArray(optionalExternals) :
externalsRootArray(optionalExternals) externalsRootArray(optionalExternals)
) + ");\n" + ) + ");\n" +
" }"; " }";
} else { } else {
var amdFactory = "factory"; var amdFactory = "factory";
} }
@ -99,29 +104,26 @@ UmdMainTemplatePlugin.prototype.apply = function(compilation) {
" module.exports = factory(" + externalsRequireArray("commonjs2") + ");\n" + " module.exports = factory(" + externalsRequireArray("commonjs2") + ");\n" +
" else if(typeof define === 'function' && define.amd)\n" + " else if(typeof define === 'function' && define.amd)\n" +
(requiredExternals.length > 0 ? (requiredExternals.length > 0 ?
" define(" + externalsDepsArray(requiredExternals) + ", " + amdFactory + ");\n" " define(" + externalsDepsArray(requiredExternals) + ", " + amdFactory + ");\n" :
: " define(" + amdFactory + ");\n"
" define(" + amdFactory + ");\n"
) + ) +
(this.name ? (this.name ?
" else if(typeof exports === 'object')\n" + " else if(typeof exports === 'object')\n" +
" exports[" + JSON.stringify(replaceKeys([].concat(this.name).pop())) + "] = factory(" + externalsRequireArray("commonjs") + ");\n" + " exports[" + JSON.stringify(replaceKeys([].concat(this.name).pop())) + "] = factory(" + externalsRequireArray("commonjs") + ");\n" +
" else\n" + " else\n" +
" " + replaceKeys(accessorAccess("root", this.name)) + " = factory(" + externalsRootArray(externals) + ");\n" " " + replaceKeys(accessorAccess("root", this.name)) + " = factory(" + externalsRootArray(externals) + ");\n" :
: " else {\n" +
" else {\n" + (externals.length > 0 ?
(externals.length > 0 ? " var a = typeof exports === 'object' ? factory(" + externalsRequireArray("commonjs") + ") : factory(" + externalsRootArray(externals) + ");\n" :
" var a = typeof exports === 'object' ? factory(" + externalsRequireArray("commonjs") + ") : factory(" + externalsRootArray(externals) + ");\n" " var a = factory();\n"
: ) +
" var a = factory();\n" " for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" +
) + " }\n"
" for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];\n" +
" }\n"
) + ) +
"})(this, function(" + externalsArguments(externals) + ") {\nreturn ", "webpack/universalModuleDefinition"), source, "\n});\n"); "})(this, function(" + externalsArguments(externals) + ") {\nreturn ", "webpack/universalModuleDefinition"), source, "\n});\n");
}.bind(this)); }.bind(this));
mainTemplate.plugin("global-hash-paths", function(paths) { mainTemplate.plugin("global-hash-paths", function(paths) {
if (this.name) paths = paths.concat(this.name); if(this.name) paths = paths.concat(this.name);
return paths; return paths;
}.bind(this)); }.bind(this));
mainTemplate.plugin("hash", function(hash) { mainTemplate.plugin("hash", function(hash) {

View File

@ -4,8 +4,7 @@
*/ */
var CaseSensitiveModulesWarning = require("./CaseSensitiveModulesWarning"); var CaseSensitiveModulesWarning = require("./CaseSensitiveModulesWarning");
function WarnCaseSensitiveModulesPlugin() { function WarnCaseSensitiveModulesPlugin() {}
}
module.exports = WarnCaseSensitiveModulesPlugin; module.exports = WarnCaseSensitiveModulesPlugin;
WarnCaseSensitiveModulesPlugin.prototype.apply = function(compiler) { WarnCaseSensitiveModulesPlugin.prototype.apply = function(compiler) {
@ -25,4 +24,4 @@ WarnCaseSensitiveModulesPlugin.prototype.apply = function(compiler) {
}, this); }, this);
}); });
}); });
}; };

View File

@ -4,8 +4,8 @@ function WatchIgnorePlugin(paths) {
module.exports = WatchIgnorePlugin; module.exports = WatchIgnorePlugin;
WatchIgnorePlugin.prototype.apply = function (compiler) { WatchIgnorePlugin.prototype.apply = function(compiler) {
compiler.plugin("after-environment", function () { compiler.plugin("after-environment", function() {
compiler.watchFileSystem = new IgnoringWatchFileSystem(compiler.watchFileSystem, this.paths); compiler.watchFileSystem = new IgnoringWatchFileSystem(compiler.watchFileSystem, this.paths);
}.bind(this)); }.bind(this));
}; };
@ -15,25 +15,27 @@ function IgnoringWatchFileSystem(wfs, paths) {
this.paths = paths; this.paths = paths;
} }
IgnoringWatchFileSystem.prototype.watch = function (files, dirs, missing, startTime, delay, callback, callbackUndelayed) { IgnoringWatchFileSystem.prototype.watch = function(files, dirs, missing, startTime, delay, callback, callbackUndelayed) {
var ignored = function (path) { var ignored = function(path) {
return this.paths.some(function (p) { return this.paths.some(function(p) {
return ((p instanceof RegExp) ? p.test(path) : path.indexOf(p) === 0); return p instanceof RegExp ? p.test(path) : path.indexOf(p) === 0;
}); });
}.bind(this); }.bind(this);
var notIgnored = function (path) { return !ignored(path); }; var notIgnored = function(path) {
return !ignored(path);
};
var ignoredFiles = files.filter(ignored); var ignoredFiles = files.filter(ignored);
var ignoredDirs = dirs.filter(ignored); var ignoredDirs = dirs.filter(ignored);
this.wfs.watch(files.filter(notIgnored), dirs.filter(notIgnored), missing, startTime, delay, function (err, filesModified, dirsModified, fileTimestamps, dirTimestamps) { this.wfs.watch(files.filter(notIgnored), dirs.filter(notIgnored), missing, startTime, delay, function(err, filesModified, dirsModified, fileTimestamps, dirTimestamps) {
if(err) return callback(err); if(err) return callback(err);
ignoredFiles.forEach(function (path) { ignoredFiles.forEach(function(path) {
fileTimestamps[path] = 1; fileTimestamps[path] = 1;
}); });
ignoredDirs.forEach(function (path) { ignoredDirs.forEach(function(path) {
dirTimestamps[path] = 1; dirTimestamps[path] = 1;
}); });

View File

@ -51,7 +51,6 @@ var FileAppendPlugin = require("enhanced-resolve/lib/FileAppendPlugin");
var DirectoryResultPlugin = require("enhanced-resolve/lib/DirectoryResultPlugin"); var DirectoryResultPlugin = require("enhanced-resolve/lib/DirectoryResultPlugin");
var ResultSymlinkPlugin = require("enhanced-resolve/lib/ResultSymlinkPlugin"); var ResultSymlinkPlugin = require("enhanced-resolve/lib/ResultSymlinkPlugin");
function WebpackOptionsApply() { function WebpackOptionsApply() {
OptionsApply.call(this); OptionsApply.call(this);
} }
@ -69,83 +68,83 @@ WebpackOptionsApply.prototype.process = function(options, compiler) {
compiler.name = options.name; compiler.name = options.name;
if(typeof options.target === "string") { if(typeof options.target === "string") {
switch(options.target) { switch(options.target) {
case "web": case "web":
var JsonpTemplatePlugin = require("./JsonpTemplatePlugin"); var JsonpTemplatePlugin = require("./JsonpTemplatePlugin");
var NodeSourcePlugin = require("./node/NodeSourcePlugin"); var NodeSourcePlugin = require("./node/NodeSourcePlugin");
compiler.apply( compiler.apply(
new JsonpTemplatePlugin(options.output), new JsonpTemplatePlugin(options.output),
new FunctionModulePlugin(options.output), new FunctionModulePlugin(options.output),
new NodeSourcePlugin(options.node), new NodeSourcePlugin(options.node),
new LoaderTargetPlugin("web") new LoaderTargetPlugin("web")
); );
break; break;
case "webworker": case "webworker":
var WebWorkerTemplatePlugin = require("./webworker/WebWorkerTemplatePlugin"); var WebWorkerTemplatePlugin = require("./webworker/WebWorkerTemplatePlugin");
var NodeSourcePlugin = require("./node/NodeSourcePlugin"); var NodeSourcePlugin = require("./node/NodeSourcePlugin");
compiler.apply( compiler.apply(
new WebWorkerTemplatePlugin(options.output), new WebWorkerTemplatePlugin(options.output),
new FunctionModulePlugin(options.output), new FunctionModulePlugin(options.output),
new NodeSourcePlugin(options.node), new NodeSourcePlugin(options.node),
new LoaderTargetPlugin("webworker") new LoaderTargetPlugin("webworker")
); );
break; break;
case "node": case "node":
case "async-node": case "async-node":
var NodeTemplatePlugin = require("./node/NodeTemplatePlugin"); var NodeTemplatePlugin = require("./node/NodeTemplatePlugin");
var NodeTargetPlugin = require("./node/NodeTargetPlugin"); var NodeTargetPlugin = require("./node/NodeTargetPlugin");
compiler.apply( compiler.apply(
new NodeTemplatePlugin(options.output, options.target === "async-node"), new NodeTemplatePlugin(options.output, options.target === "async-node"),
new FunctionModulePlugin(options.output), new FunctionModulePlugin(options.output),
new NodeTargetPlugin(), new NodeTargetPlugin(),
new LoaderTargetPlugin("node") new LoaderTargetPlugin("node")
); );
break; break;
case "node-webkit": case "node-webkit":
var JsonpTemplatePlugin = require("./JsonpTemplatePlugin"); var JsonpTemplatePlugin = require("./JsonpTemplatePlugin");
var NodeTargetPlugin = require("./node/NodeTargetPlugin"); var NodeTargetPlugin = require("./node/NodeTargetPlugin");
var ExternalsPlugin = require("./ExternalsPlugin"); var ExternalsPlugin = require("./ExternalsPlugin");
compiler.apply( compiler.apply(
new JsonpTemplatePlugin(options.output), new JsonpTemplatePlugin(options.output),
new FunctionModulePlugin(options.output), new FunctionModulePlugin(options.output),
new NodeTargetPlugin(), new NodeTargetPlugin(),
new ExternalsPlugin("commonjs", "nw.gui"), new ExternalsPlugin("commonjs", "nw.gui"),
new LoaderTargetPlugin("node-webkit") new LoaderTargetPlugin("node-webkit")
); );
break; break;
case "atom": case "atom":
case "electron": case "electron":
var NodeTemplatePlugin = require("./node/NodeTemplatePlugin"); var NodeTemplatePlugin = require("./node/NodeTemplatePlugin");
var NodeTargetPlugin = require("./node/NodeTargetPlugin"); var NodeTargetPlugin = require("./node/NodeTargetPlugin");
var ExternalsPlugin = require("./ExternalsPlugin"); var ExternalsPlugin = require("./ExternalsPlugin");
compiler.apply( compiler.apply(
new NodeTemplatePlugin(options.output, true), new NodeTemplatePlugin(options.output, true),
new FunctionModulePlugin(options.output), new FunctionModulePlugin(options.output),
new NodeTargetPlugin(), new NodeTargetPlugin(),
new ExternalsPlugin("commonjs", [ new ExternalsPlugin("commonjs", [
"app", "app",
"auto-updater", "auto-updater",
"browser-window", "browser-window",
"content-tracing", "content-tracing",
"dialog", "dialog",
"global-shortcut", "global-shortcut",
"ipc", "ipc",
"menu", "menu",
"menu-item", "menu-item",
"power-monitor", "power-monitor",
"protocol", "protocol",
"tray", "tray",
"remote", "remote",
"web-view", "web-view",
"clipboard", "clipboard",
"crash-reporter", "crash-reporter",
"screen", "screen",
"shell" "shell"
]), ]),
new LoaderTargetPlugin(options.target) new LoaderTargetPlugin(options.target)
); );
break; break;
default: default:
throw new Error("Unsupported target '" + options.target + "'."); throw new Error("Unsupported target '" + options.target + "'.");
} }
} else if(options.target !== false) { } else if(options.target !== false) {
options.target(compiler); options.target(compiler);
@ -173,7 +172,8 @@ WebpackOptionsApply.prototype.process = function(options, compiler) {
legacy ? "\n/*\n//@ sourceMappingURL=[url]\n*/" : legacy ? "\n/*\n//@ sourceMappingURL=[url]\n*/" :
modern ? "\n//# sourceMappingURL=[url]" : modern ? "\n//# sourceMappingURL=[url]" :
null; null;
compiler.apply(new (evalWrapped ? EvalSourceMapDevToolPlugin : SourceMapDevToolPlugin)({ var Plugin = evalWrapped ? EvalSourceMapDevToolPlugin : SourceMapDevToolPlugin;
compiler.apply(new Plugin({
filename: inline ? null : options.output.sourceMapFilename, filename: inline ? null : options.output.sourceMapFilename,
moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate, moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate,
fallbackModuleFilenameTemplate: options.output.devtoolFallbackModuleFilenameTemplate, fallbackModuleFilenameTemplate: options.output.devtoolFallbackModuleFilenameTemplate,

View File

@ -72,34 +72,25 @@ WebpackOptionsDefaulter.prototype.process = function(options) {
function defaultByTarget(value, web, webworker, node, nodeWebkit, def) { function defaultByTarget(value, web, webworker, node, nodeWebkit, def) {
if(value !== undefined) return value; if(value !== undefined) return value;
switch(options.target) { switch(options.target) {
case "web": return web; case "web":
case "webworker": return webworker; return web;
case "node": case "async-node": return node; case "webworker":
case "node-webkit": return nodeWebkit; return webworker;
default: return def; case "node":
case "async-node":
return node;
case "node-webkit":
return nodeWebkit;
default:
return def;
} }
} }
options.resolve.modulesDirectories = defaultByTarget(options.resolve.modulesDirectories, options.resolve.modulesDirectories = defaultByTarget(options.resolve.modulesDirectories, ["web_modules", "node_modules"], ["webworker_modules", "web_modules", "node_modules"], ["node_modules"], ["node_modules", "web_modules"], ["node_modules"]);
["web_modules", "node_modules"],
["webworker_modules", "web_modules", "node_modules"],
["node_modules"],
["node_modules", "web_modules"],
["node_modules"]);
options.resolveLoader.modulesDirectories = defaultByTarget(options.resolveLoader.modulesDirectories, options.resolveLoader.modulesDirectories = defaultByTarget(options.resolveLoader.modulesDirectories, ["web_loaders", "web_modules", "node_loaders", "node_modules"], ["webworker_loaders", "web_loaders", "web_modules", "node_loaders", "node_modules"], ["node_loaders", "node_modules"], ["node_loaders", "web_loaders", "node_modules", "web_modules"], ["node_modules"]);
["web_loaders", "web_modules", "node_loaders", "node_modules"],
["webworker_loaders", "web_loaders", "web_modules", "node_loaders", "node_modules"],
["node_loaders", "node_modules"],
["node_loaders", "web_loaders", "node_modules", "web_modules"],
["node_modules"]);
options.resolve.packageMains = defaultByTarget(options.resolve.packageMains, options.resolve.packageMains = defaultByTarget(options.resolve.packageMains, ["webpack", "browser", "web", "browserify", ["jam", "main"], "main"], ["webpackWorker", "webworker", "webpack", "browser", "web", "browserify", ["jam", "main"], "main"], ["webpackNode", "node", "main"], ["webpackNodeWebkit", "webpackNode", "node", "main", "web"], ["main"]);
["webpack", "browser", "web", "browserify", ["jam", "main"], "main"],
["webpackWorker", "webworker", "webpack", "browser", "web", "browserify", ["jam", "main"], "main"],
["webpackNode", "node", "main"],
["webpackNodeWebkit", "webpackNode", "node", "main", "web"],
["main"]);
options.resolve.packageAlias = defaultByTarget(options.resolve.packageAlias, options.resolve.packageAlias = defaultByTarget(options.resolve.packageAlias,
"browser", "browser",
@ -108,31 +99,11 @@ WebpackOptionsDefaulter.prototype.process = function(options) {
"node-webkit", "node-webkit",
false); false);
options.resolveLoader.packageMains = defaultByTarget(options.resolveLoader.packageMains, options.resolveLoader.packageMains = defaultByTarget(options.resolveLoader.packageMains, ["webpackLoader", "webLoader", "loader", "main"], ["webpackWorkerLoader", "webworkerLoader", "webLoader", "loader", "main"], ["webpackNodeLoader", "nodeLoader", "loader", "main"], ["webpackNodeWebkitLoader", "webpackNodeLoader", "nodeLoader", "loader", "webLoader", "main"], ["loader", "main"]);
["webpackLoader", "webLoader", "loader", "main"],
["webpackWorkerLoader", "webworkerLoader", "webLoader", "loader", "main"],
["webpackNodeLoader", "nodeLoader", "loader", "main"],
["webpackNodeWebkitLoader", "webpackNodeLoader", "nodeLoader", "loader", "webLoader", "main"],
["loader", "main"]);
options.resolve.extensions = defaultByTarget(options.resolve.extensions, options.resolve.extensions = defaultByTarget(options.resolve.extensions, ["", ".webpack.js", ".web.js", ".js", ".json"], ["", ".webpack-worker.js", ".webworker.js", ".web.js", ".js", ".json"], ["", ".webpack-node.js", ".js", ".json", ".node"], ["", ".webpack-node-webkit.js", ".webpack-node.js", ".js", ".json", ".node", ".web.js"], ["", ".js", ".json"]);
["", ".webpack.js", ".web.js", ".js", ".json"],
["", ".webpack-worker.js", ".webworker.js", ".web.js", ".js", ".json"],
["", ".webpack-node.js", ".js", ".json", ".node"],
["", ".webpack-node-webkit.js", ".webpack-node.js", ".js", ".json", ".node", ".web.js"],
["", ".js", ".json"]);
options.resolveLoader.extensions = defaultByTarget(options.resolveLoader.extensions, options.resolveLoader.extensions = defaultByTarget(options.resolveLoader.extensions, ["", ".webpack-loader.js", ".web-loader.js", ".loader.js", ".js"], ["", ".webpack-worker-loader.js", ".webpack-loader.js", ".webworker-loader.js", ".web-loader.js", ".loader.js", ".js"], ["", ".webpack-node-loader.js", ".loader.js", ".js"], ["", ".webpack-node-webkit-loader.js", ".webpack-node-loader.js", ".loader.js", ".web-loader.js", ".js"], ["", ".js"]);
["", ".webpack-loader.js", ".web-loader.js", ".loader.js", ".js"],
["", ".webpack-worker-loader.js", ".webpack-loader.js", ".webworker-loader.js", ".web-loader.js", ".loader.js", ".js"],
["", ".webpack-node-loader.js", ".loader.js", ".js"],
["", ".webpack-node-webkit-loader.js", ".webpack-node-loader.js", ".loader.js", ".web-loader.js", ".js"],
["", ".js"]);
options.resolveLoader.moduleTemplates = defaultByTarget(options.resolveLoader.moduleTemplates, options.resolveLoader.moduleTemplates = defaultByTarget(options.resolveLoader.moduleTemplates, ["*-webpack-loader", "*-web-loader", "*-loader", "*"], ["*-webpack-worker-loader", "*-webworker-loader", "*-web-loader", "*-loader", "*"], ["*-webpack-node-loader", "*-node-loader", "*-loader", "*"], ["*-webpack-node-webkit-loader", "*-webpack-node-loader", "*-node-loader", "*-loader", "*-web-loader", "*"], ["*-loader", "*"]);
["*-webpack-loader", "*-web-loader", "*-loader", "*"],
["*-webpack-worker-loader", "*-webworker-loader", "*-web-loader", "*-loader", "*"],
["*-webpack-node-loader", "*-node-loader", "*-loader", "*"],
["*-webpack-node-webkit-loader", "*-webpack-node-loader", "*-node-loader", "*-loader", "*-web-loader", "*"],
["*-loader", "*"]);
}; };

View File

@ -22,6 +22,7 @@ AMDDefineDependency.Template = function AMDRequireDependencyTemplate() {};
AMDDefineDependency.Template.prototype.apply = function(dep, source) { AMDDefineDependency.Template.prototype.apply = function(dep, source) {
var localModuleVar = dep.localModule && dep.localModule.used && dep.localModule.variableName(); var localModuleVar = dep.localModule && dep.localModule.used && dep.localModule.variableName();
function replace(def, text) { function replace(def, text) {
if(localModuleVar) text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); if(localModuleVar) text = text.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$"));
if(localModuleVar) def = def.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$")); if(localModuleVar) def = def.replace(/XXX/g, localModuleVar.replace(/\$/g, "$$$$"));

View File

@ -31,66 +31,67 @@ AMDDefineDependencyParserPlugin.prototype.apply = function(parser) {
parser.plugin("call define", function(expr) { parser.plugin("call define", function(expr) {
var array, fn, obj, namedModule; var array, fn, obj, namedModule;
switch(expr.arguments.length) { switch(expr.arguments.length) {
case 1: case 1:
if(expr.arguments[0].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[0])) { if(expr.arguments[0].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[0])) {
// define(f() {...}) // define(f() {...})
fn = expr.arguments[0]; fn = expr.arguments[0];
} else if(expr.arguments[0].type === "ObjectExpression") { } else if(expr.arguments[0].type === "ObjectExpression") {
// define({...}) // define({...})
obj = expr.arguments[0]; obj = expr.arguments[0];
} else { } else {
// define(expr) // define(expr)
// unclear if function or object // unclear if function or object
obj = fn = expr.arguments[0]; obj = fn = expr.arguments[0];
} }
break; break;
case 2: case 2:
if(expr.arguments[0].type === "Literal") { if(expr.arguments[0].type === "Literal") {
namedModule = expr.arguments[0].value;
// define("...", ...)
if(expr.arguments[1].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[1])) {
// define("...", f() {...})
fn = expr.arguments[1];
} else if(expr.arguments[1].type === "ObjectExpression") {
// define("...", {...})
obj = expr.arguments[1];
} else {
// define("...", expr)
// unclear if function or object
obj = fn = expr.arguments[1];
}
} else {
array = expr.arguments[0];
if(expr.arguments[1].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[1])) {
// define([...], f() {})
fn = expr.arguments[1];
} else if(expr.arguments[1].type === "ObjectExpression") {
// define([...], {...})
obj = expr.arguments[1];
} else {
// define([...], expr)
// unclear if function or object
obj = fn = expr.arguments[1];
}
}
break;
case 3:
// define("...", [...], f() {...})
namedModule = expr.arguments[0].value; namedModule = expr.arguments[0].value;
// define("...", ...) array = expr.arguments[1];
if(expr.arguments[1].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[1])) { if(expr.arguments[2].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[2])) {
// define("...", f() {...}) // define("...", [...], f() {})
fn = expr.arguments[1]; fn = expr.arguments[2];
} else if(expr.arguments[1].type === "ObjectExpression") { } else if(expr.arguments[2].type === "ObjectExpression") {
// define("...", {...}) // define("...", [...], {...})
obj = expr.arguments[1]; obj = expr.arguments[2];
} else { } else {
// define("...", expr) // define("...", [...], expr)
// unclear if function or object // unclear if function or object
obj = fn = expr.arguments[1]; obj = fn = expr.arguments[2];
} }
} else { break;
array = expr.arguments[0]; default:
if(expr.arguments[1].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[1])) { return;
// define([...], f() {})
fn = expr.arguments[1];
} else if(expr.arguments[1].type === "ObjectExpression") {
// define([...], {...})
obj = expr.arguments[1];
} else {
// define([...], expr)
// unclear if function or object
obj = fn = expr.arguments[1];
}
}
break;
case 3:
// define("...", [...], f() {...})
namedModule = expr.arguments[0].value;
array = expr.arguments[1];
if(expr.arguments[2].type === "FunctionExpression" || isBoundFunctionExpression(expr.arguments[2])) {
// define("...", [...], f() {})
fn = expr.arguments[2];
} else if(expr.arguments[2].type === "ObjectExpression") {
// define("...", [...], {...})
obj = expr.arguments[2];
} else {
// define("...", [...], expr)
// unclear if function or object
obj = fn = expr.arguments[2];
}
break;
default: return;
} }
var fnParams = null; var fnParams = null;
var fnParamsOffset = 0; var fnParamsOffset = 0;
@ -237,4 +238,3 @@ AMDDefineDependencyParserPlugin.prototype.apply = function(parser) {
return true; return true;
}); });
}; };

View File

@ -38,6 +38,7 @@ AMDPlugin.prototype.apply = function(compiler) {
return true; return true;
}); });
} }
function setExpressionToModule(expr, module) { function setExpressionToModule(expr, module) {
compiler.parser.plugin("expression " + expr, function(expr) { compiler.parser.plugin("expression " + expr, function(expr) {
var dep = new AMDRequireItemDependency(module, expr.range); var dep = new AMDRequireItemDependency(module, expr.range);
@ -111,4 +112,4 @@ AMDPlugin.prototype.apply = function(compiler) {
"webpack amd define": path.join(__dirname, "..", "..", "buildin", "amd-define.js") "webpack amd define": path.join(__dirname, "..", "..", "buildin", "amd-define.js")
}) })
); );
}; };

View File

@ -22,4 +22,3 @@ function AMDRequireDependenciesBlock(expr, arrayRange, functionRange, module, lo
module.exports = AMDRequireDependenciesBlock; module.exports = AMDRequireDependenciesBlock;
AMDRequireDependenciesBlock.prototype = Object.create(AsyncDependenciesBlock.prototype); AMDRequireDependenciesBlock.prototype = Object.create(AsyncDependenciesBlock.prototype);

View File

@ -21,46 +21,46 @@ AMDRequireDependenciesBlockParserPlugin.prototype.apply = function(parser) {
var options = this.options; var options = this.options;
parser.plugin("call require", function(expr) { parser.plugin("call require", function(expr) {
switch(expr.arguments.length) { switch(expr.arguments.length) {
case 1: case 1:
var param = this.evaluateExpression(expr.arguments[0]); var param = this.evaluateExpression(expr.arguments[0]);
var result;
var dep = new AMDRequireDependenciesBlock(expr, param.range, null, this.state.module, expr.loc);
var old = this.state.current;
this.state.current = dep;
this.inScope([], function() {
result = this.applyPluginsBailResult("call require:amd:array", expr, param);
}.bind(this));
this.state.current = old;
if(!result) return;
this.state.current.addBlock(dep);
return true;
case 2:
var param = this.evaluateExpression(expr.arguments[0]);
var dep = new AMDRequireDependenciesBlock(expr, param.range, expr.arguments[1].range, this.state.module, expr.loc);
dep.loc = expr.loc;
var old = this.state.current;
this.state.current = dep;
try {
var result; var result;
var dep = new AMDRequireDependenciesBlock(expr, param.range, null, this.state.module, expr.loc);
var old = this.state.current;
this.state.current = dep;
this.inScope([], function() { this.inScope([], function() {
result = this.applyPluginsBailResult("call require:amd:array", expr, param); result = this.applyPluginsBailResult("call require:amd:array", expr, param);
}.bind(this)); }.bind(this));
if(!result) return;
if(expr.arguments[1].type === "FunctionExpression") {
this.inScope(expr.arguments[1].params.filter(function(i) {
return ["require", "module", "exports"].indexOf(i.name) < 0;
}), function() {
if(expr.arguments[1].body.type === "BlockStatement")
this.walkStatement(expr.arguments[1].body);
else
this.walkExpression(expr.arguments[1].body);
}.bind(this));
}
} finally {
this.state.current = old; this.state.current = old;
if(!result) return;
this.state.current.addBlock(dep); this.state.current.addBlock(dep);
} return true;
return true; case 2:
var param = this.evaluateExpression(expr.arguments[0]);
var dep = new AMDRequireDependenciesBlock(expr, param.range, expr.arguments[1].range, this.state.module, expr.loc);
dep.loc = expr.loc;
var old = this.state.current;
this.state.current = dep;
try {
var result;
this.inScope([], function() {
result = this.applyPluginsBailResult("call require:amd:array", expr, param);
}.bind(this));
if(!result) return;
if(expr.arguments[1].type === "FunctionExpression") {
this.inScope(expr.arguments[1].params.filter(function(i) {
return ["require", "module", "exports"].indexOf(i.name) < 0;
}), function() {
if(expr.arguments[1].body.type === "BlockStatement")
this.walkStatement(expr.arguments[1].body);
else
this.walkExpression(expr.arguments[1].body);
}.bind(this));
}
} finally {
this.state.current = old;
this.state.current.addBlock(dep);
}
return true;
} }
}); });
parser.plugin("call require:amd:array", function(expr, param) { parser.plugin("call require:amd:array", function(expr, param) {
@ -134,4 +134,3 @@ AMDRequireDependenciesBlockParserPlugin.prototype.apply = function(parser) {
return true; return true;
}); });
}; };

View File

@ -90,4 +90,4 @@ CommonJsPlugin.prototype.apply = function(compiler) {
new CommonJsRequireDependencyParserPlugin(this.options), new CommonJsRequireDependencyParserPlugin(this.options),
new RequireResolveDependencyParserPlugin(this.options) new RequireResolveDependencyParserPlugin(this.options)
); );
}; };

View File

@ -89,4 +89,3 @@ CommonJsRequireDependencyParserPlugin.prototype.apply = function(parser) {
return true; return true;
}); });
}; };

View File

@ -27,8 +27,7 @@ module.exports = AbstractPlugin.create({
this.state.current.addDependency(dep); this.state.current.addDependency(dep);
return true; return true;
}, },
"export declaration": function() { "export declaration": function() {},
},
"export specifier": function(statement, id, name) { "export specifier": function(statement, id, name) {
var dep = new HarmonyExportSpecifierDependency(null, id, name, statement.range[1] + 0.5); var dep = new HarmonyExportSpecifierDependency(null, id, name, statement.range[1] + 0.5);
dep.loc = statement.loc; dep.loc = statement.loc;
@ -42,4 +41,3 @@ module.exports = AbstractPlugin.create({
return true; return true;
} }
}); });

View File

@ -30,4 +30,3 @@ module.exports = AbstractPlugin.create({
return true; return true;
} }
}); });

View File

@ -12,8 +12,7 @@ var NullFactory = require("../NullFactory");
var HarmonyImportDependencyParserPlugin = require("./HarmonyImportDependencyParserPlugin"); var HarmonyImportDependencyParserPlugin = require("./HarmonyImportDependencyParserPlugin");
var HarmonyExportDependencyParserPlugin = require("./HarmonyExportDependencyParserPlugin"); var HarmonyExportDependencyParserPlugin = require("./HarmonyExportDependencyParserPlugin");
function HarmonyModulesPlugin() { function HarmonyModulesPlugin() {}
}
module.exports = HarmonyModulesPlugin; module.exports = HarmonyModulesPlugin;
HarmonyModulesPlugin.prototype.apply = function(compiler) { HarmonyModulesPlugin.prototype.apply = function(compiler) {

View File

@ -19,7 +19,8 @@ LabeledModuleDependency.prototype.type = "labeled require";
LabeledModuleDependency.Template = function LabeledModuleDependencyTemplate() {}; LabeledModuleDependency.Template = function LabeledModuleDependencyTemplate() {};
LabeledModuleDependency.Template.prototype.apply = function(dep, source, outputOptions, requestShortener) { LabeledModuleDependency.Template.prototype.apply = function(dep, source, outputOptions, requestShortener) {
var comment = "", content; var comment = "",
content;
if(outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ "; if(outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ ";
if(dep.module && dep.module.meta && dep.module.meta.exports) { if(dep.module && dep.module.meta && dep.module.meta.exports) {
content = "var __WEBPACK_LABELED_MODULE__" + Template.toIdentifier(dep.module.id) + " = __webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")"; content = "var __WEBPACK_LABELED_MODULE__" + Template.toIdentifier(dep.module.id) + " = __webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")";

View File

@ -10,15 +10,15 @@ module.exports = AbstractPlugin.create({
"label require": function(stmt) { "label require": function(stmt) {
if(stmt.body.type !== "ExpressionStatement") return; if(stmt.body.type !== "ExpressionStatement") return;
switch(stmt.body.expression.type) { switch(stmt.body.expression.type) {
case "Literal": case "Literal":
var param = this.evaluateExpression(stmt.body.expression); var param = this.evaluateExpression(stmt.body.expression);
return this.applyPluginsBailResult("label require:item", stmt, param);
case "SequenceExpression":
stmt.body.expression.expressions.forEach(function(expression) {
var param = this.evaluateExpression(expression);
return this.applyPluginsBailResult("label require:item", stmt, param); return this.applyPluginsBailResult("label require:item", stmt, param);
}, this); case "SequenceExpression":
return true; stmt.body.expression.expressions.forEach(function(expression) {
var param = this.evaluateExpression(expression);
return this.applyPluginsBailResult("label require:item", stmt, param);
}, this);
return true;
} }
}, },
"label require:item": function(stmt, param) { "label require:item": function(stmt, param) {
@ -32,46 +32,45 @@ module.exports = AbstractPlugin.create({
}, },
"label exports": function(stmt) { "label exports": function(stmt) {
switch(stmt.body.type) { switch(stmt.body.type) {
case "VariableDeclaration": case "VariableDeclaration":
stmt.body.declarations.forEach(function(decl) { stmt.body.declarations.forEach(function(decl) {
if(!decl.init) return; if(!decl.init) return;
var dep = new LabeledExportsDependency(decl.id.name, decl.init.range[0]); var dep = new LabeledExportsDependency(decl.id.name, decl.init.range[0]);
dep.loc = stmt.loc; dep.loc = stmt.loc;
this.state.current.addDependency(dep); this.state.current.addDependency(dep);
if(!this.state.module.meta.exports) this.state.module.meta.exports = []; if(!this.state.module.meta.exports) this.state.module.meta.exports = [];
this.state.module.meta.exports.push(decl.id.name); this.state.module.meta.exports.push(decl.id.name);
}, this); }, this);
return true; return true;
case "FunctionDeclaration": case "FunctionDeclaration":
var name = stmt.body.id.name; var name = stmt.body.id.name;
var dep = new LabeledExportsDependency(name, stmt.body.range[0]); var dep = new LabeledExportsDependency(name, stmt.body.range[0]);
dep.loc = stmt.loc;
this.state.current.addDependency(dep);
if(!this.state.module.meta.exports) this.state.module.meta.exports = [];
this.state.module.meta.exports.push(name);
return true;
case "ExpressionStatement":
if(stmt.body.expression.type === "Identifier") {
var name = stmt.body.expression.name;
var dep = new LabeledExportsDependency(name, stmt.body.expression.range[0]);
dep.loc = stmt.loc; dep.loc = stmt.loc;
this.state.current.addDependency(dep); this.state.current.addDependency(dep);
if(!this.state.module.meta.exports) this.state.module.meta.exports = []; if(!this.state.module.meta.exports) this.state.module.meta.exports = [];
this.state.module.meta.exports.push(name); this.state.module.meta.exports.push(name);
return true; return true;
} else if(stmt.body.expression.type === "SequenceExpression") { case "ExpressionStatement":
stmt.body.expression.expressions.forEach(function(e) { if(stmt.body.expression.type === "Identifier") {
if(e.type !== "Identifier") return; var name = stmt.body.expression.name;
var name = e.name; var dep = new LabeledExportsDependency(name, stmt.body.expression.range[0]);
var dep = new LabeledExportsDependency(name, e.range[0]);
dep.loc = stmt.loc; dep.loc = stmt.loc;
this.state.current.addDependency(dep); this.state.current.addDependency(dep);
if(!this.state.module.meta.exports) this.state.module.meta.exports = []; if(!this.state.module.meta.exports) this.state.module.meta.exports = [];
this.state.module.meta.exports.push(name); this.state.module.meta.exports.push(name);
}, this); return true;
return true; } else if(stmt.body.expression.type === "SequenceExpression") {
} stmt.body.expression.expressions.forEach(function(e) {
if(e.type !== "Identifier") return;
var name = e.name;
var dep = new LabeledExportsDependency(name, e.range[0]);
dep.loc = stmt.loc;
this.state.current.addDependency(dep);
if(!this.state.module.meta.exports) this.state.module.meta.exports = [];
this.state.module.meta.exports.push(name);
}, this);
return true;
}
} }
} }
}); });

View File

@ -9,8 +9,7 @@ var NullFactory = require("../NullFactory");
var LabeledModuleDependencyParserPlugin = require("./LabeledModuleDependencyParserPlugin"); var LabeledModuleDependencyParserPlugin = require("./LabeledModuleDependencyParserPlugin");
function LabeledModulesPlugin() { function LabeledModulesPlugin() {}
}
module.exports = LabeledModulesPlugin; module.exports = LabeledModulesPlugin;
LabeledModulesPlugin.prototype.apply = function(compiler) { LabeledModulesPlugin.prototype.apply = function(compiler) {
@ -24,4 +23,4 @@ LabeledModulesPlugin.prototype.apply = function(compiler) {
compilation.dependencyTemplates.set(LabeledExportsDependency, new LabeledExportsDependency.Template()); compilation.dependencyTemplates.set(LabeledExportsDependency, new LabeledExportsDependency.Template());
}); });
compiler.parser.apply(new LabeledModuleDependencyParserPlugin()); compiler.parser.apply(new LabeledModuleDependencyParserPlugin());
}; };

View File

@ -4,8 +4,7 @@
*/ */
var LoaderDependency = require("./LoaderDependency"); var LoaderDependency = require("./LoaderDependency");
function LoaderPlugin() { function LoaderPlugin() {}
}
module.exports = LoaderPlugin; module.exports = LoaderPlugin;
LoaderPlugin.prototype.apply = function(compiler) { LoaderPlugin.prototype.apply = function(compiler) {
@ -19,7 +18,9 @@ LoaderPlugin.prototype.apply = function(compiler) {
loaderContext.loadModule = function loadModule(request, callback) { loaderContext.loadModule = function loadModule(request, callback) {
var dep = new LoaderDependency(request); var dep = new LoaderDependency(request);
dep.loc = request; dep.loc = request;
compilation.addModuleDependencies(module, [[dep]], true, "lm", false, function(err) { compilation.addModuleDependencies(module, [
[dep]
], true, "lm", false, function(err) {
if(err) return callback(err); if(err) return callback(err);
module = dep.module; module = dep.module;

View File

@ -16,4 +16,4 @@ LocalModule.prototype.flagUsed = function() {
LocalModule.prototype.variableName = function() { LocalModule.prototype.variableName = function() {
return "__WEBPACK_LOCAL_MODULE_" + this.idx + "__"; return "__WEBPACK_LOCAL_MODULE_" + this.idx + "__";
}; };

View File

@ -27,18 +27,17 @@ LocalModulesHelpers.getLocalModule = function(state, name, namedModule) {
}; };
function lookup(parent, mod) { function lookup(parent, mod) {
if (mod.charAt(0) !== ".") return mod; if(mod.charAt(0) !== ".") return mod;
var path = parent.split("/") var path = parent.split("/"),
, segs = mod.split("/"); segs = mod.split("/");
path.pop(); path.pop();
for (var i = 0; i < segs.length; i++) { for(var i = 0; i < segs.length; i++) {
var seg = segs[i]; var seg = segs[i];
if (seg === "..") path.pop(); if(seg === "..") path.pop();
else if (seg !== ".") path.push(seg); else if(seg !== ".") path.push(seg);
} }
return path.join("/"); return path.join("/");
} }

View File

@ -10,25 +10,24 @@ module.exports = AbstractPlugin.create({
var regExp = /^\.\/.*$/; var regExp = /^\.\/.*$/;
var recursive = true; var recursive = true;
switch(expr.arguments.length) { switch(expr.arguments.length) {
case 3: case 3:
var regExpExpr = this.evaluateExpression(expr.arguments[2]); var regExpExpr = this.evaluateExpression(expr.arguments[2]);
if(!regExpExpr.isRegExp()) return; if(!regExpExpr.isRegExp()) return;
regExp = regExpExpr.regExp; regExp = regExpExpr.regExp;
// falls through // falls through
case 2: case 2:
var recursiveExpr = this.evaluateExpression(expr.arguments[1]); var recursiveExpr = this.evaluateExpression(expr.arguments[1]);
if(!recursiveExpr.isBoolean()) return; if(!recursiveExpr.isBoolean()) return;
recursive = recursiveExpr.bool; recursive = recursiveExpr.bool;
// falls through // falls through
case 1: case 1:
var requestExpr = this.evaluateExpression(expr.arguments[0]); var requestExpr = this.evaluateExpression(expr.arguments[0]);
if(!requestExpr.isString()) return; if(!requestExpr.isString()) return;
var dep = new RequireContextDependency(requestExpr.string, recursive, regExp, expr.range); var dep = new RequireContextDependency(requestExpr.string, recursive, regExp, expr.range);
dep.loc = expr.loc; dep.loc = expr.loc;
dep.optional = this.scope.inTry; dep.optional = this.scope.inTry;
this.state.current.addDependency(dep); this.state.current.addDependency(dep);
return true; return true;
} }
} }
}); });

View File

@ -32,7 +32,7 @@ RequireContextPlugin.prototype.apply = function(compiler) {
callback(null, items.map(function(obj) { callback(null, items.map(function(obj) {
return extensions.filter(function(ext) { return extensions.filter(function(ext) {
var l = obj.request.length; var l = obj.request.length;
return (l > ext.length && obj.request.substr(l - ext.length, l) === ext); return l > ext.length && obj.request.substr(l - ext.length, l) === ext;
}).map(function(ext) { }).map(function(ext) {
var l = obj.request.length; var l = obj.request.length;
return { return {
@ -61,4 +61,4 @@ RequireContextPlugin.prototype.apply = function(compiler) {
}); });
}); });
new RequireContextDependencyParserPlugin().apply(compiler.parser); new RequireContextDependencyParserPlugin().apply(compiler.parser);
}; };

View File

@ -18,4 +18,3 @@ function RequireEnsureDependenciesBlock(expr, fnExpression, chunkName, chunkName
module.exports = RequireEnsureDependenciesBlock; module.exports = RequireEnsureDependenciesBlock;
RequireEnsureDependenciesBlock.prototype = Object.create(AsyncDependenciesBlock.prototype); RequireEnsureDependenciesBlock.prototype = Object.create(AsyncDependenciesBlock.prototype);

View File

@ -9,58 +9,58 @@ var getFunctionExpression = require("./getFunctionExpression");
module.exports = AbstractPlugin.create({ module.exports = AbstractPlugin.create({
"call require.ensure": function(expr) { "call require.ensure": function(expr) {
var chunkName = null, chunkNameRange = null; var chunkName = null,
chunkNameRange = null;
switch(expr.arguments.length) { switch(expr.arguments.length) {
case 3: case 3:
var chunkNameExpr = this.evaluateExpression(expr.arguments[2]); var chunkNameExpr = this.evaluateExpression(expr.arguments[2]);
if(!chunkNameExpr.isString()) return; if(!chunkNameExpr.isString()) return;
chunkNameRange = chunkNameExpr.range; chunkNameRange = chunkNameExpr.range;
chunkName = chunkNameExpr.string; chunkName = chunkNameExpr.string;
// falls through // falls through
case 2: case 2:
var dependenciesExpr = this.evaluateExpression(expr.arguments[0]); var dependenciesExpr = this.evaluateExpression(expr.arguments[0]);
var dependenciesItems = dependenciesExpr.isArray() ? dependenciesExpr.items : [dependenciesExpr]; var dependenciesItems = dependenciesExpr.isArray() ? dependenciesExpr.items : [dependenciesExpr];
var fnExpressionArg = expr.arguments[1]; var fnExpressionArg = expr.arguments[1];
var fnExpression = getFunctionExpression(fnExpressionArg); var fnExpression = getFunctionExpression(fnExpressionArg);
if(fnExpression) {
this.walkExpressions(fnExpression.expressions);
}
var dep = new RequireEnsureDependenciesBlock(expr, fnExpression ? fnExpression.fn : fnExpressionArg, chunkName, chunkNameRange, this.state.module, expr.loc);
var old = this.state.current;
this.state.current = dep;
try {
var failed = false;
this.inScope([], function() {
dependenciesItems.forEach(function(ee) {
if(ee.isString()) {
var edep = new RequireEnsureItemDependency(ee.string, ee.range);
edep.loc = dep.loc;
dep.addDependency(edep);
} else {
failed = true;
}
});
});
if(failed) {
return;
}
if(fnExpression) { if(fnExpression) {
if(fnExpression.fn.body.type === "BlockStatement") this.walkExpressions(fnExpression.expressions);
this.walkStatement(fnExpression.fn.body);
else
this.walkExpression(fnExpression.fn.body);
} }
old.addBlock(dep);
} finally { var dep = new RequireEnsureDependenciesBlock(expr, fnExpression ? fnExpression.fn : fnExpressionArg, chunkName, chunkNameRange, this.state.module, expr.loc);
this.state.current = old; var old = this.state.current;
} this.state.current = dep;
if(!fnExpression) { try {
this.walkExpression(fnExpressionArg); var failed = false;
} this.inScope([], function() {
return true; dependenciesItems.forEach(function(ee) {
if(ee.isString()) {
var edep = new RequireEnsureItemDependency(ee.string, ee.range);
edep.loc = dep.loc;
dep.addDependency(edep);
} else {
failed = true;
}
});
});
if(failed) {
return;
}
if(fnExpression) {
if(fnExpression.fn.body.type === "BlockStatement")
this.walkStatement(fnExpression.fn.body);
else
this.walkExpression(fnExpression.fn.body);
}
old.addBlock(dep);
} finally {
this.state.current = old;
}
if(!fnExpression) {
this.walkExpression(fnExpressionArg);
}
return true;
} }
} }
}); });

Some files were not shown because too many files have changed in this diff Show More