Home > Software engineering >  Modify @wordpress/scripts MiniCssExtractPlugin settings with webpack.config.js
Modify @wordpress/scripts MiniCssExtractPlugin settings with webpack.config.js

Time:01-20

I'm using the @wordpress/scripts package and I want to modify the output of the css files to make them go into a subfolder called css. How do I either remove the original MiniCssExtractPlugin settings or modify the original settings made in the default config? I don't know how to target the already created MiniCssExtractPlugin so I can remove it or modify it.

I have tried adding

plugins: [
  ...defaultConfig.plugins,
  new RemoveEmptyScriptsPlugin(),
  new MiniCssExtractPlugin({
    filename: "css/[name].css",
    ignoreOrder: false,
  }),
]

to a webpack.config.js file in the project folder and it does output the css in a subfolder called css, however, the css ALSO get output in the root of the output folder.

CodePudding user response:

Remove the original MiniCssExtractPlugin by filtering it out from the defaultConfig.plugins array. One way to do this would be to use the Array.filter() method to remove any instances of the plugin from the array before adding your modified version.

const defaultConfig = require('@wordpress/scripts/config/webpack.config');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const config = {
  ...defaultConfig,
  plugins: defaultConfig.plugins.filter((plugin) => {
    return !(plugin instanceof MiniCssExtractPlugin);
  }),
  module: {
    ...defaultConfig.module,
    rules: [
      ...defaultConfig.module.rules,
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: 'css/[name].css',
      ignoreOrder: false,
    }),
  ],
};

module.exports = config;

CodePudding user response:

The answer from Faisal sent me in the right direction so here's the code I ended up with that seems to work.

const defaultConfig = require("@wordpress/scripts/config/webpack.config");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

//Remove default MiniCssExtractPlugin settings
defaultConfig.plugins = defaultConfig.plugins.filter((plugin) => {
  return !(plugin instanceof MiniCssExtractPlugin);
});

module.exports = {
  ...defaultConfig,
  plugins: [
    ...defaultConfig.plugins,
    new MiniCssExtractPlugin({
      filename: "css/[name].css",
      ignoreOrder: false,
    }),
  ],
};
  • Related