扩展

扩展

字符串 | 字符串数组

webpack v5.82.0+ webpack-cli v5.1.0+

extends 属性允许你扩展现有配置作为基础配置。它内部使用 webpack-merge 包来合并配置,帮助你避免在多个配置之间重复配置。

base.webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: 'babel-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production'),
    }),
  ],
};

webpack.config.js

module.exports = {
  extends: path.resolve(__dirname, './base.webpack.config.js'),
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
};

扩展多个配置

你可以通过向 extends 属性传入一个配置路径数组来一次性扩展多个配置。

extends 属性中的配置是从右向左合并的,这意味着右侧的配置将被合并到左侧的配置中。通过在右侧配置中传入相同的属性,可以覆盖(左侧的)配置。

js.webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: 'babel-loader',
        exclude: /node_modules/,
      },
    ],
  },
};

css.webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
};

webpack.config.js

module.exports = {
  extends: [
    path.resolve(__dirname, './js.webpack.config.js'),
    path.resolve(__dirname, './css.webpack.config.js'),
  ],
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
};

覆盖配置

你可以通过在扩展的配置中传入相同的属性来覆盖来自被扩展配置的属性。

base.webpack.config.js

module.exports = {
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
};

webpack.config.js

module.exports = {
  extends: path.resolve(__dirname, './base.webpack.config.js'),
  entry: './src/index.js',
  // overriding the output path and filename
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: '[name].bundle.js',
  },
};

从外部包加载配置

你也可以通过将包名传递给 extends 属性来从第三方包加载配置。该包必须在 package.json 中导出 webpack 配置。

webpack.config.js

module.exports = {
  extends: require.resolve('webpack-config-foo'),
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
};

1 贡献者

burhanuday