Skip to content
This repository was archived by the owner on Aug 8, 2019. It is now read-only.

webpack options

Tobias Koppers edited this page Nov 15, 2013 · 74 revisions

webpack options

module.exports = {
  context: "/home/proj",
  entry: "./entry",
  module: {
    loaders: [{
      test: /\.coffee$/,
      include: /lib/, exclude: /test/,
      loader: "coffee"
    }],
    preLoaders: [/*...*/],
    postLoaders: [/*...*/],
    noParse: [/jquery.min.js/] // 0.11
  },
  output: {
    path: "/home/proj/assets",
    filename: "[hash].bundle.js",
    chunkFilename: "[id].[hash].bundle.js",
    namedChunkFilename: "[name].[hash].js",
    sourceMapFilename: "[file].map", // 0.10
    hotUpdateChunkFilename: "[id].[hash].bundle-update.js", // 0.11
    hotUpdateMainFilename: "[hash].bundle-update.json", // 0.11
    publicPath: "/assets/",
    jsonpFunction: "webpackJsonp",
    hotUpdateFunction: "webpackHotUpdate", // 0.11
    pathInfo: true,
    library: "Lib",
    libraryTarget: "commonjs"
  },
  recordsInputPath: "/home/proj/records.json", // 0.10
  recordsOutputPath: "/home/proj/records.json", // 0.10
  recordsPath: "/home/proj/records.json", // 0.10
  target: "web",
  bail: true,
  profile: true,
  cache: true,
  watch: true,
  watchDelay: 200,
  debug: true,
  devtool: "eval",
  hot: true, // 0.11 experimental
  amd: { jQuery: true },
  node: {
    process: "mock",
    http: "mock",
    console: true,
    __filename: "mock",
    __dirname: "mock"
  },
  define: { // 0.11
    TRUE: true,
    MY_CONST: JSON.stringify("value of my const")
  },
  resolve: {
    alias: {
      module: "other-module",
      module2: "/home/proj/shim-module.js"
    },
    root: "/home/proj/app",
    modulesDirectories: ["modules", "node_modules"],
    fallback: "/home/proj/fallback",
    extensions: ["", ".client.js", ".js"],
    unsafeCache: /^\/home\/proj\/app\/node_modules\// // 0.11
  },
  resolveLoader: {/*...*/},
  provide: {
    $: "jquery",
    jQuery: "jquery"
  },
  optimize: {
    minChunkSize: 20000,
    maxChunks: 5,
    minimize: true,
    occurenceOrder: true, // 0.10
    occurenceOrderPreferEntry: true, // 0.10
    dedupe: true // 0.10 experimental
  },
  prefetch: [ // 0.10 experimental
    "./folder/file"
  ],
  plugins: [
    new MyPlugin()
  ]
}

context

The base directory for resolving the entry option. If output.pathinfo is set, the included pathinfo is shortened to this directory.

Default: process.cwd()

entry

The entry point for the bundle.

If you pass a string: The string is resolve to a module which is loaded upon startup.

If you pass an array: All modules are loaded upon startup. The last one is exported.

entry: ["./entry1", "./entry2"]

If you pass an object: Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.

entry: {
  page1: "./page1",
  page2: ["./entry1", "./entry2"]
},
output: {
  // Make sure to use [name] or [id] in output.filename
  //  when using multiple entry points
  filename: "[name].bundle.js",
  chunkFilename: "[id].bundle.js"
}

module

Options affecting the normal modules (NormalModuleFactory)

module.loaders

A array of automatically applied loaders.

Each item can have these properties:

  • test: A condition that must be met
  • exclude: A condition that must not be met
  • include: A condition that must be met
  • loader: A string of "!" separated loaders
  • loaders: A array of loaders as string

A condition can be a RegExp, or a array of RegExps combined with "and".

See more: loaders

module.preLoaders, module.postLoaders

Syntax like module.loaders.

A array of applied pre and post loaders.

module.noParse (0.11)

A RegExp or an array of RegExps. Don't parse files matching.

