Search code examples
reactjswebpackgatsbyloaderwebpack-5

I am migrating my Gatsby site from v2 to v3 and I have updated my npm packages but I am getting errors


I am migrating from gatsby v2 to v3 so that I can use Gatsby Incremental build in my website without using Gatsby cloud services but on updating gatsby version and updating every outdated npm packages I am getting errors for this Mini Extract css,

I am having webpack version 5 and node version above 12 and after updating every oudated npm I am not able to solve this mini css extract issue

I am getting this error while running locally :

Module build failed (from 
./node_modules/gatsby/node_modules/mini-css-extract-plugin/dist/loader.js):
ValidationError: Invalid options object. Mini CSS Extract Plugin Loader has been initialized using  
an options object that does not match the API schema.
 - options has an unknown property 'hmr'. These properties are valid:
   object { publicPath?, emit?, esModule?, layer?, modules? }
    at validate 

I have setup a webpack.config.js file and here is code of this file can anyone suggest what I am missing that I am getting this hmr error:

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css",
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
  optimization: {
    minimizer: [
      // For webpack@5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
      // `...`,
      new CssMinimizerPlugin(),
    ],
    minimize: true,
  },
};

Solution

  • CSS modules in Gatsby v3 onwards needs to be imported as ES modules, so your:

    import styles from './related-products.modules.css'
    

    Should be:

    import * as styles from './related-products.modules.css'
    

    Keep in mind that this is not the recommended way of importing CSS modules, since you are not allowing webpack to treeshake your styles. Ideally, you should import the needed named modules like:

    import { style1, style2, style3 } from './related-products.modules.css'
    

    Regarding the new issue:

    I am getting this error while running locally : Module build failed (from ./node_modules/gatsby/node_modules/mini-css-extract-plugin/dist/loader.js): ValidationError: Invalid options object. Mini CSS Extract Plugin Loader has been initialized using an options object that does not match the API schema.

    Try adding the (dev)dependencies:

    yarn add --dev css-loader@^5.0.0 postcss@^8.1.10 postcss-import@^13.0.0 postcss-loader@^4.1.0 postcss-url@^10.1.1
    

    Or the equivalence in npm.