webpack/README.md

987 lines
26 KiB
Markdown
Raw Normal View History

2012-08-07 05:09:38 +08:00
# webpack
2012-03-10 20:11:23 +08:00
As developer you want to reuse existing code.
As with node.js and web all files are already in the same language, but it is extra work to use your code with the node.js module system and the browser.
2012-04-03 22:26:08 +08:00
The goal of `webpack` is to bundle CommonJs (and AMD) modules into javascript files which can be loaded by `<script>`-tags.
2012-05-01 12:14:17 +08:00
Simply concatenating all required files has a disadvantage: many code to download (and execute) on page load.
2012-03-11 20:44:38 +08:00
Therefore `webpack` uses the `require.ensure` function ([CommonJs/Modules/Async/A](http://wiki.commonjs.org/wiki/Modules/Async/A)) to split your code automatically into multiple bundles which are loaded on demand.
This happens mostly transparent to the developer.
Dependencies are resolved for you.
2012-05-01 12:14:17 +08:00
The result is a smaller initial code download which results in faster page load.
2012-03-10 20:11:23 +08:00
Another common thing in web development is that some files have to be preprocessed before send to the client (ex. template files).
This introduce more complexity to the compile step.
`webpack` supports loaders which process files before including them.
You as developer can use such files like any other module.
2012-08-07 05:09:38 +08:00
[![build status](https://secure.travis-ci.org/webpack/webpack.png)](http://travis-ci.org/webpack/webpack)
2012-05-03 06:11:08 +08:00
2012-03-10 20:11:23 +08:00
**TL;DR**
* bundle [CommonJs](/webpack/webpack/tree/master/examples/commonjs/) and/or [AMD](/webpack/webpack/tree/master/examples/mixed/) modules for browser
2012-03-11 20:44:38 +08:00
* reuse server-side code (node.js) on client-side
2012-04-03 22:26:08 +08:00
* create multiple files which are loaded on demand (faster page load in big webapps or on mobile connections)
* dependencies managed for you, on compile time (no resolution on runtime needed)
* loaders can preprocess files
2012-07-04 00:07:41 +08:00
## Quick start guide
``` javascript
var moduleA = require("module/file");
var moduleB = require("./relativeFile");
var moduleC = require("../stuff/cup.coffee");
function getTemplate(name) {
return require("./templates/" + name + ".jade");
}
require("bootstrap/less/bootstrap.less");
```
``` shell
npm install webpack -g
webpack lib/yourEntryModule.js output/bundle.js
2012-07-04 00:07:41 +08:00
```
## Goals
2012-04-03 22:26:08 +08:00
* make node.js and browser development similar
* minimize code size (mobile connection)
2012-05-01 12:14:17 +08:00
* minimize code size on initial download
* download code only on demand
2012-04-03 22:26:08 +08:00
* require minimal configuration, but offer a maximum
* load polyfills for node-specific things if used
2012-05-01 12:14:17 +08:00
* offer replacements for node buildin libraries
* support [npm](https://npmjs.org/) and [jam](http://jamjs.org/)
2012-03-10 20:11:23 +08:00
2012-05-22 01:31:13 +08:00
# Examples
2012-08-07 05:09:38 +08:00
See [example webapp](http://webpack.github.com/example-app/).
2012-08-07 05:09:38 +08:00
More [examples](https://github.com/webpack/webpack/tree/master/examples).
2012-05-22 01:31:13 +08:00
## Simple Example
2012-03-10 20:11:23 +08:00
``` javascript
// a.js
var b = require("./b");
b.stuff("It works");
// b.js
exports.stuff = function(text) {
console.log(text);
}
```
are compiled to (reformatted)
2012-03-10 20:11:23 +08:00
``` javascript
(/* small webpack header */)
({
0: function(module, exports, require) {
var b = require(1);
b.stuff("It works");
},
1: function(module, exports, require) {
exports.stuff = function(text) {
console.log(text)
2012-03-10 20:11:23 +08:00
}
}
})
```
2012-03-11 20:44:38 +08:00
## Code Splitting
### Example
``` javascript
var a = require("a");
var b = require("b");
require.ensure(["c"], function(require) {
require("b").xyz();
var d = require("d");
});
```
```
File 1: web.js
- code of that file
2012-03-11 20:44:38 +08:00
- code of module a and dependencies
- code of module b and dependencies
File 2: 1.web.js
- code of module c and dependencies (but code is not used)
- code of module d and dependencies
```
2012-04-03 22:26:08 +08:00
Initially only `web.js` is included (and loaded) by your application.
`1.web.js` is loaded when the call to `require.ensure` happens.
After the second bundle (`1.web.js`) is loaded, the callback function will be invoked.
2012-08-07 05:09:38 +08:00
See [details](/webpack/webpack/tree/master/examples/code-splitting) for exact output.
2012-04-05 20:59:01 +08:00
2012-08-07 05:09:38 +08:00
See [more examples](/webpack/webpack/tree/master/examples).
2012-03-11 20:44:38 +08:00
## Reusing node.js code
`webpack` was built to support most of the code that was coded for node.js environment.
For example this works out of the box:
* `require("./templates/" + templateName);`
* `require(condition ? "moduleA" : condition2 ? "moduleB" : "./localStuff");`
* `function xyz(require) { require("text"); } xyz(function(a) { console.log(a) });`
* `var r = require; r("./file");` with warning
* `function xyz(require) { require("./file"); } xyz(require);` with warning
* `try { require("missingModule"); } catch(e) { console.log("missing") }` with warning
* `var require = function(a) { console.log(a) }; require("text");`
* `if(condition) require("optionalModule")` with warning if missing
2012-03-10 20:11:23 +08:00
## Browser replacements
Somethings it happens that browsers require other code than node.js do.
`webpack` allow module developers to specify replacements which are used in the compile process of `webpack`.
Modules in `web_modules` and `jam` replace modules in `node_modules`.
2012-03-27 06:34:38 +08:00
`filename.web.js` replaces `filename.js` when required without file extension.
2012-03-10 20:11:23 +08:00
2012-03-21 20:41:47 +08:00
in options: `alias: { "http": "http-browserify" }`
in shell: `--alias http=http-browserify`
2012-03-10 20:11:23 +08:00
## Contexts
2012-03-12 04:37:18 +08:00
2012-03-21 20:41:47 +08:00
If the required module is not known while compile time we get into a problem.
2012-03-12 04:37:18 +08:00
A solution is the method `require.context` which takes a directory as parameter
and returns a function which behaves like the `require` function issued from a file
in this directory (but only if used for files in that directory).
2012-03-21 20:41:47 +08:00
The whole directory is included while compiling, so you have access to all files in it.
2012-03-12 04:37:18 +08:00
### Example
We have a directory full of templates, which are compiled javascript files.
A template should be loaded by template name.
``` javascript
var requireTemplate = require.context("./templates");
function getTemplate(templateName) {
return requireTemplate("./" + templateName);
}
```
In addition to that `webpack` uses the `require.context` function automatically
2012-05-01 12:14:17 +08:00
if you use variables or other not parse-able things in the `require` function.
2012-03-12 04:37:18 +08:00
That means the following code behaves like the above:
``` javascript
function getTemplate(templateName) {
return require("./templates/" + templateName);
}
// is compiled like: return require.context("./templates")("./"+templateName)
2012-03-21 20:41:47 +08:00
// which compiles to: return require(123)("./"+templateName)
2012-03-12 04:37:18 +08:00
```
2012-08-07 05:09:38 +08:00
See [details](/webpack/webpack/tree/master/examples/require.context) for complete example.
2012-03-12 04:37:18 +08:00
When try to store the `require` function in another variable or try to pass it as parameter,
2012-03-21 20:41:47 +08:00
`webpack` convert it to a `require.context(".")` to be compatible.
There is a warning emitted in this case.
2012-03-12 04:37:18 +08:00
*Warning: The complete code in the directory are included. So use it carefully.*
2012-03-27 10:23:11 +08:00
## Loaders
You can use a syntax for loader plugins to preprocess files before emitting javascript code to the bundle.
The following example loads the raw content of a file with the `raw` loader:
``` javascript
var content = require("raw!./file.txt");
```
2012-05-01 12:14:17 +08:00
Multiple loader plugins can be prepended by separating them with `!`.
2012-03-27 10:23:11 +08:00
The loader plugins are resolved like in normal `require` call but with different default extension.
The `raw` loader plugin is looked up at modules `raw-webpack-web-loader`, `raw-webpack-loader`, `raw-web-loader`, `raw-loader`, `raw`
and the following files are looked up: `index.webpack-web-loader.js`, `index.webpack-loader.js`, `index.web-loader.js`, `index.loader.js`, `index`, `index.js`.
Note that the `web-` versions are omitted if loaders are used in node.js.
2012-08-07 05:09:38 +08:00
See [example](/webpack/webpack/tree/master/examples/loader).
2012-03-27 10:23:11 +08:00
The following loaders are included in webpack:
2012-03-27 10:23:11 +08:00
2012-08-07 05:09:38 +08:00
* [`raw`](https://github.com/webpack/raw-loader): Loads raw content of a file (as utf-8)
* [`json`](https://github.com/webpack/json-loader) (default at `.json`): Loads file as JSON
* [`jade`](https://github.com/webpack/jade-loader) (default at `.jade`): Loads jade template and returns a function
* [`coffee`](https://github.com/webpack/coffee-loader) (default at `.coffee`): Loads coffee-script like javascript
* [`css`](https://github.com/webpack/css-loader): Loads css file with resolved imports and returns css code
* [`less`](https://github.com/webpack/less-loader): Loads and compiles a less file and returns css code
* [`val`](https://github.com/webpack/val-loader): Excutes code as module and consider exports as javascript code
* [`bundle`](https://github.com/webpack/bundle-loader): Wraps request in a `require.ensure` block
* [`file`](https://github.com/webpack/file-loader): Emits the file into the output folder and returns the (relative) url (`file/{ext}` for some extensions)
* [`style`](https://github.com/webpack/style-loader): Adds result of javascript execution to DOM
* [`script`](https://github.com/webpack/script-loader): Executes a javascript file once in global context (like in script tag), requires are not parsed. Use this to include a library. ex. `require("script!./jquery.min.js")`. This is synchron, so the `$` variable is available after require.
2012-05-04 22:42:38 +08:00
* (`.css` defaults to `style!css` loader, so all css rules are added to DOM)
2012-05-22 01:31:13 +08:00
* (`.less` defaults to `style!css!val/cacheable!less` loader, so all less rules are added to DOM)
2012-05-04 22:42:38 +08:00
See docs for loader in github repo of the loader.
2012-03-27 10:23:11 +08:00
2012-08-23 10:24:00 +08:00
[Bigger list of loaders](https://github.com/webpack/webpack/wiki/Loaders)
2012-03-27 10:23:11 +08:00
## TL;DR
``` javascript
var a = require("a"); // require modules
var b = require("./b"); // and files
// like in node.js
// polyfill require method to use the new members in node.js too
require = require("enhanced-require")(module);
2012-03-27 10:23:11 +08:00
// create a lazy loaded bundle
require.ensure([], function(require) {
var c = require("c");
// require json
var packageJson = require("../package.json");
// or jade templates, coffee-script, and many more with own loaders
var result = require("./template.jade")(require("./dataFrom.coffee"));
// files are compiled to javascript and packed into the bundle...
});
```
... and compile from the shell with:
```
webpack lib/input.js js/output.js
```
try `--min` to minimize with `uglify-js`.
2012-03-10 20:11:23 +08:00
## Limitations
### `require`-function
2012-04-03 22:26:08 +08:00
* `require` should not be overwritten, except from polyfill
2012-03-12 04:37:18 +08:00
* `require.ensure` should not be overwritten or called indirect
* `require.context` should not be overwritten or called indirect
* the argument to `require.context` should be a literal or addition of multiple literals
* An indirect call of `require` should access a file in current directory: This throws an exception: `var r = require; r("../file");`
2012-03-21 20:41:47 +08:00
The following cases could result in **too much code** in result file if used wrong:
2012-04-03 22:26:08 +08:00
* indirect call of `require`: `var r = require; r("./file");`. It includes the whole directory.
* `require.context`. It includes the whole directory.
2012-04-03 22:26:08 +08:00
* expressions in require arguments: `require(variable)`. It includes the whole directory. (except from `?:`-operator `require(condition ? "a" : "b")`)
* the function passed to `require.ensure` is not inlined in the call. Only requires in inlined function move into the second bundle.
2012-03-10 20:11:23 +08:00
### node.js specific modules
2012-04-03 22:26:08 +08:00
As node.js specific modules like `fs` will not work in browser they are not included (by default) and cause an exception.
2012-03-12 05:16:24 +08:00
You should replace them by own modules if you want to use them.
2012-04-03 22:26:08 +08:00
For some simple modules are replacements included in `webpack`.
2012-03-21 20:41:47 +08:00
Expensive replacements are not needed by everyone, so that are not included by default.
You need to specify `--alias [module]=[replacement]` to use them.
2012-04-03 22:26:08 +08:00
A warning saying that some module is missing is emitted in the case you use it without providing a replacement.
Some credit goes to the browserify contributors, you can use replacements provided by them.
2012-03-10 20:11:23 +08:00
2012-03-27 10:45:48 +08:00
Included simple replacements:
2012-04-05 20:59:01 +08:00
* `assert`: copy of node.js' version, small change
* `buffer`: copy of node-browserify's version
* `buffer_ieee754`: copy of node-browserify's version
2012-03-27 10:45:48 +08:00
* `child_process`: disabled
* `events`: copy of node.js' version
2012-04-05 20:59:01 +08:00
* `path`: copy of node.js' version
* `punycode`: copy of node.js' version, one line removed (http://mths.be/punycode by @mathias)
2012-04-05 20:59:01 +08:00
* `querystring`: copy of node.js' version
* `string_decoder`: copy of node.js' version
* `url`: copy of node.js' version
2012-03-27 10:45:48 +08:00
* `util`: copy of node.js' version
Here is a list of possible useful replacements: (intentionally not by default)
2012-03-10 20:11:23 +08:00
2012-03-21 20:41:47 +08:00
* `http=http-browserify`
* `vm=vm-browserify`
* TODO provide some more replacements
2012-03-10 20:11:23 +08:00
## Usage
### Shell
`webpack` offers a command line interface:
after `npm install webpack -g` you can use the `webpack` command
if invoked without arguments it prints a usage:
```
Usage: webpack <options> <input> <output>
Options:
API: loaderContext.depencency is more relaxed and don't need to be called before reading API: loader.seperable cannot combined with loaderContext.emitFile and loaderContext.emitSubStats loaderContext.options.resolve loaderContext.options.events loaderContext.resolve and .sync API: added profile option (and --profile) API: added workers option (and --workers) API: added closeWorkers option API: if option workers is used: options must be JSON.stringify-able. Except options.resolve and options.events. Any error thrown in loader must be an object (i. e. an Error object). Only message, stack and value of toString is passed to main process. API: The expected Cache object for options.cache has changed. API: event module is emited after the module is finished. API: event context is now named context-enum API: added event context which is emited after the context is finished. API: event dependency is removed. Use stats.dependencies for this. API: event loader is removed. Use stats.loaders for this. API: added stats.contexts as a list of contexts. API: added stats...modules[..].dependencies for as list of files which affect the module's content. API: added stats...modules[..].loaders for as list of loaders which affect the module's content. API: removed stats.modulesPerChunk, it is useless and was deprecated. API: added stats.chunkNameFiles which export the files for named chunks API: added stats.startTime, timestamp as number cmd: more colorful output to indicate caching and timing API: webpack in watch mode emits the event watch-end if watch mode have to end (i. e. loader changed). You may restart it after clearing require.cache. API: added loaderContext.loaderType as one of loader, preLoader or postLoader. API: added loaderContext.currentLoaders as list of all loader of the current type. API: added loaderContext.loaderIndex as index of current loader in loaderContext.currentLoaders. API: added loaderContext.loaders, loaderContext.preLoaders and loaderContext.postLoaders.
2012-09-25 22:45:53 +08:00
--min Minimize it with uglifyjs [boolean] [default: false]
--filenames Output Filenames Into File [boolean] [default: false]
--options Options JSON File [string]
--public-prefix Path Prefix For JavaScript Loading [string]
--libary Stores the exports into this variable [string]
--colors Output Stats with colors [boolean] [default: false]
--single Disable lazy loading [boolean] [default: false]
--json Output Stats as JSON [boolean] [default: false]
--by-size Sort modules by size in Stats [boolean] [default: false]
--verbose Output dependencies in Stats [boolean] [default: false]
--profile Capture timings for modules [boolean] [default: false]
--alias Set a alias name for a module. ex. http=http-browserify [string]
--debug Prints debug info to output files [boolean] [default: false]
--watch Recompiles on changes (except loaders) [boolean] [default: false]
--watch-delay Timeout to wait for the last change
--workers Use worker processes to be faster (BETA) [boolean] [default: false]
--progress Displays a progress while compiling [boolean] [default: false]
2012-03-10 20:11:23 +08:00
```
### Programmatically Usage
2012-03-11 20:44:38 +08:00
``` javascript
webpack(context, moduleName, [options], callback)
webpack(absoluteModulePath, [options], callback)
```
2012-03-10 20:11:23 +08:00
#### `options`
2012-04-03 22:26:08 +08:00
You can also save this options object in a JSON file and use it with the shell command.
2012-03-10 20:11:23 +08:00
2012-05-12 22:43:37 +08:00
``` javascript
{
output: "out/file.js", // required
// output file to initial chunk
outputDirectory: "out/dir", // default: extract directory from output
// output directory for file
outputPostfix: ".chunk.js", // default: "." + output
// postfix appended to id of lazy loaded chunks
2012-07-11 08:15:39 +08:00
context: "/home/node/stuff",
// default: [context] parameter if Programmatically Usage
// default: process.cwd() if Shell Usage
// paths in stats and debug sourceUrl are shortened to this base directory
2012-05-12 22:43:37 +08:00
ouputJsonpFunction: "myJsonp", // default: "webpackJsonp"
// jsonp function used for lazy loaded chunks,
// should be unique for all instances of webpack in a page
publicPrefix: "http://static.url.com/asserts/", // default: ""
// path to create the chunks url relative to page
// deprecated name: scriptSrcPrefix
libary: "mylib", // default: null
// store the exports of the entrace module in a variable of this name
// use this to create a libary from webpack
includeFilenames: true, // default: false
// include the filename of each module as comment before the module
2012-06-30 04:45:48 +08:00
single: false, // default: false
// ignore all Code Splitting and emit only a single file
// all code is included and should work as with Code Splitting
2012-07-06 22:51:58 +08:00
debug: true, // default: false
// put the source of the modules into annotated eval,
// which cause a nice debug experience in some dev tools
2012-05-12 22:43:37 +08:00
watch: true, // default: false
// recompiles on changes on module and contexts (currently not on loaders)
2012-05-22 01:31:13 +08:00
// unchanged files are cached for greater performance
2012-05-12 22:43:37 +08:00
watchDelay: 1000, // default: 200
// delay in ms before recompile after the last file change
events: new EventEmitter(), // default: new EventEmitter()
// EventEmitter on which events for the compile process are fired
// events:
// -- bundling process --
// "bundle" (stats) the bundle is finished
// "bundle-invalid" () fired when the bundle gets invalid
// [bundle-invalid is only fired in watch mode]
// "start-writing" (hash) fired when webpack starts writing
API: loaderContext.depencency is more relaxed and don't need to be called before reading API: loader.seperable cannot combined with loaderContext.emitFile and loaderContext.emitSubStats loaderContext.options.resolve loaderContext.options.events loaderContext.resolve and .sync API: added profile option (and --profile) API: added workers option (and --workers) API: added closeWorkers option API: if option workers is used: options must be JSON.stringify-able. Except options.resolve and options.events. Any error thrown in loader must be an object (i. e. an Error object). Only message, stack and value of toString is passed to main process. API: The expected Cache object for options.cache has changed. API: event module is emited after the module is finished. API: event context is now named context-enum API: added event context which is emited after the context is finished. API: event dependency is removed. Use stats.dependencies for this. API: event loader is removed. Use stats.loaders for this. API: added stats.contexts as a list of contexts. API: added stats...modules[..].dependencies for as list of files which affect the module's content. API: added stats...modules[..].loaders for as list of loaders which affect the module's content. API: removed stats.modulesPerChunk, it is useless and was deprecated. API: added stats.chunkNameFiles which export the files for named chunks API: added stats.startTime, timestamp as number cmd: more colorful output to indicate caching and timing API: webpack in watch mode emits the event watch-end if watch mode have to end (i. e. loader changed). You may restart it after clearing require.cache. API: added loaderContext.loaderType as one of loader, preLoader or postLoader. API: added loaderContext.currentLoaders as list of all loader of the current type. API: added loaderContext.loaderIndex as index of current loader in loaderContext.currentLoaders. API: added loaderContext.loaders, loaderContext.preLoaders and loaderContext.postLoaders.
2012-09-25 22:45:53 +08:00
// "watch-end" () watch ended because of loader change
// -- events for modules --
// "module" (module, filename) after a module is loaded
// "context-enum" (module, dirname) before a context is enumerated
// "context" (module, dirname) after a context is loaded
// -- events for progress --
// "task" (name?) start of a task
// "task-end" (name?) end of a task
noWrite: true, // default: undefined
// if true webpack do not write out any file
2012-05-12 22:43:37 +08:00
parse: {
// options for parsing
overwrites: {
"myglobal": "modulename-of-myglobal"
// defaults: (defaults are also included if you define your own)
// process: "__webpack_process",
// module: "__webpack_module",
// console: "__webpack_console",
// global: "__webpack_global",
// Buffer: "buffer+.Buffer" // -> require("buffer").Buffer
// "__dirname": "__webpack_dirname",
// "__filename": "__webpack_filename"
},
// inject a free variable named "myglobal" which are required as
// require("modulename-of-myglobal")
// to each module which uses "myglobal"
}
resolve: {
// options for resolving
paths: ["/my/absolute/dirname"],
// default: (defaults are also included if you define your own)
// [".../buildin",
// ".../buildin/web_modules", ".../buildin/name_modules",
// ".../node_modules"]
// search paths for modules
modulesDirectorys: ["xyz_modules", "node_modules"],
// default: (defaults are NOT included if you define your own)
// ["web_modules", "jam", "node_modules"];
// directories to be searched for modules
2012-05-12 22:43:37 +08:00
alias: {
"old-module": "new-module"
},
// replace a module
extensions: ["", ".www.js", ".js"],
// defaults: (defaults are NOT included if you define your own)
// ["", ".webpack.js", ".web.js", ".js"]
// postfixes for files to try
loaderExtensions: [".loader.js", ".www-loader.js", "", ".js"],
// defaults: (defaults are NOT included if you define your own)
// [".webpack-web-loader.js", ".webpack-loader.js",
// ".web-loader.js", ".loader.js", "", ".js"]
// postfixes for loaders to try
loaderPostfixes: ["-loader", "-xyz", ""],
// defaults: (defaults are NOT included if you define your own)
// ["-webpack-web-loader", "-webpack-loader",
// "-web-loader", "-loader", ""]
// postfixes for loader modules to try
loaders: [{
test: /\.generator\.js/,
exclude: /\.no\.generator\.js/,
loader: "val"
}],
2012-05-12 22:43:37 +08:00
// default: (defaults are also included if you define your own)
// [{test: /\.coffee$/, loader: "coffee"},
// {test: /\.json$/, loader: "json"},
// {test: /\.jade$/, loader: "jade"},
// {test: /\.css$/, loader: "style!css"},
// {test: /\.less$/, loader: "style!css!val!less"}]
// automatically use loaders if filename match RegExp
// and no loader is specified.
// you can pass a RegExp as string, or multiple RegExps/strings in an array
2012-07-11 02:59:05 +08:00
postprocess: {
normal: [function(filename, callback) {
// webpack will not find files including ".exclude."
2012-07-11 03:01:13 +08:00
if(/\.exclude\.[^\\\/]*$/.test(filename))
2012-07-11 02:59:05 +08:00
return callback(new Error("File is excluded"));
callback(null, filename);
}],
// defaults: []
// postprocess resolved filenames by all specified async functions
// a postprocessor must call the callback
2012-09-26 18:28:23 +08:00
// You must pass a filename instead of a function if you use workers
// The filename is required in the worker process.
2012-07-11 02:59:05 +08:00
context: [],
// same as postprocess.normal but for contextes
}
2012-05-12 22:43:37 +08:00
}
2012-07-11 18:18:31 +08:00
postLoaders: [{test: /\.export.js$/, loader: "export"}],
// default: []
// syntax like resolve.loaders
// all loaders which matches the file are applied after the
// normal loaders. This cannot be overridden in the require call.
2012-09-26 18:28:23 +08:00
// You must pass a string instead of a RegExp if you use workers
2012-07-11 18:18:31 +08:00
preLoaders: [{test: /\.txt$|\.html$/, loader: "normalizeNLs"}],
// default: []
// syntax like resolve.loaders
// all loaders which matches the file are applied before the
// normal loaders. This cannot be overridden in the require call.
2012-09-26 18:28:23 +08:00
// You must pass a string instead of a RegExp if you use workers
API: loaderContext.depencency is more relaxed and don't need to be called before reading API: loader.seperable cannot combined with loaderContext.emitFile and loaderContext.emitSubStats loaderContext.options.resolve loaderContext.options.events loaderContext.resolve and .sync API: added profile option (and --profile) API: added workers option (and --workers) API: added closeWorkers option API: if option workers is used: options must be JSON.stringify-able. Except options.resolve and options.events. Any error thrown in loader must be an object (i. e. an Error object). Only message, stack and value of toString is passed to main process. API: The expected Cache object for options.cache has changed. API: event module is emited after the module is finished. API: event context is now named context-enum API: added event context which is emited after the context is finished. API: event dependency is removed. Use stats.dependencies for this. API: event loader is removed. Use stats.loaders for this. API: added stats.contexts as a list of contexts. API: added stats...modules[..].dependencies for as list of files which affect the module's content. API: added stats...modules[..].loaders for as list of loaders which affect the module's content. API: removed stats.modulesPerChunk, it is useless and was deprecated. API: added stats.chunkNameFiles which export the files for named chunks API: added stats.startTime, timestamp as number cmd: more colorful output to indicate caching and timing API: webpack in watch mode emits the event watch-end if watch mode have to end (i. e. loader changed). You may restart it after clearing require.cache. API: added loaderContext.loaderType as one of loader, preLoader or postLoader. API: added loaderContext.currentLoaders as list of all loader of the current type. API: added loaderContext.loaderIndex as index of current loader in loaderContext.currentLoaders. API: added loaderContext.loaders, loaderContext.preLoaders and loaderContext.postLoaders.
2012-09-25 22:45:53 +08:00
workers: true,
// default: false
// options: true, false, number > 0, object of type webpack/lib/Workers
// Use worker processes to do some work.
// This *can* boost performance, but starting these processes has some
// overhead (~100-200ms). If loaders are used they need to have the
// seperable flag to work in worker process. If they havn't they work in
// the main process.
2012-09-26 01:23:05 +08:00
// Pushing jobs to worker processes has an addititional overhead of ~100ms.
API: loaderContext.depencency is more relaxed and don't need to be called before reading API: loader.seperable cannot combined with loaderContext.emitFile and loaderContext.emitSubStats loaderContext.options.resolve loaderContext.options.events loaderContext.resolve and .sync API: added profile option (and --profile) API: added workers option (and --workers) API: added closeWorkers option API: if option workers is used: options must be JSON.stringify-able. Except options.resolve and options.events. Any error thrown in loader must be an object (i. e. an Error object). Only message, stack and value of toString is passed to main process. API: The expected Cache object for options.cache has changed. API: event module is emited after the module is finished. API: event context is now named context-enum API: added event context which is emited after the context is finished. API: event dependency is removed. Use stats.dependencies for this. API: event loader is removed. Use stats.loaders for this. API: added stats.contexts as a list of contexts. API: added stats...modules[..].dependencies for as list of files which affect the module's content. API: added stats...modules[..].loaders for as list of loaders which affect the module's content. API: removed stats.modulesPerChunk, it is useless and was deprecated. API: added stats.chunkNameFiles which export the files for named chunks API: added stats.startTime, timestamp as number cmd: more colorful output to indicate caching and timing API: webpack in watch mode emits the event watch-end if watch mode have to end (i. e. loader changed). You may restart it after clearing require.cache. API: added loaderContext.loaderType as one of loader, preLoader or postLoader. API: added loaderContext.currentLoaders as list of all loader of the current type. API: added loaderContext.loaderIndex as index of current loader in loaderContext.currentLoaders. API: added loaderContext.loaders, loaderContext.preLoaders and loaderContext.postLoaders.
2012-09-25 22:45:53 +08:00
closeWorkers: false,
// default: true
// close the worker processes on webpack exit.
2012-09-26 18:28:23 +08:00
workersNoResolve: true,
// default: false
// workers should not be used in the resolving process
// This may be useful if you want to have your postprocessors in the main process.
workerMinLoaders: 2,
// default: 0
// only process file in seperate process if more or equal loaders applied to the file.
API: loaderContext.depencency is more relaxed and don't need to be called before reading API: loader.seperable cannot combined with loaderContext.emitFile and loaderContext.emitSubStats loaderContext.options.resolve loaderContext.options.events loaderContext.resolve and .sync API: added profile option (and --profile) API: added workers option (and --workers) API: added closeWorkers option API: if option workers is used: options must be JSON.stringify-able. Except options.resolve and options.events. Any error thrown in loader must be an object (i. e. an Error object). Only message, stack and value of toString is passed to main process. API: The expected Cache object for options.cache has changed. API: event module is emited after the module is finished. API: event context is now named context-enum API: added event context which is emited after the context is finished. API: event dependency is removed. Use stats.dependencies for this. API: event loader is removed. Use stats.loaders for this. API: added stats.contexts as a list of contexts. API: added stats...modules[..].dependencies for as list of files which affect the module's content. API: added stats...modules[..].loaders for as list of loaders which affect the module's content. API: removed stats.modulesPerChunk, it is useless and was deprecated. API: added stats.chunkNameFiles which export the files for named chunks API: added stats.startTime, timestamp as number cmd: more colorful output to indicate caching and timing API: webpack in watch mode emits the event watch-end if watch mode have to end (i. e. loader changed). You may restart it after clearing require.cache. API: added loaderContext.loaderType as one of loader, preLoader or postLoader. API: added loaderContext.currentLoaders as list of all loader of the current type. API: added loaderContext.loaderIndex as index of current loader in loaderContext.currentLoaders. API: added loaderContext.loaders, loaderContext.preLoaders and loaderContext.postLoaders.
2012-09-25 22:45:53 +08:00
profile: true,
// default: false
// capture timings for the build.
// they are stored in the stats
2012-05-12 22:43:37 +08:00
}
```
2012-04-03 22:26:08 +08:00
2012-03-10 20:11:23 +08:00
#### `callback`
2012-03-12 05:16:24 +08:00
2012-03-10 20:11:23 +08:00
`function(err, source / stats)`
2012-05-12 22:43:37 +08:00
`source` if `options.output` is not set (DEPRECATED)
else `stats` as json:
``` javascript
{
hash: "52bd9213...38d",
API: loaderContext.depencency is more relaxed and don't need to be called before reading API: loader.seperable cannot combined with loaderContext.emitFile and loaderContext.emitSubStats loaderContext.options.resolve loaderContext.options.events loaderContext.resolve and .sync API: added profile option (and --profile) API: added workers option (and --workers) API: added closeWorkers option API: if option workers is used: options must be JSON.stringify-able. Except options.resolve and options.events. Any error thrown in loader must be an object (i. e. an Error object). Only message, stack and value of toString is passed to main process. API: The expected Cache object for options.cache has changed. API: event module is emited after the module is finished. API: event context is now named context-enum API: added event context which is emited after the context is finished. API: event dependency is removed. Use stats.dependencies for this. API: event loader is removed. Use stats.loaders for this. API: added stats.contexts as a list of contexts. API: added stats...modules[..].dependencies for as list of files which affect the module's content. API: added stats...modules[..].loaders for as list of loaders which affect the module's content. API: removed stats.modulesPerChunk, it is useless and was deprecated. API: added stats.chunkNameFiles which export the files for named chunks API: added stats.startTime, timestamp as number cmd: more colorful output to indicate caching and timing API: webpack in watch mode emits the event watch-end if watch mode have to end (i. e. loader changed). You may restart it after clearing require.cache. API: added loaderContext.loaderType as one of loader, preLoader or postLoader. API: added loaderContext.currentLoaders as list of all loader of the current type. API: added loaderContext.loaderIndex as index of current loader in loaderContext.currentLoaders. API: added loaderContext.loaders, loaderContext.preLoaders and loaderContext.postLoaders.
2012-09-25 22:45:53 +08:00
startTime: 237467691, // in ms since 1.1.1990
2012-07-11 01:31:22 +08:00
time: 1234, // in ms
2012-05-12 22:43:37 +08:00
chunkCount: 2,
modulesCount: 10,
modulesIncludingDuplicates: 10,
modulesFirstChunk: 3,
fileSizes: {
"output.js": 1234,
"1.output.js": 2345
},
API: loaderContext.depencency is more relaxed and don't need to be called before reading API: loader.seperable cannot combined with loaderContext.emitFile and loaderContext.emitSubStats loaderContext.options.resolve loaderContext.options.events loaderContext.resolve and .sync API: added profile option (and --profile) API: added workers option (and --workers) API: added closeWorkers option API: if option workers is used: options must be JSON.stringify-able. Except options.resolve and options.events. Any error thrown in loader must be an object (i. e. an Error object). Only message, stack and value of toString is passed to main process. API: The expected Cache object for options.cache has changed. API: event module is emited after the module is finished. API: event context is now named context-enum API: added event context which is emited after the context is finished. API: event dependency is removed. Use stats.dependencies for this. API: event loader is removed. Use stats.loaders for this. API: added stats.contexts as a list of contexts. API: added stats...modules[..].dependencies for as list of files which affect the module's content. API: added stats...modules[..].loaders for as list of loaders which affect the module's content. API: removed stats.modulesPerChunk, it is useless and was deprecated. API: added stats.chunkNameFiles which export the files for named chunks API: added stats.startTime, timestamp as number cmd: more colorful output to indicate caching and timing API: webpack in watch mode emits the event watch-end if watch mode have to end (i. e. loader changed). You may restart it after clearing require.cache. API: added loaderContext.loaderType as one of loader, preLoader or postLoader. API: added loaderContext.currentLoaders as list of all loader of the current type. API: added loaderContext.loaderIndex as index of current loader in loaderContext.currentLoaders. API: added loaderContext.loaders, loaderContext.preLoaders and loaderContext.postLoaders.
2012-09-25 22:45:53 +08:00
chunkNameFiles: {
"main": "output.js",
"namedChunk": "1.output.js"
}
2012-10-09 04:39:22 +08:00
dependencies: [ "filename", ... ],
loaders: [ "filename of loader", ... ]
contexts: [ "dirname of context", ... ]
2012-05-12 22:43:37 +08:00
warnings: [ "Some warning" ],
errors: [ "Some error" ],
fileModules: {
"output.js": [
2012-10-09 04:39:22 +08:00
{
id: 0,
size: 123,
filename: "/home/.../main.js",
reasons: [ { type: "main" } ],
API: loaderContext.depencency is more relaxed and don't need to be called before reading API: loader.seperable cannot combined with loaderContext.emitFile and loaderContext.emitSubStats loaderContext.options.resolve loaderContext.options.events loaderContext.resolve and .sync API: added profile option (and --profile) API: added workers option (and --workers) API: added closeWorkers option API: if option workers is used: options must be JSON.stringify-able. Except options.resolve and options.events. Any error thrown in loader must be an object (i. e. an Error object). Only message, stack and value of toString is passed to main process. API: The expected Cache object for options.cache has changed. API: event module is emited after the module is finished. API: event context is now named context-enum API: added event context which is emited after the context is finished. API: event dependency is removed. Use stats.dependencies for this. API: event loader is removed. Use stats.loaders for this. API: added stats.contexts as a list of contexts. API: added stats...modules[..].dependencies for as list of files which affect the module's content. API: added stats...modules[..].loaders for as list of loaders which affect the module's content. API: removed stats.modulesPerChunk, it is useless and was deprecated. API: added stats.chunkNameFiles which export the files for named chunks API: added stats.startTime, timestamp as number cmd: more colorful output to indicate caching and timing API: webpack in watch mode emits the event watch-end if watch mode have to end (i. e. loader changed). You may restart it after clearing require.cache. API: added loaderContext.loaderType as one of loader, preLoader or postLoader. API: added loaderContext.currentLoaders as list of all loader of the current type. API: added loaderContext.loaderIndex as index of current loader in loaderContext.currentLoaders. API: added loaderContext.loaders, loaderContext.preLoaders and loaderContext.postLoaders.
2012-09-25 22:45:53 +08:00
dependencies: [ "filename", ... ],
loaders: [ "filename of loader", ... ]
},
2012-05-12 22:43:37 +08:00
{ id: 1, size: 234, filename: "...", reasons: [
2012-10-09 05:45:46 +08:00
{ type: "require", // or "context"
async: true,
2012-10-09 04:39:22 +08:00
count: 2,
filename: "/home/.../main.js",
2012-10-09 05:45:46 +08:00
// additionally: dirname: "..." // for type = "context"
2012-10-09 04:39:22 +08:00
}
2012-05-12 22:43:37 +08:00
]},
...
],
"1.output.js": [...]
2012-08-07 00:23:24 +08:00
},
subStats: [...], // stats for embedded webpacks
2012-05-12 22:43:37 +08:00
}
```
2012-03-10 20:11:23 +08:00
2012-05-12 23:30:41 +08:00
### with grunt
2012-08-07 05:09:38 +08:00
see [grunt-webpack](https://github.com/webpack/grunt-webpack).
2012-05-12 23:30:41 +08:00
2012-05-01 23:54:19 +08:00
## Bonus features
2012-05-01 23:46:26 +08:00
### File hash
2012-05-12 23:02:20 +08:00
You can use `[hash]` in `publicPrefix`, `output`, `outputDirectory`, `outputPostfix` and in the shell parameters.
2012-05-01 23:46:26 +08:00
`webpack` will replace it with a hash of your files, when writing.
2012-05-02 03:33:59 +08:00
### From shell
Combine the options `--colors --watch --progress` to get a pretty shell compilation.
## Comparison
<table>
<tr>
<th>
Feature
</th>
<th>
2012-08-07 05:09:38 +08:00
webpack/<br/>webpack
</th>
<th>
2012-08-23 10:24:00 +08:00
jrburke/<br/>requirejs
</th>
<th>
substack/<br/>node-<br/>browserify
</th>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
sync <code>require</code>
</td>
<td>
yes
</td>
<td>
2012-08-23 10:24:00 +08:00
only wrapped
</td>
<td>
yes
</td>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
sync <code>require.resolve</code>
</td>
<td>
yes
</td>
<td>
no
</td>
<td>
2012-08-23 10:24:00 +08:00
yes
</td>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
<code>define</code>
</td>
<td>
2012-08-23 10:24:00 +08:00
yes
</td>
<td>
2012-08-23 10:24:00 +08:00
yes
</td>
<td>
no
</td>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
async <code>require</code>
</td>
<td>
yes
</td>
<td>
yes
</td>
<td>
no
</td>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
single bundle
</td>
<td>
2012-08-23 10:24:00 +08:00
yes
</td>
<td>
2012-08-23 10:24:00 +08:00
yes
</td>
<td>
2012-08-23 10:24:00 +08:00
yes
</td>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
load each file seperate
</td>
<td>
no
</td>
<td>
2012-08-23 10:24:00 +08:00
yes
</td>
<td>
no
</td>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
multiple bundles, Code Splitting
</td>
<td>
yes
</td>
<td>
no
</td>
<td>
no
</td>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
indirect require
<code>var r = require; r("./file");</code>
</td>
<td>
2012-08-23 10:24:00 +08:00
in directory
</td>
<td>
2012-08-23 10:24:00 +08:00
yes (not bundled)
</td>
<td>
no
</td>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
concat in require
<code>require("./fi" + "le")</code>
</td>
<td>
yes
</td>
<td>
2012-08-23 10:24:00 +08:00
yes (not bundled)
</td>
<td>
no
</td>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
variables in require (local)
<code>require("./templates/"+template)</code>
</td>
<td>
2012-08-23 10:24:00 +08:00
yes, complete directory included
</td>
<td>
2012-08-23 10:24:00 +08:00
yes (not bundled)
</td>
<td>
no
</td>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
variables in require (global)
<code>require(moduleName)</code>
</td>
<td>
2012-03-21 06:32:28 +08:00
no
</td>
<td>
2012-08-23 10:24:00 +08:00
yes (not bundled)
</td>
<td>
2012-03-21 06:32:28 +08:00
no
</td>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
requirable files
</td>
<td>
2012-08-23 10:24:00 +08:00
filesystem
</td>
<td>
2012-08-23 10:24:00 +08:00
web
</td>
<td>
2012-08-23 10:24:00 +08:00
filesystem
</td>
</tr>
<tr>
<td>
plugins
</td>
<td>
no
</td>
<td>
no
</td>
<td>
yes
</td>
</tr>
<tr>
<td>
2012-03-27 06:34:38 +08:00
loaders
</td>
<td>
2012-05-01 23:46:26 +08:00
yes
</td>
<td>
2012-08-23 10:24:00 +08:00
yes
</td>
<td>
no
</td>
2012-03-27 06:34:38 +08:00
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
watch mode
2012-03-27 06:34:38 +08:00
</td>
<td>
2012-05-01 23:46:26 +08:00
yes
2012-03-27 06:34:38 +08:00
</td>
<td>
2012-08-23 10:24:00 +08:00
not needed
2012-03-27 06:34:38 +08:00
</td>
<td>
yes
</td>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
debug support
</td>
<td>
2012-05-08 05:46:59 +08:00
yes
</td>
<td>
2012-08-23 10:24:00 +08:00
yes
</td>
<td>
yes
</td>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
node buildin libs
<code>require("path");</code>
</td>
<td>
yes
</td>
<td>
no
</td>
<td>
yes
</td>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
<code>process</code> polyfill
</td>
<td>
2012-08-23 10:24:00 +08:00
yes, on demand
</td>
<td>
no
</td>
<td>
2012-08-23 10:24:00 +08:00
yes, ever
</td>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
<code>global</code> to <code>window</code> mapping
</td>
<td>
2012-08-23 10:24:00 +08:00
yes
</td>
<td>
no
</td>
<td>
2012-08-23 10:24:00 +08:00
no
</td>
</tr>
<tr>
<td>
2012-08-23 10:24:00 +08:00
node browser replacements
</td>
<td>
2012-08-23 10:24:00 +08:00
<code>web_modules</code> and <code>.web.js</code><br />
by alias config option
</td>
<td>
2012-08-23 10:24:00 +08:00
by alias config option
</td>
<td>
2012-08-23 10:24:00 +08:00
by alias config option
</td>
</tr>
</table>
2012-03-10 20:11:23 +08:00
2012-03-27 06:34:38 +08:00
2012-03-10 20:11:23 +08:00
## Tests
2012-03-12 04:50:55 +08:00
You can run the unit tests with `npm test`.
2012-03-10 20:11:23 +08:00
You can run the browser tests:
```
cd test/browsertests
node build
```
and open `test.html` in browser. There must be several OKs in the file, no FAIL and no RED boxes.
2012-03-10 20:11:23 +08:00
## Contribution
You are welcome to contribute by writing issues or pull requests.
2012-05-08 05:46:59 +08:00
It would be nice if you open source your own loaders or webmodules. :)
2012-03-10 20:11:23 +08:00
2012-03-21 06:28:43 +08:00
You are also welcome to correct any spelling mistakes or any language issues, because my english is not perfect...
## Future plans
API: loaderContext.depencency is more relaxed and don't need to be called before reading API: loader.seperable cannot combined with loaderContext.emitFile and loaderContext.emitSubStats loaderContext.options.resolve loaderContext.options.events loaderContext.resolve and .sync API: added profile option (and --profile) API: added workers option (and --workers) API: added closeWorkers option API: if option workers is used: options must be JSON.stringify-able. Except options.resolve and options.events. Any error thrown in loader must be an object (i. e. an Error object). Only message, stack and value of toString is passed to main process. API: The expected Cache object for options.cache has changed. API: event module is emited after the module is finished. API: event context is now named context-enum API: added event context which is emited after the context is finished. API: event dependency is removed. Use stats.dependencies for this. API: event loader is removed. Use stats.loaders for this. API: added stats.contexts as a list of contexts. API: added stats...modules[..].dependencies for as list of files which affect the module's content. API: added stats...modules[..].loaders for as list of loaders which affect the module's content. API: removed stats.modulesPerChunk, it is useless and was deprecated. API: added stats.chunkNameFiles which export the files for named chunks API: added stats.startTime, timestamp as number cmd: more colorful output to indicate caching and timing API: webpack in watch mode emits the event watch-end if watch mode have to end (i. e. loader changed). You may restart it after clearing require.cache. API: added loaderContext.loaderType as one of loader, preLoader or postLoader. API: added loaderContext.currentLoaders as list of all loader of the current type. API: added loaderContext.loaderIndex as index of current loader in loaderContext.currentLoaders. API: added loaderContext.loaders, loaderContext.preLoaders and loaderContext.postLoaders.
2012-09-25 22:45:53 +08:00
see [/webpack/webpack/wiki/Ideas](wiki Ideas)
2012-03-10 20:11:23 +08:00
## License
2012-05-25 06:17:02 +08:00
Copyright (c) 2012 Tobias Koppers
2012-05-12 23:02:20 +08:00
MIT (http://www.opensource.org/licenses/mit-license.php)
## Dependencies
* [esprima](http://esprima.org/)
* [optimist](https://github.com/substack/node-optimist)
* [uglify-js](https://github.com/mishoo/UglifyJS)
* [sprintf](https://github.com/maritz/node-sprintf)