Extends

extends

文字列 | 文字列配列

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