This can boost performance when ignoring big libraries.

The files are expected to have no call to require, define or similar. They are allowed to use exports and module.exports.

output

Options affecting the output.

If you use any hashing ([hash] or [chunkhash]) make sure to have a consistent ordering of modules. Use optimize.occurenceOrder or recordsPath.

output.path

The output directory as absolute path.

[hash] is replaced by the hash of the compilation.

output.filename

The filename of the entry chunk as relative path inside the output.path directory.

[name] is replaced by the name of the chunk.

[hash] is replaced by the hash of the compilation.

output.chunkFilename

The filename of non-entry chunks as relative path inside the output.path directory.

[id] is replaced by the id of the chunk.

[hash] is replaced by the hash of the compilation.

[chunkhash] is replaced by the hash of the chunk. (0.10)

output.namedChunkFilename

The filename of named chunks as relative path inside the output.path directory.

[name] is replaced by the name of the chunk.

[hash] is replaced by the hash of the compilation.

output.sourceMapFilename (0.10)

The filename of the SourceMaps for the Javascript files. They are inside the output.path directory.

[file] is replaced by the filename of the Javascript file.

[id] is replaced by the id of the chunk.

[hash] is replaced by the hash of the compilation.

Default: "[file].map"

output.hotUpdateChunkFilename (0.11)

The filename of the Hot Update Chunks. They are inside the output.path directory.

[id] is replaced by the id of the chunk.

[hash] is replaced by the hash of the compilation. (The last hash stored in the records)

Default: "[id].[hash].hot-update.js"

output.hotUpdateChunkFilename (0.11)

The filename of the Hot Update Main File. It is inside the output.path directory.

[hash] is replaced by the hash of the compilation. (The last hash stored in the records)

Default: "[hash].hot-update.json"

output.publicPath

The output.path from the view of the javascript.

// Example
output: {
  path: "/home/proj/public/assets",
  publicPath: "/assets"
}
// Example CDN
output: {
  path: "/home/proj/cdn/assets/[hash]",
  publicPath: "http://cdn.example.com/assets/[hash]/"
}

output.jsonpFunction

The JSONP function used by webpack for asnyc loading of chunks.

A shorter function may reduce the filesize a bit. Use different identifier, when having multiple webpack instances on a single page.

Default: "webpackJsonp"

output.hotUpdateFunction

The JSONP function used by webpack for asnyc loading of hot update chunks.

Default: "webpackHotUpdate"

output.pathInfo

Include comments with information about the modules.

require(/* ./test */23)

Do not use this in production.

Default: false

output.library

If set, export the bundle as library. output.library is the name.

Use this, if you are writing a library and want to publish it as single file.

output.libraryTarget

Kind of exporting as library.

var - Export by setting a variable: var Library = xxx (default)

this - Export by setting a property of this: this["Library"] = xxx

commonjs - Export by setting a property of exports: exports["Library"] = xxx

commonjs2 - Export by setting module.exports: module.exports = xxx

umd - Export to AMD, CommonJS2 or as property in root

Default: var

recordsPath, recordsInputPath, recordsOutputPath (0.11)

Store/Load compiler state from/to a json file. This will result in persistent ids of modules and chunks.

An absolute path is excepted. recordsPath is used for recordsInputPath and recordsOutputPath if they left undefined.

This is required, when using Hot Code Replacement between multiple calls to the compiler.

target

  • "web" Compile for usage in a browser-like environment (default)
  • "webworker" Compile as WebWorker
  • "node" Compile for usage in a node.js-like environment

bail

Report the first error at a hard error instead of tolerating it.

profile

Capture timing information for each module.

Hint: Use the analyse tool to visualize it.

cache

Cache generated modules and chunks to improve performance for multiple incremental builds.

watch

Enter watch mode, which rebuilds on file change.

Only use it with the node.js javascript api webpack(options, fn).

watchDelay

Delay the rebuilt after the first change. Value is a time in ms.

Default: 200

debug

Switch loaders to debug mode.

devtool

