首页 > 解决方案 > 使用 Webpack 5 for Next.js 配置文件加载器选项

问题描述

我正在尝试将 Nextjs 应用程序从 Webpack 4 升级到 Webpack 5。目前我使用file-loader 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]',
            }
          },
        ]
      },
    ]
  }
};

根据资产模块说明,我应该更改file-loadertype: 'asset/resource'. 我想知道我如何才能满足options用于file-loader. 如何设置公共和文件系统路径和文件名?

我曾尝试使用outputgenerator.filename配置,但完全不知道应该将 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]'
        }
      },
    ]
  }
};

标签: webpacknext.js

解决方案


下面是 Webpack 5 中 Asset Module 的正确配置:

// 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;
    }
};

注意不要在 和 之间加上[hash]句号[ext]


推荐阅读