How do I configure mini-css-extract-plugin in Gatsby?

Solution 1:

As you can see in Gatsby documentation in your gatsby-node.js Gatsby exposes a few APIs to change webpack's default configuration, one of them, onCreateWebpackConfig, extends and mutates this configuration allowing you to fit your requirements:

Let plugins extend/mutate the site’s webpack configuration.

See also the documentation for setWebpackConfig.

exports.onCreateWebpackConfig = ({ stage, actions, getConfig }) => {
  if (stage === 'build-javascript') {
    const config = getConfig()
    const miniCssExtractPlugin = config.plugins.find(
      plugin => plugin.constructor.name === 'MiniCssExtractPlugin'
    )
    if (miniCssExtractPlugin) {
      miniCssExtractPlugin.options.ignoreOrder = true
    }
    actions.replaceWebpackConfig(config)
  }
}

There's no much mistery, the code is self-explanatory. Basically you look for mini-css-extract-plugin with plugin.constructor.name === 'MiniCssExtractPlugin' and set your ignoreOrder option as true. Afterward, you replace webpack's default stage action with actions.replaceWebpackConfig(config).

Solution 2:

If you want to use it also in development and in production, you have to add one more condition:


//gatsby-node.js

exports.onCreateWebpackConfig = helper => {
  const { stage, actions, getConfig } = helper
  if (stage === "develop" || stage === 'build-javascript') {
    const config = getConfig()
    const miniCssExtractPlugin = config.plugins.find(
      plugin => plugin.constructor.name === "MiniCssExtractPlugin"
    )
    if (miniCssExtractPlugin) {
      miniCssExtractPlugin.options.ignoreOrder = true
    }
    actions.replaceWebpackConfig(config)
  }
}