Home > database >  Webpack5 is unable to compile images while is running and raise an error
Webpack5 is unable to compile images while is running and raise an error

Time:09-24

I am using webpack5 config to run a react repository and everything seems to be working fine except loading images, I have an error that I do not understand:

ERROR in ./src/assets/styles/main.scss
Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleNotFoundError: Module not found: Error: Can't resolve 'file-loader' in '/Users/user.user/Desktop/react-boilerplate-master'

I have tried to reinstall the mini-css-extract-plugin butt didn't worked, not sure what could be the problem here.

This is the webpack config:

const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

const {
  NODE_ENV: nodeEnv = 'development'
} = process.env;
const devMode = nodeEnv !== "production";
const pkg = require("./package.json");

module.exports = {
  entry: {
    app: "./src/index.js",
    vendor: Object.keys(pkg.dependencies)
  },
  output: {
    filename: devMode ? "[name].js" : "[name].[hash].js",
    path: path.resolve(__dirname, "dist"),
    chunkFilename: devMode ? "[name].js" : "[name].[chunkhash].js",
    publicPath: "/"
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          test: /[\\/]node_modules[\\/]/,
          chunks: "all"
        }
      }
    }
  },
  devServer: {
    historyApiFallback: {
      index: "/index.html",
      port: 3001
    }
  },
  watchOptions: {
    poll: true
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: '[path][name].[ext]?[contenthash]',
              outputPath: 'images/',
            },
          },
        ],
      },
      {
        test: /\.(woff(2)?|ttf|eot|otf|svg)(\?v=\d \.\d \.\d )?$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              outputPath: "fonts/",
            },
          },
        ],
      },
      {
        test: /\.scss|css$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: "css-loader",
            options: { url: false }
          },
          {
            loader: "sass-loader",
            options: {
              sassOptions: {
                includePaths: ["src/styles/"]
              }
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new MiniCssExtractPlugin({
      filename: devMode ? "[name].css" : "[name].[hash].css",
      chunkFilename: devMode ? "[id].css" : "[id].[hash].css"
    }),
    new HtmlWebpackPlugin({
      filename: "index.html",
      chunks: ["vendor", "app"],
      template: path.join(__dirname, "public", "index.html")
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(nodeEnv),
      'process.env.API_PATH': JSON.stringify(process.env.API_PATH)
    })
  ]
};



and the package.json scripts:

``` "scripts": {
    "start": "./node_modules/webpack/bin/webpack.js --mode development",
    "build": "./node_modules/webpack/bin/webpack.js --mode production",
    "start:watch": "./node_modules/webpack/bin/webpack.js --mode development --watch",
    "dev": "webpack serve --mode development --open",
    "test": "./node_modules/jest/bin/jest.js --env=jsdom",
    "test:watch": "./node_modules/jest/bin/jest.js --watch --env=jsdom --verbose",
    "test:watch:log": "TERM=dumb ./node_modules/jest/bin/jest.js --watch --env=jsdom --verbose",
    "coverage": "npm test -- --coverage",
    "eslint": "eslint ./src",
    "profile": "./node_modules/webpack/bin/webpack.js --profile --json > stats.json",
    "profile:analyze": "./node_modules/.bin/webpack-bundle-analyzer ./stats.json"
  },```

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/AZH7s.png

CodePudding user response:

Looks like I can reproduce your issue with the above setup. It's very likely an issue from using file-loader in webpack 5.

Basically webpack has urged to use asset module in favor of kind of traditional loader like file-loader.

In short, it should be working if you replace the file-loader with asset module like:

{
  test: /\.(png|jpg|gif|svg)$/,
  type: 'asset/resource',
  // use: [
  //   {
  //     loader: 'file-loader',
  //     options: {
  //       name: '[path][name].[ext]?[contenthash]',
  //       // outputPath: 'images/',
  //     },
  //   },
  // ],
},
  • Related