Merge branch 'master' into webpack-2

Conflicts:
	.travis.yml
	bin/config-optimist.js
	package.json
	test/TestCases.test.js
This commit is contained in:
Tobias Koppers 2015-08-09 13:32:19 +02:00
commit 7934faa181
25 changed files with 355 additions and 306 deletions

View File

@ -1,8 +1,10 @@
sudo: false
language: node_js
node_js:
- "0.12"
- "iojs"
- node
- iojs-1
- iojs-2
- iojs
script: npm run travis
env:
- NO_WATCH_TESTS=1

View File

@ -12,14 +12,14 @@ that include your webpack.config.js and relevant files are more likely to receiv
If you have created your own loader/plugin please include it on the relevant
documentation pages:
[List of loaders](http://webpack.github.io/docs/list-of-loaders.html)
[List of plugins](http://webpack.github.io/docs/list-of-plugins.html)
[List of loaders](https://webpack.github.io/docs/list-of-loaders.html)
[List of plugins](https://webpack.github.io/docs/list-of-plugins.html)
### Documentation
webpack is insanely feature rich and documentation is a huge time sink. We
greatly appreciate any time spent fixing typos or clarifying sections in the
documentation.
documentation.
## Submitting Changes
@ -38,4 +38,3 @@ Some things that will increase the chance that your pull request is accepted:
* Write tests
* Follow the existing coding style
* Write a [good commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)

View File

@ -1,24 +1,20 @@
[![webpack](http://webpack.github.io/assets/logo.png)](http://webpack.github.io)
[![webpack](https://webpack.github.io/assets/logo.png)](https://webpack.github.io)
[![NPM version][npm-image]][npm-url] [![Gitter chat][gitter-image]][gitter-url] [![Downloads][downloads-image]][downloads-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]
build
[![Build Status][travis-image]][travis-url] [![Appveyor Status][appveyor-image]][appveyor-url] [![Coverage Status][coveralls-image]][coveralls-url]
dependencies
dependencies
[![Dependency Status][david-image]][david-url] [![devDependency Status][david-dev-image]][david-dev-url] [![peerDependency Status][david-peer-image]][david-peer-url]
donation
donation
[![Gittip donate button][gittip-image]][gittip-url] [![Donate to sokra][donate-image]][donate-url]
[documentation](http://webpack.github.io/docs/?utm_source=github&utm_medium=readme&utm_campaign=top)
[documentation](https://webpack.github.io/docs/?utm_source=github&utm_medium=readme&utm_campaign=top)
# Introduction
@ -37,7 +33,7 @@ or packaging just about any resource or asset.
# Getting Started
Check out webpack's [documentation](http://webpack.github.io/docs/?utm_source=github&utm_medium=readme&utm_campaign=trdr) for quick Getting Started guide, in-depth usage,
Check out webpack's [documentation](https://webpack.github.io/docs/?utm_source=github&utm_medium=readme&utm_campaign=trdr) for quick Getting Started guide, in-depth usage,
tutorials and resources.
# Installation
@ -48,7 +44,7 @@ project:
global:
`npm install webpack -g`
Usage
http://webpack.github.io/docs/tutorials/getting-started/
https://webpack.github.io/docs/tutorials/getting-started/
# Examples
@ -59,7 +55,7 @@ Take a look at the [`examples`](https://github.com/webpack/webpack/tree/master/e
## Plugins
webpack has a [rich plugin
interface](http://webpack.github.io/docs/plugins.html). Most of the features
interface](https://webpack.github.io/docs/plugins.html). Most of the features
within webpack itself use this plugin interface. This makes webpack very
**flexible**.
@ -73,12 +69,12 @@ and incredibly **fast** on incremental compilations.
webpack enables use of loaders to preprocess files. This allows you to bundle
**any static resource** way beyond JavaScript. You can easily [write your own
loaders](http://webpack.github.io/docs/loaders.html) using node.js.
loaders](https://webpack.github.io/docs/loaders.html) using node.js.
Loaders are activated by using `loadername!` prefixes in `require()` statements,
or are automatically applied via regex from your webpack configuration.
Please see [Using Loaders](http://webpack.github.io/docs/using-loaders.html) for more information.
Please see [Using Loaders](https://webpack.github.io/docs/using-loaders.html) for more information.
**basic**
* [`json`](https://github.com/webpack/json-loader): Loads file as JSON
@ -98,7 +94,7 @@ Please see [Using Loaders](http://webpack.github.io/docs/using-loaders.html) for
* [`coffee`](https://github.com/webpack/coffee-loader): Loads coffee-script like JavaScript
* [`babel`](https://github.com/babel/babel-loader): Turn ES6 code into vanilla ES5 using [Babel](https://github.com/babel/babel).
* [`livescript`](https://github.com/appedemic/livescript-loader): Loads LiveScript like JavaScript
* [`sweetjs`](https://github.com/jlongster/sweetjs-loader): Use sweetjs macros.
* [`sweetjs`](https://github.com/jlongster/sweetjs-loader): Use sweetjs macros.
* [`traceur`](https://github.com/jupl/traceur-loader): Use future JavaScript features with [Traceur](https://github.com/google/traceur-compiler).
* [`typescript`](https://github.com/andreypopp/typescript-loader): Loads TypeScript like JavaScript.
@ -127,7 +123,7 @@ Please see [Using Loaders](http://webpack.github.io/docs/using-loaders.html) for
* [`injectable`](https://github.com/jauco/webpack-injectable): Allow to inject dependencies into modules
* [`transform`](https://github.com/webpack/transform-loader): Use browserify transforms as loader.
For the full list of loaders, see [list of loaders](http://webpack.github.io/docs/list-of-loaders.html).
For the full list of loaders, see [list of loaders](https://webpack.github.io/docs/list-of-loaders.html).
## Module Format (AMD/CommonJS)
@ -140,7 +136,7 @@ simple expressions. This allows you to **support most existing libraries** out o
webpack allows you to split your codebase into multiple chunks. Chunks are
loaded asynchronously at runtime. This reduces the initial loading time.
[Code Splitting documentation](http://webpack.github.io/docs/code-splitting.html)
[Code Splitting documentation](https://webpack.github.io/docs/code-splitting.html)
## Optimizations
@ -148,9 +144,9 @@ webpack can do many optimizations to **reduce the output size of your
JavaScript** by deduplicating frequently used modules, minifying, and giving
you full control of what is loaded initially and what is loaded at runtime
through code splitting. It can also can make your code chunks **cache
friendly** by using hashes.
friendly** by using hashes.
[Optimization documentation](http://webpack.github.io/docs/optimization.html)
[Optimization documentation](https://webpack.github.io/docs/optimization.html)
webpack optimizes in several ways. It also makes your chunks **cache-friendly** by using hashes.
@ -160,7 +156,7 @@ webpack optimizes in several ways. It also makes your chunks **cache-friendly**
// webpack is a module bundler.
// This means webpack takes modules with dependencies
// and emits static assets representing those modules.
// Dependencies can be written in CommonJs
var commonjs = require("./commonjs");
// or in AMD
@ -178,8 +174,8 @@ define(["amd-module", "../file"], function (amdModule, file) {
// of the AMD require.
});
});
require("coffee!./cup.coffee");
// "Loaders" are used to preprocess files.
// They can be prefixed in the require call
@ -200,7 +196,7 @@ function loadTemplate (name) {
// ...and you can combine everything.
function loadTemplateAsync (name, callback) {
require(["bundle?lazy!./templates/" + name + ".jade"],
require(["bundle?lazy!./templates/" + name + ".jade"],
function (templateBundle) {
templateBundle(callback);
});
@ -209,12 +205,12 @@ function loadTemplateAsync (name, callback) {
## Documentation
[documentation](http://webpack.github.io/docs/?utm_source=github&utm_medium=readme&utm_campaign=documentation)
[documentation](https://webpack.github.io/docs/?utm_source=github&utm_medium=readme&utm_campaign=documentation)
## Changelog
[changelog](http://webpack.github.io/docs/changelog.html)
[changelog](https://webpack.github.io/docs/changelog.html)
## Tests

View File

@ -1,91 +1,47 @@
module.exports = function(optimist) {
optimist
.boolean("help").alias("help", "h").alias("help", "?").describe("help")
.string("config").describe("config")
.string("env").describe("env", "Enviroment passed to the config, when it is a function")
.string("context").describe("context")
.string("entry").describe("entry")
.string("module-bind").describe("module-bind")
.string("module-bind-post").describe("module-bind-post")
.string("module-bind-pre").describe("module-bind-pre")
.string("output-path").describe("output-path")
.string("output-file").describe("output-file")
.string("output-chunk-file").describe("output-chunk-file")
.string("output-source-map-file").describe("output-source-map-file")
.string("output-public-path").describe("output-public-path")
.string("output-jsonp-function").describe("output-jsonp-function")
.boolean("output-pathinfo").describe("output-pathinfo")
.string("output-library").describe("output-library")
.string("output-library-target").describe("output-library-target")
.string("records-input-path").describe("records-input-path")
.string("records-output-path").describe("records-output-path")
.string("records-path").describe("records-path")
.string("define").describe("define")
.string("target").describe("target")
.boolean("cache").describe("cache").default("cache", true)
.boolean("watch").alias("watch", "w").describe("watch")
.describe("watch-aggregate-timeout")
.describe("watch-poll")
.boolean("hot").alias("hot", "h").describe("hot")
.boolean("debug").describe("debug")
.string("devtool").describe("devtool")
.boolean("progress").describe("progress")
.string("resolve-alias").describe("resolve-alias")
.string("resolve-loader-alias").describe("resolve-loader-alias")
.describe("optimize-max-chunks")
.describe("optimize-min-chunk-size")
.boolean("optimize-minimize").describe("optimize-minimize")
.boolean("optimize-dedupe").describe("optimize-dedupe")
.string("prefetch").describe("prefetch")
.string("provide").describe("provide")
.boolean("labeled-modules").describe("labeled-modules")
.string("plugin").describe("plugin")
.boolean("bail").describe("bail")
.boolean("profile").describe("profile")
.boolean("d").describe("d", "shortcut for --debug --devtool sourcemap --output-pathinfo")
.boolean("p").describe("p", "shortcut for --optimize-minimize");
};
.boolean("help").alias("help", "h").alias("help", "?").describe("help")
.string("config").describe("config")
.string("env").describe("env", "Enviroment passed to the config, when it is a function")
.string("context").describe("context")
.string("entry").describe("entry")
.string("module-bind").describe("module-bind")
.string("module-bind-post").describe("module-bind-post")
.string("module-bind-pre").describe("module-bind-pre")
.string("output-path").describe("output-path")
.string("output-file").describe("output-file")
.string("output-chunk-file").describe("output-chunk-file")
.string("output-source-map-file").describe("output-source-map-file")
.string("output-public-path").describe("output-public-path")
.string("output-jsonp-function").describe("output-jsonp-function")
.boolean("output-pathinfo").describe("output-pathinfo")
.string("output-library").describe("output-library")
.string("output-library-target").describe("output-library-target")
.string("records-input-path").describe("records-input-path")
.string("records-output-path").describe("records-output-path")
.string("records-path").describe("records-path")
.string("define").describe("define")
.string("target").describe("target")
.boolean("cache").describe("cache").default("cache", true)
.boolean("watch").alias("watch", "w").describe("watch")
.describe("watch-aggregate-timeout")
.describe("watch-poll")
.boolean("hot").alias("hot", "h").describe("hot")
.boolean("debug").describe("debug")
.string("devtool").describe("devtool")
.boolean("progress").describe("progress")
.string("resolve-alias").describe("resolve-alias")
.string("resolve-loader-alias").describe("resolve-loader-alias")
.describe("optimize-max-chunks")
.describe("optimize-min-chunk-size")
.boolean("optimize-minimize").describe("optimize-minimize")
.boolean("optimize-dedupe").describe("optimize-dedupe")
.string("prefetch").describe("prefetch")
.string("provide").describe("provide")
.boolean("labeled-modules").describe("labeled-modules")
.string("plugin").describe("plugin")
.boolean("bail").describe("bail")
.boolean("profile").describe("profile")
.boolean("d").describe("d", "shortcut for --debug --devtool sourcemap --output-pathinfo")
.boolean("p").describe("p", "shortcut for --optimize-minimize");
};

View File

@ -28,25 +28,25 @@ module.exports = function(optimist, argv, convertOptions) {
var configFileLoaded = false;
var configPath, ext;
var extensions = Object.keys(interpret.extensions).sort(function(a, b){
var extensions = Object.keys(interpret.extensions).sort(function(a, b) {
return a.length - b.length;
});
if (argv.config) {
if(argv.config) {
configPath = path.resolve(argv.config);
for (var i = extensions.length - 1; i >= 0; i--) {
for(var i = extensions.length - 1; i >= 0; i--) {
var tmpExt = extensions[i];
if (configPath.indexOf(tmpExt, configPath.length - tmpExt.length) > -1){
if(configPath.indexOf(tmpExt, configPath.length - tmpExt.length) > -1) {
ext = tmpExt;
break;
}
};
if (!ext) {
}
if(!ext) {
ext = path.extname(configPath);
}
} else {
for(var i = 0; i < extensions.length; i++) {
var webpackConfig = path.resolve('webpack.config' + extensions[i]);
var webpackConfig = path.resolve("webpack.config" + extensions[i]);
if(fs.existsSync(webpackConfig)) {
ext = extensions[i];
configPath = webpackConfig;
@ -58,8 +58,8 @@ module.exports = function(optimist, argv, convertOptions) {
if(configPath) {
function registerCompiler(moduleDescriptor) {
if (moduleDescriptor) {
if(typeof(moduleDescriptor) == "string") {
if(moduleDescriptor) {
if(typeof moduleDescriptor === "string") {
require(moduleDescriptor);
} else if(!Array.isArray(moduleDescriptor)) {
moduleDescriptor.register(require(moduleDescriptor.module));
@ -103,7 +103,7 @@ module.exports = function(optimist, argv, convertOptions) {
options.context = process.cwd();
}
if(argv["watch"]) {
if(argv.watch) {
// TODO remove this in next major version
if(options.watch && typeof options.watch === "object") {
console.warn("options.watch is deprecated: Use 'options.watchOptions' instead");
@ -198,6 +198,19 @@ module.exports = function(optimist, argv, convertOptions) {
}
function loadPlugin(name) {
var loadUtils = require("loader-utils");
var args = null;
try {
var p = name && name.indexOf("?");
if(p > -1) {
args = loadUtils.parseQuery(name.substring(p));
name = name.substring(0, p);
}
} catch(e) {
console.log("Invalid plugin arguments " + name + " (" + e + ").");
process.exit(-1);
}
var path;
try {
path = resolve.sync(process.cwd(), name);
@ -213,7 +226,7 @@ module.exports = function(optimist, argv, convertOptions) {
throw e;
}
try {
return new Plugin();
return new Plugin(args);
} catch(e) {
console.log("Cannot instantiate plugin " + name + ". (" + path + ")");
throw e;
@ -353,7 +366,8 @@ module.exports = function(optimist, argv, convertOptions) {
ifBooleanArg("progress", function() {
var ProgressPlugin = require("../lib/ProgressPlugin");
ensureArray(options, "plugins");
var chars = 0, lastState, lastStateTime;
var chars = 0,
lastState, lastStateTime;
options.plugins.push(new ProgressPlugin(function(percentage, msg) {
var state = msg;
if(percentage < 1) {
@ -386,6 +400,7 @@ module.exports = function(optimist, argv, convertOptions) {
goToLineStart(msg);
process.stderr.write(msg);
}));
function goToLineStart(nextMessage) {
var str = "";
for(; chars > nextMessage.length; chars--) {
@ -503,6 +518,7 @@ module.exports = function(optimist, argv, convertOptions) {
};
}
ensureObject(options, "entry");
function addTo(name, entry) {
if(options.entry[name]) {
if(!Array.isArray(options.entry[name])) {

View File

@ -14,41 +14,26 @@ try {
} catch(e) {}
var optimist = require("optimist")
.usage("webpack " + require("../package.json").version + "\n" +
"Usage: http://webpack.github.io/docs/cli.html");
"Usage: https://webpack.github.io/docs/cli.html");
require("./config-optimist")(optimist);
optimist
.boolean("json").alias("json", "j").describe("json")
.boolean("colors").alias("colors", "c").describe("colors")
.string("sort-modules-by").describe("sort-modules-by")
.string("sort-chunks-by").describe("sort-chunks-by")
.string("sort-assets-by").describe("sort-assets-by")
.boolean("hide-modules").describe("hide-modules")
.string("display-exclude").describe("display-exclude")
.boolean("display-modules").describe("display-modules")
.boolean("display-chunks").describe("display-chunks")
.boolean("display-error-details").describe("display-error-details")
.boolean("display-origins").describe("display-origins")
.boolean("display-cached").describe("display-cached")
.boolean("display-cached-assets").describe("display-cached-assets")
.boolean("display-reasons").alias("display-reasons", "verbose").alias("display-reasons", "v").describe("display-reasons");
var argv = optimist.argv;
var options = require("./convert-argv")(optimist, argv);
@ -155,6 +140,7 @@ var webpack = require("../lib/webpack.js");
Error.stackTraceLimit = 30;
var lastHash = null;
var compiler = webpack(options);
function compilerCallback(err, stats) {
if(!options.watch) {
// Do not keep cache anymore

View File

@ -12,6 +12,6 @@ MovedToPluginWarningPlugin.prototype.apply = function(compiler) {
var optionName = this.optionName;
var pluginName = this.pluginName;
compiler.plugin("compilation", function(compilation) {
compilation.warnings.push(new Error("webpack options:\nDEPRECATED option '" + optionName + "' will be moved to the " + pluginName + ". Use this instead.\nFor more info about the usage of the " + pluginName + " see http://webpack.github.io/docs/list-of-plugins.html"));
compilation.warnings.push(new Error("webpack options:\nDEPRECATED option '" + optionName + "' will be moved to the " + pluginName + ". Use this instead.\nFor more info about the usage of the " + pluginName + " see https://webpack.github.io/docs/list-of-plugins.html"));
});
};

View File

@ -4,7 +4,7 @@
*/
function AggressiveMergingPlugin(options) {
if(options !== undefined && typeof options !== "object" || Array.isArray(options)) {
throw new Error("Argument should be an options object. To use defaults, pass in nothing.\nFor more info on options, see http://webpack.github.io/docs/list-of-plugins.html");
throw new Error("Argument should be an options object. To use defaults, pass in nothing.\nFor more info on options, see https://webpack.github.io/docs/list-of-plugins.html");
}
this.options = options || {};
}

View File

@ -4,7 +4,7 @@
*/
function LimitChunkCountPlugin(options) {
if(options !== undefined && typeof options !== "object" || Array.isArray(options)) {
throw new Error("Argument should be an options object.\nFor more info on options, see http://webpack.github.io/docs/list-of-plugins.html");
throw new Error("Argument should be an options object.\nFor more info on options, see https://webpack.github.io/docs/list-of-plugins.html");
}
this.options = options || {};
}

View File

@ -4,7 +4,7 @@
*/
function MinChunkSizePlugin(options) {
if(typeof options !== "object" || Array.isArray(options)) {
throw new Error("Argument should be an options object.\nFor more info on options, see http://webpack.github.io/docs/list-of-plugins.html");
throw new Error("Argument should be an options object.\nFor more info on options, see https://webpack.github.io/docs/list-of-plugins.html");
}
this.options = options;
}

View File

@ -4,7 +4,7 @@
*/
function OccurrenceOrderPlugin(preferEntry) {
if(preferEntry !== undefined && typeof preferEntry !== "boolean") {
throw new Error("Argument should be a boolean.\nFor more info on this plugin, see http://webpack.github.io/docs/list-of-plugins.html");
throw new Error("Argument should be a boolean.\nFor more info on this plugin, see https://webpack.github.io/docs/list-of-plugins.html");
}
this.preferEntry = preferEntry;
}

View File

@ -28,8 +28,8 @@
"component-webpack-plugin": "~0.2.0",
"coveralls": "^2.11.2",
"css-loader": "~0.15.0",
"diff": "^1.4.0",
"eslint": "^0.24.0",
"diff": "^2.0.2",
"eslint": "^1.1.0",
"eslint-plugin-nodeca": "^1.0.3",
"express": "~4.13.1",
"extract-text-webpack-plugin": "~0.8.0",
@ -41,7 +41,7 @@
"js-beautify": "^1.5.10",
"json-loader": "~0.5.1",
"less-loader": "^2.0.0",
"microtime": "^1.2.0",
"loader-utils": "^0.2.11",
"mocha": "~2.2.0",
"mocha-lcov-reporter": "0.0.2",
"raw-loader": "~0.5.0",
@ -59,9 +59,9 @@
},
"repository": {
"type": "git",
"url": "http://github.com/webpack/webpack.git"
"url": "https://github.com/webpack/webpack.git"
},
"homepage": "http://github.com/webpack/webpack",
"homepage": "https://github.com/webpack/webpack",
"main": "lib/webpack.js",
"web": "lib/webpack.web.js",
"bin": "./bin/webpack.js",
@ -76,7 +76,7 @@
"pretest": "npm run lint && npm run beautify-lint",
"test": "mocha --full-trace --check-leaks",
"travis": "npm run cover -- --report lcovonly",
"lint": "eslint lib",
"lint": "eslint lib bin hot scripts",
"beautify-lint": "node ./scripts/beautify-check",
"beautify": "node ./scripts/beautify-rewrite",
"precover": "npm run lint && npm run beautify-lint",

View File

@ -1,3 +1,3 @@
exports.beautify = {
files: "{{lib,hot,scripts}/**/*.js,benchmark/*.js}"
files: "{{lib,hot,scripts,bin}/**/*.js,{benchmark,test}/*.js}"
};

View File

@ -45,29 +45,33 @@ describe("ConfigTestCases", function() {
if(checkArrayExpectation(testDirectory, jsonStats, "error", "Error", done)) return;
if(checkArrayExpectation(testDirectory, jsonStats, "warning", "Warning", done)) return;
var exportedTests = 0;
function _it(title, fn) {
var test = new Test(title, fn);
suite.addTest(test);
exportedTests++;
return test;
}
function _require(module) {
if(module.substr(0, 2) === "./") {
var p = path.join(outputDirectory, module);
var fn;
if (options.target === "web") {
if(options.target === "web") {
fn = vm.runInNewContext("(function(require, module, exports, __dirname, __filename, it) {" + fs.readFileSync(p, "utf-8") + "\n})", {}, p);
} else {
fn = vm.runInThisContext("(function(require, module, exports, __dirname, __filename, it) {" + fs.readFileSync(p, "utf-8") + "\n})", p);
}
var module = { exports: {} };
var module = {
exports: {}
};
fn.call(module.exports, _require, module, module.exports, outputDirectory, p, _it);
return module.exports;
} else return require(module);
}
var filesCount = 0;
var testConfig = {
findBundle: function (i, options) {
findBundle: function(i, options) {
if(fs.existsSync(path.join(options.output.path, "bundle" + i + ".js"))) {
return "./bundle" + i + ".js";
}
@ -79,7 +83,7 @@ describe("ConfigTestCases", function() {
} catch(e) {}
for(var i = 0; i < optionsArr.length; i++) {
var bundlePath = testConfig.findBundle(i, optionsArr[i]);
if (bundlePath) {
if(bundlePath) {
filesCount++;
_require(bundlePath);
}

View File

@ -21,6 +21,7 @@ describe("Errors", function() {
};
return files;
}
function getErrors(options, callback) {
options.context = base;
var c = webpack(options);
@ -28,7 +29,9 @@ describe("Errors", function() {
c.run(function(err, stats) {
if(err) throw err;
should.strictEqual(typeof stats, "object");
stats = stats.toJson({ errorDetails: false });
stats = stats.toJson({
errorDetails: false
});
should.strictEqual(typeof stats, "object");
stats.should.have.property("errors");
stats.should.have.property("warnings");

View File

@ -22,6 +22,7 @@ describe("Examples", function() {
options.forEach(processOptions);
else
processOptions(options);
function processOptions(options) {
options.context = examplePath;
options.optimize = options.optimize || {};
@ -36,7 +37,9 @@ describe("Examples", function() {
}
webpack(options, function(err, stats) {
if(err) return done(err);
stats = stats.toJson({ errorDetails: true });
stats = stats.toJson({
errorDetails: true
});
if(stats.errors.length > 0) {
return done(new Error(stats.errors[0]));
}
@ -44,4 +47,4 @@ describe("Examples", function() {
});
});
});
});
});

View File

@ -10,8 +10,12 @@ describe("HotModuleReplacementPlugin", function() {
var statsFile1 = path.join(__dirname, "js", "HotModuleReplacementPlugin.test.stats1.txt");
var statsFile2 = path.join(__dirname, "js", "HotModuleReplacementPlugin.test.stats2.txt");
var recordsFile = path.join(__dirname, "js", "records.json");
try { fs.mkdirSync(path.join(__dirname, "js")); } catch(e) {}
try { fs.unlinkSync(recordsFile); } catch(e) {}
try {
fs.mkdirSync(path.join(__dirname, "js"));
} catch(e) {}
try {
fs.unlinkSync(recordsFile);
} catch(e) {}
var compiler = webpack({
cache: false,
entry: entryFile,
@ -65,4 +69,4 @@ describe("HotModuleReplacementPlugin", function() {
});
});
});
});
});

View File

@ -36,12 +36,10 @@ describe("Integration", function() {
},
bail: true,
module: {
postLoaders: [
{
test: /extra2\.js/,
loader: "raw!extra!val?cacheable"
}
]
postLoaders: [{
test: /extra2\.js/,
loader: "raw!extra!val?cacheable"
}]
},
amd: {
fromOptions: true
@ -49,21 +47,29 @@ describe("Integration", function() {
resolve: {
// cannot resolve should outside the outermost node_modules
// so it is injected here
alias: { should: require.resolve("should") }
alias: {
should: require.resolve("should")
}
},
plugins: [
new webpack.optimize.LimitChunkCountPlugin({maxChunks: 1}),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1
}),
new webpack.DefinePlugin({
"typeof CONST_TYPEOF": JSON.stringify("typeof"),
CONST_TRUE: true,
CONST_FALSE: false,
CONST_FUNCTION: function() { return "ok"; },
CONST_FUNCTION: function() {
return "ok";
},
CONST_NUMBER: 123,
CONST_NUMBER_EXPR: "1*100+23",
CONST_OBJECT: {
A: 1,
B: JSON.stringify("B"),
C: function() { return "C"; }
C: function() {
return "C";
}
}
}),
function() {
@ -84,4 +90,4 @@ describe("Integration", function() {
done();
});
});
});
});

View File

@ -30,7 +30,9 @@ describe("NodeTemplatePlugin", function() {
result.loadChunk(456, function(chunk) {
chunk.should.be.eql(123);
result.loadChunk(567, function(chunk) {
chunk.should.be.eql({a: 1});
chunk.should.be.eql({
a: 1
});
done();
});
});
@ -50,7 +52,9 @@ describe("NodeTemplatePlugin", function() {
},
entry: "./entry",
plugins: [
new webpack.optimize.LimitChunkCountPlugin({maxChunks: 1}),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1
}),
new webpack.optimize.UglifyJsPlugin()
]
}, function(err, stats) {
@ -64,7 +68,9 @@ describe("NodeTemplatePlugin", function() {
chunk.should.be.eql(123);
sameTick.should.be.eql(true);
result.loadChunk(567, function(chunk) {
chunk.should.be.eql({a: 1});
chunk.should.be.eql({
a: 1
});
done();
});
});

View File

@ -22,7 +22,9 @@ describe("NodeWatchFileSystem", function() {
it("should register a file change (change delayed)", function(done) {
var startTime = new Date().getTime();
var wfs = new NodeWatchFileSystem();
var watcher = wfs.watch([fileDirect], [], [], startTime, { aggregateTimeout: 1000 }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps /*, dirTimestamps */) {
var watcher = wfs.watch([fileDirect], [], [], startTime, {
aggregateTimeout: 1000
}, function(err, filesModified, dirsModified, missingCreated, fileTimestamps /*, dirTimestamps */ ) {
if(err) throw err;
filesModified.should.be.eql([fileDirect]);
dirsModified.should.be.eql([]);
@ -39,7 +41,9 @@ describe("NodeWatchFileSystem", function() {
var startTime = new Date().getTime();
setTimeout(function() {
var wfs = new NodeWatchFileSystem();
var watcher = wfs.watch([fileDirect], [], [], startTime, { aggregateTimeout: 1000 }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps /*, dirTimestamps */) {
var watcher = wfs.watch([fileDirect], [], [], startTime, {
aggregateTimeout: 1000
}, function(err, filesModified, dirsModified, missingCreated, fileTimestamps /*, dirTimestamps */ ) {
if(err) throw err;
filesModified.should.be.eql([fileDirect]);
dirsModified.should.be.eql([]);
@ -54,7 +58,9 @@ describe("NodeWatchFileSystem", function() {
it("should register a context change (change delayed)", function(done) {
var startTime = new Date().getTime();
var wfs = new NodeWatchFileSystem();
var watcher = wfs.watch([], [fixtures], [], startTime, { aggregateTimeout: 1000 }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) {
var watcher = wfs.watch([], [fixtures], [], startTime, {
aggregateTimeout: 1000
}, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) {
if(err) throw err;
filesModified.should.be.eql([]);
dirsModified.should.be.eql([fixtures]);
@ -71,7 +77,9 @@ describe("NodeWatchFileSystem", function() {
var startTime = new Date().getTime();
setTimeout(function() {
var wfs = new NodeWatchFileSystem();
var watcher = wfs.watch([], [fixtures], [], startTime, { aggregateTimeout: 1000 }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) {
var watcher = wfs.watch([], [fixtures], [], startTime, {
aggregateTimeout: 1000
}, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) {
if(err) throw err;
filesModified.should.be.eql([]);
dirsModified.should.be.eql([fixtures]);
@ -86,7 +94,9 @@ describe("NodeWatchFileSystem", function() {
it("should register a context change (change delayed, subdirectory)", function(done) {
var startTime = new Date().getTime();
var wfs = new NodeWatchFileSystem();
var watcher = wfs.watch([], [fixtures], [], startTime, { aggregateTimeout: 1000 }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) {
var watcher = wfs.watch([], [fixtures], [], startTime, {
aggregateTimeout: 1000
}, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) {
if(err) throw err;
filesModified.should.be.eql([]);
dirsModified.should.be.eql([fixtures]);
@ -103,7 +113,9 @@ describe("NodeWatchFileSystem", function() {
var startTime = new Date().getTime();
setTimeout(function() {
var wfs = new NodeWatchFileSystem();
var watcher = wfs.watch([], [fixtures], [], startTime, { aggregateTimeout: 1000 }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) {
var watcher = wfs.watch([], [fixtures], [], startTime, {
aggregateTimeout: 1000
}, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) {
if(err) throw err;
filesModified.should.be.eql([]);
dirsModified.should.be.eql([fixtures]);
@ -119,7 +131,9 @@ describe("NodeWatchFileSystem", function() {
var startTime = new Date().getTime();
setTimeout(function() {
var wfs = new NodeWatchFileSystem();
var watcher = wfs.watch([fileDirect, fileSubdir], [fixtures], [], startTime, { aggregateTimeout: 1000 }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) {
var watcher = wfs.watch([fileDirect, fileSubdir], [fixtures], [], startTime, {
aggregateTimeout: 1000
}, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) {
if(err) throw err;
filesModified.should.be.eql([fileSubdir, fileDirect]);
dirsModified.should.be.eql([fixtures]);
@ -136,17 +150,19 @@ describe("NodeWatchFileSystem", function() {
});
it("should sum up multiple changes", function(done) {
var startTime = new Date().getTime();
var wfs = new NodeWatchFileSystem();
var watcher = wfs.watch([fileDirect, fileSubdir], [fixtures], [], startTime, { aggregateTimeout: 1000 }, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) {
if(err) throw err;
filesModified.should.be.eql([fileSubdir, fileDirect]);
dirsModified.should.be.eql([fixtures]);
fileTimestamps.should.have.property(fileDirect).have.type("number");
fileTimestamps.should.have.property(fileSubdir).have.type("number");
dirTimestamps.should.have.property(fixtures).have.type("number");
watcher.close();
done();
});
var wfs = new NodeWatchFileSystem();
var watcher = wfs.watch([fileDirect, fileSubdir], [fixtures], [], startTime, {
aggregateTimeout: 1000
}, function(err, filesModified, dirsModified, missingCreated, fileTimestamps, dirTimestamps) {
if(err) throw err;
filesModified.should.be.eql([fileSubdir, fileDirect]);
dirsModified.should.be.eql([fixtures]);
fileTimestamps.should.have.property(fileDirect).have.type("number");
fileTimestamps.should.have.property(fileSubdir).have.type("number");
dirTimestamps.should.have.property(fixtures).have.type("number");
watcher.close();
done();
});
setTimeout(function() {
fs.writeFile(fileDirect, "", function() {});

View File

@ -8,40 +8,35 @@ describe("Parser", function() {
"call ident": [
function() {
abc("test");
},
{
}, {
abc: ["test"]
}
],
"call member": [
function() {
cde.abc("membertest");
},
{
}, {
cdeabc: ["membertest"]
}
],
"call inner member": [
function() {
cde.ddd.abc("inner");
},
{
}, {
cdedddabc: ["inner"]
}
],
"expression": [
function() {
fgh;
},
{
}, {
fgh: [""]
}
],
"expression sub": [
function() {
fgh.sub;
},
{
}, {
fghsub: ["notry"]
}
],
@ -49,8 +44,7 @@ describe("Parser", function() {
function() {
test[memberExpr]
test[+memberExpr]
},
{
}, {
expressions: ["memberExpr", "memberExpr"]
}
],
@ -63,8 +57,7 @@ describe("Parser", function() {
fgh;
fgh.sub;
})();
},
{}
}, {}
],
"var definition": [
function() {
@ -74,27 +67,28 @@ describe("Parser", function() {
cde.ddd.abc("test");
fgh;
fgh.sub;
},
{}
}, {}
],
"function definition": [
function() {
function abc() {}
function cde() {}
function fgh() {}
abc("test");
cde.abc("test");
cde.ddd.abc("test");
fgh;
fgh.sub;
},
{}
}, {}
],
"in try": [
function() {
try {
fgh.sub;
fgh;
function test(ttt) {
fgh.sub;
fgh;
@ -103,8 +97,7 @@ describe("Parser", function() {
fgh.sub;
fgh;
}
},
{
}, {
fghsub: ["try", "notry", "notry"],
fgh: ["", "test ttt", "test e"]
}
@ -113,8 +106,7 @@ describe("Parser", function() {
function() {
var xyz = abc;
xyz("test");
},
{
}, {
abc: ["test"]
}
],
@ -123,28 +115,25 @@ describe("Parser", function() {
var xyz;
xyz = abc;
xyz("test");
},
{
}, {
abc: ["test"]
}
],
"renaming with IIFE": [
function() {
!function(xyz) {
! function(xyz) {
xyz("test");
}(abc);
},
{
}, {
abc: ["test"]
}
],
"renaming with IIFE (called)": [
function() {
!function(xyz) {
! function(xyz) {
xyz("test");
}.call(fgh, abc);
},
{
}, {
abc: ["test"],
fgh: [""]
}
@ -266,11 +255,11 @@ describe("Parser", function() {
return result.join(" ");
}
}
it("should eval " + key, function() {
var evalExpr = evaluateInParser(key);
evalExprToString(evalExpr).should.be.eql(testCases[key] ? key + " " + testCases[key] : key);
});
});
});
});
});

View File

@ -47,26 +47,28 @@ describe("Stats", function() {
c.apply(new webpack.optimize.OccurrenceOrderPlugin());
c.run(function(err, stats) {
if(err) return done(err);
if(/error$/.test(testName)) {
stats.compilation.errors.length.should.be.above(0);
} else {
stats.compilation.errors.length.should.equal(0);
}
var toStringOptions = { colors: false };
var toStringOptions = {
colors: false
};
if(typeof options.stats !== "undefined") {
toStringOptions = options.stats;
}
var actual = stats.toString(toStringOptions);
(typeof actual).should.be.eql("string");
actual =
actual =
actual.replace(/\u001b\[[0-9;]*m/g, "")
.replace(/Version:.+\n/, "")
.replace(/[0-9]+(\s?ms)/g, "X$1")
.replace(/\r/g, "")
.replace(path.join(base, testName), "Xdir/" + testName);
.replace(/Version:.+\n/, "")
.replace(/[0-9]+(\s?ms)/g, "X$1")
.replace(/\r/g, "")
.replace(path.join(base, testName), "Xdir/" + testName);
var expected = fs.readFileSync(path.join(base, testName, "expected.txt"), "utf-8").replace(/\r/g, "");
if(actual !== expected) {
fs.writeFileSync(path.join(base, testName, "actual.txt"), actual, "utf-8");
@ -78,45 +80,59 @@ describe("Stats", function() {
});
});
});
describe("Error Handling", function(){
describe("does have", function(){
describe("Error Handling", function() {
describe("does have", function() {
it("hasErrors", function() {
var mockStats = new Stats({errors:['firstError'],hash:'1234'});
var mockStats = new Stats({
errors: ['firstError'],
hash: '1234'
});
mockStats.hasErrors().should.be.ok;
});
it("hasWarnings", function() {
var mockStats = new Stats({warnings:['firstError'],hash:'1234'});
var mockStats = new Stats({
warnings: ['firstError'],
hash: '1234'
});
mockStats.hasWarnings().should.be.ok;
});
});
describe("does not have", function(){
describe("does not have", function() {
it("hasErrors", function() {
var mockStats = new Stats({errors:[],hash:'1234'});
var mockStats = new Stats({
errors: [],
hash: '1234'
});
mockStats.hasErrors().should.not.be.ok;
});
it("hasWarnings", function() {
var mockStats = new Stats({warnings:[],hash:'1234'});
var mockStats = new Stats({
warnings: [],
hash: '1234'
});
mockStats.hasWarnings().should.not.be.ok;
});
});
it("formatError handles string errors", function(){
it("formatError handles string errors", function() {
var mockStats = new Stats({
errors:['firstError'],
warnings:[],
assets:[],
chunks:[],
modules:[],
children:[],
hash:'1234',
mainTemplate:{
getPublicPath:function(){return 'path';}
errors: ['firstError'],
warnings: [],
assets: [],
chunks: [],
modules: [],
children: [],
hash: '1234',
mainTemplate: {
getPublicPath: function() {
return 'path';
}
}
});
var obj = mockStats.toJson();
obj.errors[0].should.be.equal('firstError');
});
});
describe("Presets", function(){
describe("Presets", function() {
describe("presetToOptions", function() {
it("returns correct object with 'Normal'", function() {
Stats.presetToOptions("Normal").should.eql({
@ -136,7 +152,7 @@ describe("Stats", function() {
Stats.presetToOptions("pizza").should.eql(normalOpts);
Stats.presetToOptions(true).should.eql(normalOpts);
Stats.presetToOptions(1).should.eql(normalOpts);
Stats.presetToOptions("verbose").should.not.eql(normalOpts);
Stats.presetToOptions(false).should.not.eql(normalOpts);
});

View File

@ -4,7 +4,7 @@ var path = require("path");
var template = require("../lib/Template");
describe("Template", function() {
it("should generate valid identifiers", function() {
template.toIdentifier("0abc-def9").should.equal("_abc_def9");
});
it("should generate valid identifiers", function() {
template.toIdentifier("0abc-def9").should.equal("_abc_def9");
});
});

View File

@ -18,56 +18,92 @@ describe("TestCases", function() {
})
};
});
[
{ name: "normal" },
{ name: "hot", plugins: [
[{
name: "normal"
}, {
name: "hot",
plugins: [
new webpack.HotModuleReplacementPlugin()
]},
{ name: "hot-multi-step", plugins: [
]
}, {
name: "hot-multi-step",
plugins: [
new webpack.HotModuleReplacementPlugin({
multiStep: true
})
]},
{ name: "devtool-eval", devtool: "eval" },
{ name: "devtool-eval-named-modules", devtool: "eval", plugins: [
]
}, {
name: "devtool-eval",
devtool: "eval"
}, {
name: "devtool-eval-named-modules",
devtool: "eval",
plugins: [
new webpack.NamedModulesPlugin()
]},
{ name: "devtool-eval-source-map", devtool: "#eval-source-map" },
{ name: "devtool-inline-source-map", devtool: "inline-source-map" },
{ name: "devtool-source-map", devtool: "#@source-map" },
{ name: "devtool-cheap-inline-source-map", devtool: "cheap-inline-source-map" },
{ name: "devtool-cheap-eval-source-map", devtool: "cheap-eval-source-map" },
{ name: "devtool-cheap-eval-module-source-map", devtool: "cheap-eval-module-source-map" },
{ name: "devtool-cheap-source-map", devtool: "cheap-source-map" },
{ name: "minimized", plugins: [
]
}, {
name: "devtool-eval-source-map",
devtool: "#eval-source-map"
}, {
name: "devtool-inline-source-map",
devtool: "inline-source-map"
}, {
name: "devtool-source-map",
devtool: "#@source-map"
}, {
name: "devtool-cheap-inline-source-map",
devtool: "cheap-inline-source-map"
}, {
name: "devtool-cheap-eval-source-map",
devtool: "cheap-eval-source-map"
}, {
name: "devtool-cheap-eval-module-source-map",
devtool: "cheap-eval-module-source-map"
}, {
name: "devtool-cheap-source-map",
devtool: "cheap-source-map"
}, {
name: "minimized",
plugins: [
new webpack.optimize.UglifyJsPlugin({
sourceMap: false
})
]},
{ name: "minimized-source-map", plugins: [
]
}, {
name: "minimized-source-map",
plugins: [
new webpack.optimize.UglifyJsPlugin()
]},
{ name: "deduped", plugins: [
]
}, {
name: "deduped",
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.NamedModulesPlugin()
]},
{ name: "minimized-deduped", plugins: [
]
}, {
name: "minimized-deduped",
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin()
]},
{ name: "optimized", plugins: [
]
}, {
name: "optimized",
plugins: [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin()
]},
{ name: "all-combined", devtool: "#@source-map", plugins: [
]
}, {
name: "all-combined",
devtool: "#@source-map",
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.NamedModulesPlugin()
]}
].forEach(function(config) {
]
}].forEach(function(config) {
describe(config.name, function() {
categories.forEach(function(category) {
describe(category.name, function() {
@ -80,7 +116,7 @@ describe("TestCases", function() {
var outputDirectory = path.join(__dirname, "js", config.name, category.name, testName);
var options = {
context: casesPath,
entry: "./" + category.name + "/" + testName +"/index",
entry: "./" + category.name + "/" + testName + "/index",
target: "async-node",
devtool: config.devtool,
output: {
@ -100,11 +136,16 @@ describe("TestCases", function() {
extensions: ["", ".webpack-loader.js", ".web-loader.js", ".loader.js", ".js"]
},
module: {
loaders: [
{ test: /\.json$/, loader: "json" },
{ test: /\.coffee$/, loader: "coffee" },
{ test: /\.jade$/, loader: "jade" }
]
loaders: [{
test: /\.json$/,
loader: "json"
}, {
test: /\.coffee$/,
loader: "coffee"
}, {
test: /\.jade$/,
loader: "jade"
}]
},
plugins: (config.plugins || []).concat(
new webpack.dependencies.LabeledModulesPlugin()
@ -118,17 +159,21 @@ describe("TestCases", function() {
if(checkArrayExpectation(testDirectory, jsonStats, "error", "Error", done)) return;
if(checkArrayExpectation(testDirectory, jsonStats, "warning", "Warning", done)) return;
var exportedTest = 0;
function _it(title, fn) {
var test = new Test(title, fn);
suite.addTest(test);
exportedTest++;
return test;
}
function _require(module) {
if(module.substr(0, 2) === "./") {
var p = path.join(outputDirectory, module);
var fn = vm.runInThisContext("(function(require, module, exports, __dirname, it) {" + fs.readFileSync(p, "utf-8") + "\n})", p);
var module = { exports: {} };
var module = {
exports: {}
};
fn.call(module.exports, _require, module, module.exports, outputDirectory, _it);
return module.exports;
} else return require(module);

View File

@ -2,9 +2,11 @@ var fs = require("fs");
var path = require("path");
module.exports = function checkArrayExpectation(testDirectory, object, kind, upperCaseKind, done) {
var array = object[kind+"s"].slice().sort();
if(kind === "warning") array = array.filter(function(item) { return !/from UglifyJs/.test(item); });
if(fs.existsSync(path.join(testDirectory, kind+ "s.js"))) {
var array = object[kind + "s"].slice().sort();
if(kind === "warning") array = array.filter(function(item) {
return !/from UglifyJs/.test(item);
});
if(fs.existsSync(path.join(testDirectory, kind + "s.js"))) {
var expected = require(path.join(testDirectory, kind + "s.js"));
if(expected.length < array.length)
return done(new Error("More " + kind + "s while compiling than expected:\n\n" + array.join("\n\n"))), true;