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": {
"node": true
},
"plugins": [
"nodeca"
],
"rules": {
"strict": 0,
"camelcase": 0,
"curly": 0,
"indent": [0, "tab"],
"nodeca/indent": [2, "tabs", 1 ],
"eol-last": 1,
"no-shadow": 0,
"no-redeclare": 1,
"no-extra-bind": 1,
"no-empty": 0,
"no-process-exit": 1,
"no-underscore-dangle": 0,
"no-use-before-define": 0,
"no-unused-vars": 0,
"consistent-return": 0,
"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
/coverage
.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)
[![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)
@ -97,6 +113,7 @@ Please see [Using Loaders](http://webpack.github.io/docs/using-loaders.html) for
**styling**
* [`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
* [`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
* [`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
@ -202,7 +219,7 @@ function loadTemplateAsync (name, callback) {
## 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:
@ -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.
[![Donate to sokra][donate-image]][donate-url]
## 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)
* [clone](https://github.com/pvorb/node-clone)
[![Dependency status][david-image]][david-url]
[travis-url]: http://travis-ci.org/webpack/webpack
[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
[npm-url]: https://npmjs.org/package/webpack
[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-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-image]: https://img.shields.io/badge/donate-sokra-brightgreen.svg
[gittip-url]: https://www.gittip.com/sokra/

View File

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

View File

@ -25,148 +25,181 @@ function runTimes(compiler, times, deferred) {
}
var tests = {
"normal build": [[0, 1, 5, 10, 50, 100, 200], function(size, deferred) {
webpack({
context: fixtures,
entry: "./" + size + ".js",
output: {
path: outputPath,
filename: "bundle.js"
}
}, 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",
output: {
path: outputPath,
filename: "bundle.js"
},
devtool: "eval"
}, function(err, stats) {
if(err) throw err;
deferred.resolve();
})
}],
"sourcemap build": [[0, 1, 2, 5, 10, 15], function(size, deferred) {
webpack({
context: fixtures,
entry: "./" + size + ".big.js",
output: {
path: outputPath,
filename: "bundle.js"
},
devtool: "source-map"
}, function(err, stats) {
if(err) throw err;
deferred.resolve();
})
}],
"cheap sourcemap build": [[0, 1, 2, 5, 10, 15], function(size, deferred) {
webpack({
context: fixtures,
entry: "./" + size + ".big.js",
output: {
path: outputPath,
filename: "bundle.js"
},
devtool: "cheap-source-map"
}, function(err, stats) {
if(err) throw err;
deferred.resolve();
})
}],
"build w/ chunks": [[0, 1, 5, 10, 50, 100, 200], function(size, deferred) {
webpack({
context: fixtures,
entry: "./" + size + ".async.js",
output: {
path: outputPath,
filename: "bundle.js"
}
}, function(err, stats) {
if(err) throw err;
deferred.resolve();
})
}],
"build w/ chunks": [[0, 1, 5, 10, 50, 100, 200], function(size, deferred) {
webpack({
context: fixtures,
entry: "./" + size + ".async.js",
output: {
path: outputPath,
filename: "bundle.js"
}
}, function(err, stats) {
if(err) throw err;
deferred.resolve();
})
}],
"incremental": [[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, 2, deferred);
}],
"incremental cheap sourcemap": [[1, 2, 3, 4, 5, 6], function(size, deferred) {
var compiler = webpack({
cache: true,
context: fixtures,
entry: "./200.js",
output: {
path: outputPath,
filename: "bundle.js"
},
devtool: "cheap-source-map"
});
runTimes(compiler, size, deferred);
}],
"incremental2": [[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, 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);
}],
"normal build": [
[0, 1, 5, 10, 50, 100, 200],
function(size, deferred) {
webpack({
context: fixtures,
entry: "./" + size + ".js",
output: {
path: outputPath,
filename: "bundle.js"
}
}, 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",
output: {
path: outputPath,
filename: "bundle.js"
},
devtool: "eval"
}, function(err, stats) {
if(err) throw err;
deferred.resolve();
})
}
],
"sourcemap build": [
[0, 1, 2, 5, 10, 15],
function(size, deferred) {
webpack({
context: fixtures,
entry: "./" + size + ".big.js",
output: {
path: outputPath,
filename: "bundle.js"
},
devtool: "source-map"
}, function(err, stats) {
if(err) throw err;
deferred.resolve();
})
}
],
"cheap sourcemap build": [
[0, 1, 2, 5, 10, 15],
function(size, deferred) {
webpack({
context: fixtures,
entry: "./" + size + ".big.js",
output: {
path: outputPath,
filename: "bundle.js"
},
devtool: "cheap-source-map"
}, function(err, stats) {
if(err) throw err;
deferred.resolve();
})
}
],
"build w/ chunks": [
[0, 1, 5, 10, 50, 100, 200],
function(size, deferred) {
webpack({
context: fixtures,
entry: "./" + size + ".async.js",
output: {
path: outputPath,
filename: "bundle.js"
}
}, function(err, stats) {
if(err) throw err;
deferred.resolve();
})
}
],
"build w/ chunks": [
[0, 1, 5, 10, 50, 100, 200],
function(size, deferred) {
webpack({
context: fixtures,
entry: "./" + size + ".async.js",
output: {
path: outputPath,
filename: "bundle.js"
}
}, function(err, stats) {
if(err) throw err;
deferred.resolve();
})
}
],
"incremental": [
[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, 2, deferred);
}
],
"incremental cheap sourcemap": [
[1, 2, 3, 4, 5, 6],
function(size, deferred) {
var compiler = webpack({
cache: true,
context: fixtures,
entry: "./200.js",
output: {
path: outputPath,
filename: "bundle.js"
},
devtool: "cheap-source-map"
});
runTimes(compiler, size, deferred);
}
],
"incremental2": [
[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, 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;
@ -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)));
});
suite.run({ async: true });
suite.run({
async: true
});

View File

@ -3,19 +3,20 @@ var fs = require("fs");
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++) {
var source = [];
if(i > 8)
source.push("require("+ JSON.stringify("./" + (i / 8 | 0) + ".js") + ");");
source.push("require(" + JSON.stringify("./" + (i / 8 | 0) + ".js") + ");");
if(i > 4)
source.push("require("+ JSON.stringify("./" + (i / 4 | 0) + ".js") + ");");
source.push("require(" + JSON.stringify("./" + (i / 4 | 0) + ".js") + ");");
if(i > 2)
source.push("require("+ JSON.stringify("./" + (i / 2 | 0) + ".js") + ");");
source.push("require(" + JSON.stringify("./" + (i / 2 | 0) + ".js") + ");");
if(i > 0)
source.push("require("+ JSON.stringify("./" + (i - 1) + ".js") + ");");
source.push("require(" + JSON.stringify("./" + (i - 1) + ".js") + ");");
source.push("module.exports = " + i + ";");
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 = [];
source.push("require.ensure([], function(require) {");
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)
source.push("require("+ JSON.stringify("./" + (i / 4 | 0) + ".async.js") + ");");
source.push("require(" + JSON.stringify("./" + (i / 4 | 0) + ".async.js") + ");");
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)
source.push("require("+ JSON.stringify("./" + (i - 1) + ".async.js") + ");");
source.push("require(" + JSON.stringify("./" + (i - 1) + ".async.js") + ");");
source.push("});");
source.push("module.exports = " + i + ";");
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++) {
var source = [];
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)
source.push("require("+ JSON.stringify("./" + (i / 4 | 0) + ".big.js") + ");");
source.push("require(" + JSON.stringify("./" + (i / 4 | 0) + ".big.js") + ");");
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)
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++)
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 + ";");

View File

@ -265,6 +265,12 @@ module.exports = function(optimist, argv, convertOptions) {
});
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");
options.output.filename = value;
});

View File

@ -28,7 +28,10 @@ if(module.hot) {
}
}).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] " + err.stack || err.message);
window.location.reload();
@ -39,7 +42,7 @@ if(module.hot) {
};
var addEventListener = window.addEventListener ? function(eventName, listener) {
window.addEventListener(eventName, listener, false);
} : function (eventName, listener) {
} : function(eventName, listener) {
window.attachEvent("on" + eventName, listener);
};
addEventListener("message", function(event) {

View File

@ -20,7 +20,10 @@ if(module.hot) {
ignoreUnaccepted: true
}, function(err, renewedModules) {
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] " + err.stack || err.message);
} else {
@ -40,7 +43,10 @@ if(module.hot) {
}
});
}).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] " + err.stack || err.message);
} else {
@ -50,7 +56,7 @@ if(module.hot) {
};
var addEventListener = window.addEventListener ? function(eventName, listener) {
window.addEventListener(eventName, listener, false);
} : function (eventName, listener) {
} : function(eventName, listener) {
window.attachEvent("on" + eventName, listener);
};
addEventListener("message", function(event) {

View File

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

View File

@ -18,7 +18,10 @@ if(module.hot) {
ignoreUnaccepted: true
}, function(err, renewedModules) {
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] " + err.stack || err.message);
console.warn("[HMR] You need to restart the application!");
@ -33,7 +36,10 @@ if(module.hot) {
checkForUpdate(true);
});
}).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] " + err.stack || err.message);
console.warn("[HMR] You need to restart the application!");

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -73,7 +73,11 @@ Chunk.prototype.addBlock = function(block) {
};
Chunk.prototype.addOrigin = function(module, loc) {
this.origins.push({module: module, loc: loc, name: this.name});
this.origins.push({
module: module,
loc: loc,
name: this.name
});
};
Chunk.prototype.remove = function(reason) {
@ -123,6 +127,7 @@ Chunk.prototype.integrate = function(other, reason) {
m.rewriteChunkInReasons(other, [this]);
}, this);
other.modules.length = 0;
function moveChunks(chunks, kind, onChunk) {
chunks.forEach(function(c) {
var idx = c[kind].indexOf(other);
@ -164,7 +169,7 @@ Chunk.prototype.integrate = function(other, reason) {
};
Chunk.prototype.isEmpty = function() {
return (this.modules.length === 0);
return this.modules.length === 0;
};
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 source = this.applyPluginsWaterfall("render", core, chunk, moduleTemplate, dependencyTemplates);
if(chunk.modules.some(function(module) {
return (module.entry);
})) {
return module.entry;
})) {
source = this.applyPluginsWaterfall("render-with-entry", source, chunk);
}
chunk.rendered = true;

View File

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

View File

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

View File

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

View File

@ -7,8 +7,7 @@ var BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
var NullFactory = require("./NullFactory");
function ConstPlugin() {
}
function ConstPlugin() {}
module.exports = ConstPlugin;
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]));
return true;
});
};
};

View File

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

View File

@ -123,7 +123,9 @@ ContextModuleFactory.prototype.resolveDependencies = function resolveDependencie
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);
}, []));
});

View File

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

View File

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

View File

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

View File

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

View File

@ -14,4 +14,4 @@ EvalDevToolModulePlugin.prototype.apply = function(compiler) {
compiler.plugin("compilation", function(compilation) {
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),
self.sourceUrlComment.replace(/\[url\]/g, encodeURI(str).replace(/%2F/g, "/").replace(/%20/g, "_").replace(/%5E/g, "^").replace(/%5C/g, "\\").replace(/^\//, ""))
].join("\n");
return new RawSource("eval(" + JSON.stringify(content + footer) + ");" );
return new RawSource("eval(" + JSON.stringify(content + footer) + ");");
});
moduleTemplate.plugin("hash", function(hash) {
hash.update("EvalDevToolModuleTemplatePlugin");

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -122,13 +122,17 @@ function MultiStats(stats) {
MultiStats.prototype.hasErrors = function() {
return this.stats.map(function(stat) {
return stat.hasErrors();
}).reduce(function(a, b) { return a || b; }, false);
}).reduce(function(a, b) {
return a || b;
}, false);
};
MultiStats.prototype.hasWarnings = function() {
return this.stats.map(function(stat) {
return stat.hasWarnings();
}).reduce(function(a, b) { return a || b; }, false);
}).reduce(function(a, b) {
return a || b;
}, false);
};
MultiStats.prototype.toJson = function(options, forToString) {
@ -158,4 +162,4 @@ MultiStats.prototype.toJson = function(options, forToString) {
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
Author Tobias Koppers @sokra
*/
function NewWatchingPlugin() {
}
function NewWatchingPlugin() {}
module.exports = NewWatchingPlugin;
NewWatchingPlugin.prototype.apply = function(compiler) {

View File

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

View File

@ -19,13 +19,18 @@ NodeStuffPlugin.prototype.apply = function(compiler) {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
});
function ignore() { return true; }
function ignore() {
return true;
}
function setConstant(expressionName, value) {
compiler.parser.plugin("expression " + expressionName, function() {
this.state.current.addVariable(expressionName, JSON.stringify(value));
return true;
});
}
function setModuleConstant(expressionName, fn) {
compiler.parser.plugin("expression " + expressionName, function() {
this.state.current.addVariable(expressionName, JSON.stringify(fn(this.state.module)));
@ -84,4 +89,4 @@ NodeStuffPlugin.prototype.apply = function(compiler) {
compiler.parser.plugin("expression module", function() {
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(Array.isArray(options.module.noParse)) {
if(options.module.noParse.some(function(regExp) {
return typeof regExp === "string" ?
this.request.indexOf(regExp) === 0 :
regExp.test(this.request);
}, this)) return callback();
return typeof regExp === "string" ?
this.request.indexOf(regExp) === 0 :
regExp.test(this.request);
}, this)) return callback();
} else if(typeof options.module.noParse === "string" ?
this.request.indexOf(options.module.noParse) === 0 :
options.module.noParse.test(this.request)) {
this.request.indexOf(options.module.noParse) === 0 :
options.module.noParse.test(this.request)) {
return callback();
}
}
@ -125,21 +125,30 @@ NormalModule.prototype.source = function(dependencyTemplates, outputOptions, req
var _source = this._source;
if(!_source) return new RawSource("throw new Error('No source available');");
var source = new ReplaceSource(_source);
this._cachedSource = { source: source, hash: hash };
this._cachedSource = {
source: source,
hash: hash
};
var topLevelBlock = this;
function doDep(dep) {
var template = dependencyTemplates.get(dep.Class);
if(!template) throw new Error("No template for dependency: " + dep.Class.name);
template.apply(dep, source, outputOptions, requestShortener, dependencyTemplates);
}
function doVariable(availableVars, vars, variable) {
var name = variable.name;
var expr = variable.expressionSource(dependencyTemplates, outputOptions, requestShortener);
if(availableVars.some(function(v) {
return v.name === name && v.expression.source() === expr.source();
})) return;
vars.push({name: name, expression: expr});
return v.name === name && v.expression.source() === expr.source();
})) return;
vars.push({
name: name,
expression: expr
});
}
function doBlock(availableVars, block) {
block.dependencies.forEach(doDep);
var vars = [];
@ -149,6 +158,7 @@ NormalModule.prototype.source = function(dependencyTemplates, outputOptions, req
var varExpressions = [];
var varStartCode = "";
var varEndCode = "";
function emitFunction() {
if(varNames.length === 0) return;
@ -218,13 +228,16 @@ NormalModule.prototype.getSourceHash = function() {
NormalModule.prototype.getAllModuleDependencies = function() {
var list = [];
function doDep(dep) {
if(dep.module && list.indexOf(dep.module) < 0)
list.push(dep.module);
}
function doVariable(variable) {
variable.dependencies.forEach(doDep);
}
function doBlock(block) {
block.variables.forEach(doVariable);
block.dependencies.forEach(doDep);
@ -260,6 +273,7 @@ NormalModule.prototype.createTemplate = function(keepModules, roots) {
return array.join("|");
};
var args = template.arguments = [];
function doDeps(deps) {
return deps.map(function(dep) {
if(dep.module && keepModules.indexOf(dep.module) < 0) {
@ -271,6 +285,7 @@ NormalModule.prototype.createTemplate = function(keepModules, roots) {
}
});
}
function doBlock(block, newBlock) {
block.variables.forEach(function(variable) {
var newDependencies = doDeps(variable.dependencies);
@ -289,13 +304,16 @@ NormalModule.prototype.createTemplate = function(keepModules, roots) {
NormalModule.prototype.getTemplateArguments = function(keepModules) {
var list = [];
function doDep(dep) {
if(dep.module && keepModules.indexOf(dep.module) < 0)
list.push(dep.module);
}
function doVariable(variable) {
variable.dependencies.forEach(doDep);
}
function doBlock(block) {
block.variables.forEach(doVariable);
block.dependencies.forEach(doDep);

View File

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

View File

@ -4,6 +4,7 @@
*/
var path = require("path");
function NormalModuleReplacementPlugin(resourceRegExp, newResource) {
this.resourceRegExp = resourceRegExp;
this.newResource = newResource;
@ -16,7 +17,7 @@ NormalModuleReplacementPlugin.prototype.apply = function(compiler) {
nmf.plugin("before-resolve", function(result, callback) {
if(!result) return callback();
if(resourceRegExp.test(result.request)) {
if (typeof newResource === "function") {
if(typeof newResource === "function") {
newResource(result);
} else {
result.request = newResource;
@ -27,7 +28,7 @@ NormalModuleReplacementPlugin.prototype.apply = function(compiler) {
nmf.plugin("after-resolve", function(result, callback) {
if(!result) return callback();
if(resourceRegExp.test(result.resource)) {
if (typeof newResource === "function") {
if(typeof newResource === "function") {
newResource(result);
} else {
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
Author Tobias Koppers @sokra
*/
function NullFactory() {
}
function NullFactory() {}
module.exports = NullFactory;
NullFactory.prototype.create = function(context, dependency, callback) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,4 +2,4 @@
MIT License http://www.opensource.org/licenses/mit-license.php
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");
function RecordIdsPlugin() {
}
function RecordIdsPlugin() {}
module.exports = RecordIdsPlugin;
function makeRelative(compiler, identifier) {

View File

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

View File

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

View File

@ -2,4 +2,4 @@
MIT License http://www.opensource.org/licenses/mit-license.php
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*/");
}
if(sourceMapFilename) {
var filename = file, query = "";
var filename = file,
query = "";
var idx = filename.indexOf("?");
if(idx >= 0) {
query = filename.substr(idx);
@ -165,4 +166,3 @@ function basename(name) {
if(name.indexOf("/") < 0) return name;
return name.substr(name.lastIndexOf("/") + 1);
}

View File

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

View File

@ -28,7 +28,8 @@ Template.prototype.indent = function indent(str) {
} else {
str = str.trimRight();
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();
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) {
@ -50,8 +52,8 @@ Template.prototype.asString = function(str) {
Template.prototype.getModulesArrayBounds = function(modules) {
if(modules.some(function(module) {
return typeof module.id !== "number";
}))
return typeof module.id !== "number";
}))
return false;
var maxId = -Infinity;
var minId = Infinity;
@ -64,8 +66,11 @@ Template.prototype.getModulesArrayBounds = function(modules) {
minId = 0;
}
var objectOverhead = modules.map(function(module) {
return (module.id + "").length + 2;
}).reduce(function(a, b) { return a + b; }, -1);
var idLength = (module.id + "").length;
return idLength + 2;
}).reduce(function(a, b) {
return a + b;
}, -1);
var arrayOverhead = minId === 0 ? maxId : 16 + ("" + minId).length + maxId;
return arrayOverhead < objectOverhead ? [minId, maxId] : false;
};

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -38,6 +38,7 @@ AMDPlugin.prototype.apply = function(compiler) {
return true;
});
}
function setExpressionToModule(expr, module) {
compiler.parser.plugin("expression " + expr, function(expr) {
var dep = new AMDRequireItemDependency(module, expr.range);
@ -111,4 +112,4 @@ AMDPlugin.prototype.apply = function(compiler) {
"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;
AMDRequireDependenciesBlock.prototype = Object.create(AsyncDependenciesBlock.prototype);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -10,15 +10,15 @@ module.exports = AbstractPlugin.create({
"label require": function(stmt) {
if(stmt.body.type !== "ExpressionStatement") return;
switch(stmt.body.expression.type) {
case "Literal":
var param = this.evaluateExpression(stmt.body.expression);
return this.applyPluginsBailResult("label require:item", stmt, param);
case "SequenceExpression":
stmt.body.expression.expressions.forEach(function(expression) {
var param = this.evaluateExpression(expression);
case "Literal":
var param = this.evaluateExpression(stmt.body.expression);
return this.applyPluginsBailResult("label require:item", stmt, param);
}, this);
return true;
case "SequenceExpression":
stmt.body.expression.expressions.forEach(function(expression) {
var param = this.evaluateExpression(expression);
return this.applyPluginsBailResult("label require:item", stmt, param);
}, this);
return true;
}
},
"label require:item": function(stmt, param) {
@ -32,46 +32,45 @@ module.exports = AbstractPlugin.create({
},
"label exports": function(stmt) {
switch(stmt.body.type) {
case "VariableDeclaration":
stmt.body.declarations.forEach(function(decl) {
if(!decl.init) return;
var dep = new LabeledExportsDependency(decl.id.name, decl.init.range[0]);
dep.loc = stmt.loc;
this.state.current.addDependency(dep);
if(!this.state.module.meta.exports) this.state.module.meta.exports = [];
this.state.module.meta.exports.push(decl.id.name);
}, this);
return true;
case "FunctionDeclaration":
var name = stmt.body.id.name;
var dep = new LabeledExportsDependency(name, stmt.body.range[0]);
dep.loc = stmt.loc;
this.state.current.addDependency(dep);
if(!this.state.module.meta.exports) this.state.module.meta.exports = [];
this.state.module.meta.exports.push(name);
return true;
case "ExpressionStatement":
if(stmt.body.expression.type === "Identifier") {
var name = stmt.body.expression.name;
var dep = new LabeledExportsDependency(name, stmt.body.expression.range[0]);
case "VariableDeclaration":
stmt.body.declarations.forEach(function(decl) {
if(!decl.init) return;
var dep = new LabeledExportsDependency(decl.id.name, decl.init.range[0]);
dep.loc = stmt.loc;
this.state.current.addDependency(dep);
if(!this.state.module.meta.exports) this.state.module.meta.exports = [];
this.state.module.meta.exports.push(decl.id.name);
}, this);
return true;
case "FunctionDeclaration":
var name = stmt.body.id.name;
var dep = new LabeledExportsDependency(name, stmt.body.range[0]);
dep.loc = stmt.loc;
this.state.current.addDependency(dep);
if(!this.state.module.meta.exports) this.state.module.meta.exports = [];
this.state.module.meta.exports.push(name);
return true;
} 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]);
case "ExpressionStatement":
if(stmt.body.expression.type === "Identifier") {
var name = stmt.body.expression.name;
var dep = new LabeledExportsDependency(name, stmt.body.expression.range[0]);
dep.loc = stmt.loc;
this.state.current.addDependency(dep);
if(!this.state.module.meta.exports) this.state.module.meta.exports = [];
this.state.module.meta.exports.push(name);
}, 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");
function LabeledModulesPlugin() {
}
function LabeledModulesPlugin() {}
module.exports = LabeledModulesPlugin;
LabeledModulesPlugin.prototype.apply = function(compiler) {
@ -24,4 +23,4 @@ LabeledModulesPlugin.prototype.apply = function(compiler) {
compilation.dependencyTemplates.set(LabeledExportsDependency, new LabeledExportsDependency.Template());
});
compiler.parser.apply(new LabeledModuleDependencyParserPlugin());
};
};

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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