Choose a developer tool to enhance debugging.

eval - Each module is executed with eval and //@ sourceURL.

source-map - A SourceMap is emitted. See also output.sourceMapFilename. (0.10)

inline-source-map - A SourceMap is added as DataUrl to the Javascript file. (0.10)

Prefixing @, # or #@ will enforce a pragma style. (0.11)

hot

Enables Hot Module Replacement. (This requires records data if not in dev-server mode, recordsPath)

Generates Hot Update Chunks of each chunk in the records. It also enables the API.

node

Include polyfills or mocks for various node stuff:

  • console: true or false
  • global: true or false
  • process: true, "mock" or false
  • buffer: true, "mock" or false
  • __filename: true (real filename), "mock" ("/index.js") or false
  • __dirname: true (real dirname), "mock" ("/") or false
  • <node buildin>: true, "mock" or false
// Default:
{
  console: false,
  process: true,
  global: true,
  buffer: true,
  __filename: "mock",
  __dirname: "mock"
}

amd

Set the value of require.amd and define.amd.

Example: amd: { jQuery: true } (for old 1.x AMD versions of jquery)

define

Define free variables. The values will be inlined into the code.

A key is a identifier or multiple identifier joined with .. If the value is a string it'll be used a code fragment. If the value isn't a string, it'll be stringified (including functions).

If the value is an object all keys are defined the same way.

Example:

define: {
  VERSION: JSON.stringify("5fa3b9"),
  BROWSER_SUPPORTS_HTML5: true,
  TWO: "1+1"
}
console.log("Running App version " + VERSION);
if(!BROWSER_SUPPORTS_HTML5) require("html5shiv");

resolve

Options affecting the resolving of modules.

resolve.alias

Replace modules by other modules or paths.

Expected is a object with keys being module names. The value can be either something that resolve to a file or something that resolve to a directory. If it resolve to a file, only the direct require to the module will resolve to that file. If it resolve to a directory all requires to that module or children will resolve relative to that value.

If the value is a relative path it will be relative to the file containing the require.

Examples: Calling a require from /abc/entry.js with different alias settings.

alias: require("xyz") require("xyz/file.js")
{} /abc/node_modules/xyz/index.js /abc/node_modules/xyz/file.js
{ xyz: "/absolute/path/to/file.js" } /absolute/path/to/file.js /abc/node_modules/xyz/file.js
{ xyz: "./dir/file.js" } /abc/dir/file.js /abc/node_modules/xyz/file.js
{ xyz: "/some/dir" } /some/dir/index.js /some/dir/file.js
{ xyz: "./dir" } /abc/dir/index.js /abc/dir/file.js
{ xyz: "modu" } /abc/node_modules/modu/index.js /abc/node_modules/modu/file.js
{ xyz: "modu/some/file.js" } /abc/node_modules/modu/some/file.js /abc/node_modules/xyz/file.js
{ xyz: "modu/dir" } /abc/node_modules/modu/dir/index.js /abc/node_modules/dir/file.js
{ xyz: "xyz/dir" } /abc/node_modules/xyz/dir/index.js /abc/node_modules/xyz/dir/file.js

index.js may resolve to another file if defined in the package.json.

/abc/node_modules may resolve in /node_modules too.

resolve.root

Look of modules in this directory (or directories if you pass an array).

resolve.modulesDirectories

Look of modules in this directories. It'll check these directories in current directory and each parent directory.

Default: ["web_modules", "node_modules"]

resolve.fallback

Look of modules in this directory (or directories if you pass an array), if no module found in resolve.root and resolve.modulesDirectories.

resolve.extensions

Resolve to files by adding this extensions.

Default: ["", ".webpack.js", ".web.js", ".js"]

resolve.packageMains

Check these fields in the package.json for suitable files.

Default: ["webpack", "browser", "web", "main"]

resolve.unsafeCache

Enable aggressive but unsafe caching for the resolving of a part of your files. Changes to cached paths may cause failure (in rar cases). An array of RegExps, only a RegExp or true (all files) is expected. If the resolved path matches, it'll be cached.

