Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure file-loader options with Webpack 5 for Next.js

I'm trying to upgrade Nextjs app from Webpack 4 to Webpack 5. Currently I use file-loader with options in next.config.js:

// next.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.(jpe?g|png|svg|gif|ico|eot|ttf|woff|woff2|mp4|pdf|webm|txt)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              context: '',
              outputPath: 'static',
              publicPath: '_next/static',
              name: '[path][name].[hash].[ext]',
            }
          },
        ]
      },
    ]
  }
};

According to Asset Modules instruction I should change file-loader into type: 'asset/resource'. I wonder how I can satisfy options used in file-loader. How can I set public and filesystem path and filename as well?

I have tried to use output and generator.filename configuration but completely I have no idea where I should put public and filesystem path for Next.js :

module.exports = {
  output: {
     filename: '[path][name].[hash].[ext]',
     path: path.resolve(__dirname, 'static')
  },
  module: {
    rules: [
      {
        test: /\.(jpe?g|png|svg|gif|ico|eot|ttf|woff|woff2|mp4|pdf|webm|txt)$/,
        type: 'asset/resource',
        generator: {
          filename: '_next/static/[path][name].[hash].[ext]'
        }
      },
    ]
  }
};

Answer

This works for me.

// next.config.js
module.exports = {
  webpack: (config, options) => {
    config.module.rules.push(      {
      test: /\.(jpe?g|png|svg|gif|ico|eot|ttf|woff|woff2|mp4|pdf|webm)$/,
      type: 'asset',
      generator: {
        filename: 'static/chunks/[path][name].[hash][ext]'
      },
    });

      return config;
  }
};
like image 213
Aga Avatar asked May 05 '21 13:05

Aga


Video Answer


1 Answers

Here is the correct configuration of Asset Module in Webpack 5:

// next.config.js
module.exports = {
    webpack: (config, options) => {
        config.module.rules.push({
            test: /\.(jpe?g|png|svg|gif|ico|eot|ttf|woff|woff2|mp4|pdf|webm|txt)$/,
            type: 'asset/resource',
            generator: {
                filename: 'static/chunks/[path][name].[hash][ext]'
            },
        });

        return config;
    }
};

Be careful not to put a period between [hash] and [ext].

like image 69
Kacper Podpora Avatar answered Oct 17 '22 05:10

Kacper Podpora