Configuration

Out of the box, webpack won't require you to use a configuration file. However, it will assume the entry point of your project is src/index.js and will output the result in dist/main.js minified and optimized for production.

Usually your projects will need to extend this functionality, for this you can create a webpack.config.js file in the root folder and webpack will automatically use it.

All the available configuration options are specified below.

New to webpack? Check out our guide to some of webpack's core concepts to get started!

Use different configuration file

If for some reason you want to use different configuration file depending on certain situations you can change this via command line by using the --config flag.

package.json

"scripts": {
  "build": "webpack --config prod.config.js"
}

Options

Click on the name of each option in the configuration code below to jump to the detailed documentation. Also note that the items with arrows can be expanded to show more examples and, in some cases, more advanced configuration.

Notice that throughout the configuration we use Node's built-in path module and prefix it with the __dirname global. This prevents file path issues between operating systems and allows relative paths to work as expected. See this section for more info on POSIX vs. Windows paths.

Notice that many array configurations allow to reference the default value via "...".

webpack.config.js

const path = require('path');

module.exports = {
  
  // Chosen mode tells webpack to use its built-in optimizations accordingly.
  
  // defaults to ./src
  // Here the application starts executing
  // and webpack starts bundling
  
    // options related to how webpack emits results
    
    // the target directory for all output files
    // must be an absolute path (use the Node.js path module)
    
    // the filename template for entry chunks
    
    // the url to the output directory resolved relative to the HTML page
    
      
      // the type of the exported library
      
      // the name of the exported library

      
    },
    uniqueName: "my-application", // (defaults to package.json "name")
    // unique name for this build to avoid conflicts with other builds in the same HTML
    name: "my-config",
    // name of the configuration, shown in output
    
    <expertOutput "#">
      <default>
        /* Expert output configuration (on own risk) */
      </default>
      pathinfo: true, // boolean
      // include useful path info about modules, exports, requests, etc. into the generated code
      charset: true, // string
      // add charset attribute to injected script tags
      chunkLoadTimeout: 120000, // number (default)
      // timeout for loading chunks
      chunkLoading: "jsonp" // "jsonp" | "import-scripts" | "require" | "async-node" | false
      // method of loading chunks
      chunkLoadingGlobal: "myWebpackJsonp", // string
      // name of the global variable used to load chunks
      enabledChunkLoadingTypes: ["jsonp"], // string[]
      // the chunk loading methods that are available
      enabledLibraryTypes: ["var"], // string[]
      // the library types that are available
      enabledWasmLoadingTypes: ["var"], // string[]
      // the wasm loading methods that are available
      compareBeforeEmit: true, // boolean (default)
      // compare the generated asset with the asset on disk before writing to disk
      chunkFormat: "array-push",
      chunkFormat: "commonjs",
      chunkFormat: false,
      // the format of chunks
      hotUpdateMainFilename: "[hash].hot-update.json", // string
      // filename template for HMR manifest
      hotUpdateChunkFilename: "[id].[hash].hot-update.js", // string
      // filename template for HMR chunks
      hotUpdateGlobal: "hmrUpdateFunction", // string
      // the name of the global variable used to load hot update chunks
      sourcePrefix: "\t", // string
      // prefix module sources in bundle for better readablitity
      // but breaks multi-line template strings
      strictModuleExceptionHandling: true, // boolean
      // handle errors in module evaluation correctly, but for a performance cost
      devtoolNamespace: "MyLibrary", // string
      // prefix in the source names for devtools
      // defaults to output.uniqueName
      environment: {
        // Properties about the environment
        arrowFunction: true,
        bigIntLiteral: true,
        const: true,
        destructuring: true,
        dynamicImport: true,
        forOf: true,
        module: true
      },
      iife: true, // boolean (default)
      // wrap the bundle in a IIFE for isolation
      module: false, // boolean (default)
      // generate a module type javascript file instead of a classic script
      scriptType: "module"
      // adds a type attribute to injected script tags
      globalObject: "self", // string (default),
      // expression that points to the global object
      importFunctionName: "import", // string (default)
      // expression that is called when using import()
      // can be replaced to use polyfills
      importMetaName: "import.meta", // string (default)
      // expression that is used when using import.meta
      // can be replaced to use polyfills
      hashFunction: "md4", // string (default)
      // hash function used in general
      hashDigest: "hex", // string (default)
      // hash digest type used
      hashDigestLength: 20, // number (default)
      // length of hashes
      hashSalt: "salt", // string | Buffer
      // an additional hash salt to fix hash related issues or change the hash in general
    </expertOutput>
  },
  module: {
    // configuration regarding modules
    rules: [
      // rules for modules (configure loaders, parser options, etc.)
      {
        // Conditions:
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, "app")
        ],
        exclude: [
          path.resolve(__dirname, "app/demo-files")
        ],
        // these are matching conditions, each accepting a regular expression or string
        // test and include have the same behavior, both must be matched
        // exclude must not be matched (takes preferrence over test and include)
        // Best practices:
        // - Use RegExp only in test and for filename matching
        // - Use arrays of absolute paths in include and exclude to match the full path
        // - Try to avoid exclude and prefer include
        // Each condition can also receive an object with "and", "or" or "not" properties
        // which are an array of conditions.
        issuer: /\.css$/,
        issuer: path.resolve(__dirname, "app"),
        issuer: { and: [ /\.css$/, path.resolve(__dirname, "app") ] },
        issuer: { or: [ /\.css$/, path.resolve(__dirname, "app") ] },
        issuer: { not: [ /\.css$/ ] },
        issuer: [ /\.css$/, path.resolve(__dirname, "app") ], // like "or"
        // conditions for the issuer (the origin of the import)
        

        // Actions:
        loader: "babel-loader",
        // the loader which should be applied, it'll be resolved relative to the context
        options: {
          presets: ["es2015"]
        },
        // options for the loader
        use: [
          // apply multiple loaders and options instead
          "htmllint-loader",
          {
            loader: "html-loader",
            options: {
              / ... /
            }
          }
        ]
        
        // specifies the module type
        
      },
      {
        oneOf: [ / rules / ]
        // only use one of these nested rules
      },
      {
        / conditions /
        rules: [ / rules / ]
        // use all of these nested rules (combine with conditions to be useful)
      },
    ],
    
  },
  resolve: {
    // options for resolving module requests
    // (does not apply to resolving of loaders)
    
    // directories where to look for modules (in order)
    extensions: [".js", ".json", ".jsx", ".css"],
    // extensions that are used
    alias: {
      // a list of module name aliases
      // aliases are imported relative to the current context
      "module": "new-module",
      // alias "module" -> "new-module" and "module/path/file" -> "new-module/path/file"
      "only-module$": "new-module",
      // alias "only-module" -> "new-module", but not "only-module/path/file" -> "new-module/path/file"
      "module": path.resolve(__dirname, "app/third/module.js"),
      // alias "module" -> "./app/third/module.js" and "module/file" results in error
      "module": path.resolve(__dirname, "app/third"),
      // alias "module" -> "./app/third" and "module/file" -> "./app/third/file"
      [path.resolve(__dirname, "app/module.js")]: path.resolve(__dirname, "app/alternative-module.js"),
      // alias "./app/module.js" -> "./app/alternative-module.js"
    },
    
    
  },
  performance: {
    
    maxAssetSize: 200000, // int (in bytes),
    maxEntrypointSize: 400000, // int (in bytes)
    assetFilter: function(assetFilename) {
      // Function predicate that provides asset filenames
      return assetFilename.endsWith('.css') || assetFilename.endsWith('.js');
    }
  },
  
  // enhance debugging by adding meta info for the browser devtools
  // source-map most detailed at the expense of build speed.
  context: __dirname, // string (absolute path!)
  // the home directory for webpack
  // the entry and module.rules.loader option
  //   is resolved relative to this directory
  
  // the environment in which the bundle should run
  // changes chunk loading behavior, available external modules
  // and generated code style
  
  // Type of externals, when not specified inline in externals
  
  // presets of externals
  
  
  stats: {
    // lets you precisely control what bundle information gets displayed
    
    // A stats preset

    

    env: true,
    // include value of --env in the output
    outputPath: true,
    // include absolute output path in the output
    publicPath: true,
    // include public path in the output

    assets: true,
    // show list of assets in output
    

    entrypoints: true,
    // show entrypoints list
    chunkGroups: true,
    // show named chunk group list
    

    chunks: true,
    // show list of chunks in output
    

    modules: true,
    // show list of modules in output
    

    

    splitChunks: {
      cacheGroups: {
        "my-name": {
          // define groups of modules with specific
          // caching behavior
          test: /\.sass$/,
          type: "css/mini-extract",

          

          
        }
      },

      

      

      

      
    }
  },
  
  
  

