扩展

扩展

字符串 | 字符串数组

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