配置

webpack 开箱即用,可以无需使用任何配置文件。然而,webpack 会假定项目的入口起点为 src/index.js,然后会在 dist/main.js 输出结果,并且在生产环境开启压缩和优化。

通常你的项目还需要继续扩展此能力,为此你可以在项目根目录下创建一个 webpack.config.js 文件,然后 webpack 会自动使用它。

下面指定了所有可用的配置选项。

刚开始学习 webpack?请查看我们提供的指南,从 webpack 一些 核心概念 开始学习吧!

使用不同的配置文件

如果出于某些原因,需要根据特定情况使用不同的配置文件,则可以通过在命令行中使用 --config flag 修改此配置文件名称。

package.json

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

选项

点击下面配置代码中每个选项的名称,跳转到详细的文档。还要注意,带有箭头的项目可以展开,以显示更多示例,在某些情况下可以看到高级配置。

注意整个配置中我们使用 Node 内置的 path 模块,并在它前面加上 __dirname这个全局变量。可以防止不同操作系统之间的文件路径问题,并且可以使相对路径按照预期工作。更多「POSIX 和 Windows」的相关信息请查看 此章节

webpack.config.js

const path = require('path');

module.exports = {
  
  // Chosen mode tells webpack to use its built-in optimizations accordingly.
  
  // 默认为 ./src
  // 这里应用程序开始执行
  // webpack 开始打包
  
    // webpack 如何输出结果的相关选项
    path: path.resolve(__dirname, "dist"), // string
    // 所有输出文件的目标路径
    // 必须是绝对路径(使用 Node.js 的 path 模块)
    
    // entry chunk 的文件名模板
    
    // 输出解析文件的目录,url 相对于 HTML 页面
    library: "MyLibrary", // string,
    // 导出库(export library)的名称
    
    // 导出库(export library)的类型
    
    
  },
  module: {
    // configuration regarding modules
    rules: [
      // rules for modules (configure loaders, parser options, etc.)
      {
        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
        // - Try to avoid exclude and prefer include
        issuer: { test, include, exclude },
        // conditions for the issuer (the origin of the import)
        enforce: "pre",
        enforce: "post",
        // flags to apply these rules, even if they are overridden (advanced option)
        loader: "babel-loader",
        // the loader which should be applied, it'll be resolved relative to the context
        options: {
          presets: ["es2015"]
        },
        // options for the loader
      },
      {
        test: /\.html$/,
        use: [
          // apply multiple loaders and options
          "htmllint-loader",
          {
            loader: "html-loader",
            options: {
              / ... /
            }
          }
        ]
      },
      { oneOf: [ / rules / ] },
      // only use one of these nested rules
      { rules: [ / rules / ] },
      // use all of these nested rules (combine with conditions to be useful)
      { resource: { and: [ / conditions / ] } },
      // matches only if all conditions are matched
      { resource: { or: [ / conditions / ] } },
      { resource: [ / conditions / ] },
      // matches if any condition is matched (default for arrays)
      { resource: { not: / condition / } }
      // matches if the condition is not matched
    ],
    
  },
  resolve: {
    // options for resolving module requests
    // (does not apply to resolving to loaders)
    modules: [
      "node_modules",
      path.resolve(__dirname, "app")
    ],
    // directories where to look for modules
    extensions: [".js", ".json", ".jsx", ".css"],
    // extensions that are used
    alias: {
      // a list of module name aliases
      "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
      // modules aliases are imported relative to the current context
    },
    
    
  },
  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 and available modules
  
  // Don't follow/bundle these modules, but request them at runtime from the environment
  
  // lets you precisely control what bundle information gets displayed
  devServer: {
    proxy: { // proxy URLs to backend development server
      '/api': 'http://localhost:3000'
    },
    contentBase: path.join(__dirname, 'public'), // boolean | string | array, static file location
    compress: true, // enable gzip compression
    historyApiFallback: true, // true for index.html upon 404, object for multiple paths
    hot: true, // hot module replacement. Depends on HotModuleReplacementPlugin
    https: false, // true for self-signed, object for cert authority
    noInfo: true, // only errors & warns on hot reload
    // ...
  },
  plugins: [
    // ...
  ],
  // list of additional plugins
  

webpack applies configuration defaults after plugins defaults are applied.

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

Generate Custom Webpack Configuration is an interactive portal you can play around by selecting custom webpack configuration options tailored for your frontend project. It automatically generates a minimal webpack configuration based on your selection of loaders/plugins, etc.

Or 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.