webpack applies configuration defaults after plugins defaults are applied.

Want to rapidly generate webpack configuration file for your project requirements with few clicks away.

Use webpack-cli's init command that will ask you a couple of questions before creating a configuration file.

npx webpack-cli init

You might be prompted to install @webpack-cli/init if it is not yet installed in the project or globally.

After running npx webpack-cli init you might get more packages installed to your project depending on the choices you've made during configuration generation.

npx webpack-cli init

β„Ή INFO For more information and a detailed description of each question, have a look at https://github.com/webpack/webpack-cli/blob/master/INIT.md
β„Ή INFO Alternatively, run `webpack(-cli) --help` for usage info.

? Will your application have multiple bundles? No
? Which module will be the first to enter the application? [default: ./src/index]
? Which folder will your generated bundles be in? [default: dist]:
? Will you be using ES2015? Yes
? Will you use one of the below CSS solutions? No

+ babel-plugin-syntax-dynamic-import@6.18.0
+ uglifyjs-webpack-plugin@2.0.1
+ webpack-cli@3.2.3
+ @babel/core@7.2.2
+ babel-loader@8.0.4
+ @babel/preset-env@7.1.0
+ webpack@4.29.3
added 124 packages from 39 contributors, updated 4 packages and audited 25221 packages in 7.463s
found 0 vulnerabilities


Congratulations! Your new webpack configuration file has been created!

createapp.dev - create a webpack configuration in your browser is an online tool for creating custom webpack configuration. It allows you to select various features that will be combined and added to resulting configuration file. Also, it generates an example project based on provided webpack configuration that you can review in your browser and download.