Default: []

resolveLoader

Like resolve but for loaders.

// Default:
{
  modulesDirectories: ["web_loaders", "web_modules", "node_loaders", "node_modules"],
  extensions: ["", ".webpack-loader.js", ".web-loader.js", ".loader.js", ".js"],
  packageMains: ["webpackLoader", "webLoader", "loader", "main"]
}

resolveLoader.moduleTemplates

That's a resolveLoader only property.

It describes alternatives for the module name that are tried.

Default: ["*-webpack-loader", "*-web-loader", "*-loader", "*"]

optimize

Options affecting the optimization of the compilation.

optimize.minChunkSize

Merge small chunks that are lower than this min size (in chars). Size is approximated.

optimize.maxChunks

Limit the chunk count to a defined value. Chunks are merged until it fits.

optimize.minimize

Minimize all javascript output of chunks. Loaders are switched into minimizing mode. You can pass false, true or an object containing UglifyJs options.

optimize.occurenceOrder

Assign the module and chunk ids by occurrence count. Ids that are used often get lower (shorter) ids. This make ids predictable and is recommended. (It is available as option since 0.10, but was ever activated prior to 0.10)

Default: false

optimize.occurenceOrderPreferEntry

Only available if optimize.occurenceOrder is set. Occurrences in entry chunks have higher priority. This make entry chunks smaller but increases the overall size.

Default: true

optimize.dedupe

Search for equal or similar files and deduplicate them in the output. This comes with some overhead for the entry chunk, but can reduce file size effectively.

This is experimental and may crash, because of some missing implementations. (Report an issue)

Default: false

prefetch

A list of requests for normal modules, which are resolved and built even before a require to them occur. This can boost performance. Try to profile the built first to determine clever prefetching points.

plugins

Add additional plugins to the compiler.

Good start config (example)

var path = require("path");
module.exports = {
  context: __dirname,
  entry: "./app/app.js",
  output: {
    path: path.join(__dirname, "public", "assets"),
    publicPath: "/assets/",
    filename: "[hash].js"
  },
  module: {
    loaders: [
      { test: /\.json$/,   loader: "json-loader" },
      { test: /\.coffee$/, loader: "coffee-loader" },
      { test: /\.css$/,    loader: "style-loader!css-loader" },
      { test: /\.less$/,   loader: "style-loader!css-loader!less-loader" },
      { test: /\.jade$/,   loader: "jade-loader" },
      { test: /\.png$/,    loader: "url-loader?limit=10000&minetype=image/png" },
      { test: /\.jpg$/,    loader: "url-loader?limit=10000&minetype=image/jpg" },
      { test: /\.gif$/,    loader: "url-loader?limit=10000&minetype=image/gif" },
      { test: /\.woff$/,   loader: "url-loader?limit=10000&minetype=application/font-woff" }
      { test: /\.ttf$/,    loader: "url-loader?limit=10000&minetype=application/octet-stream" },
      { test: /\.eot$/,    loader: "file-loader" },
      { test: /\.svg$/,    loader: "url-loader?limit=10000&minetype=image/svg+xml" },
    ],
    preLoaders: [
      {
        test: [
          /\.js$/,
          /\.json$/,
        ],
        include: pathToRegExp(path.join(__dirname, "app")),
        loader: "jshint-loader"
      }
    ]
  },
  resolve: {
    fallback: path.join(__dirname, "app")
  },
  cache: true,
  amd: { jQuery: true },
  optimize: {
    minChunkSize: 10000,
    maxChunks: 20,
  },
  plugins: [
  ]
};
function escapeRegExpString(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\\+\?\.\\\\\^\$\|]/g, "\\\\$&"); }
function pathToRegExp(p) { return new RegExp("^" + escapeRegExpString(p)); }
# development: compile and watch
webpack -d --watch --progress --colors

# development: server
webpack-dev-server -d --colors

# production: compile
webpack -p --progress --colors
Clone this wiki locally