【问题标题】:Configure file-loader options with Webpack 5 for Next.js使用 Webpack 5 for Next.js 配置文件加载器选项
【发布时间】:2021-07-27 20:02:38
【问题描述】:

我正在尝试将 Nextjs 应用程序从 Webpack 4 升级到 Webpack 5。 目前我在 next.config.js 中使用file-loader 和选项:

// 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]',
            }
          },
        ]
      },
    ]
  }
};

根据Asset Modules 指令,我应该将file-loader 更改为type: 'asset/resource'。我想知道如何才能满足file-loader 中使用的options。如何设置公共和文件系统路径和文件名?

我尝试使用 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]'
        }
      },
    ]
  }
};

【问题讨论】:

    标签: webpack next.js


    【解决方案1】:

    你确定你正确覆盖了 webpack 配置吗?我希望 next.config.js 更改而不是 webpack.config.js

    这里有一篇关于在 next.js 中自定义 webpack 配置的不同部分的文章: https://dev.to/marcinwosinek/how-to-add-resolve-fallback-to-webpack-5-in-nextjs-10-i6j

    【讨论】:

      【解决方案2】:

      这是 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] 之间加上句号。

      【讨论】:

      • 这在下一个版本 12.0.7 上没有任何作用,它对其他人有用吗?
      猜你喜欢
      • 2021-05-13
      • 2022-08-03
      • 2023-03-15
      • 2020-09-25
      • 2018-02-27
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 2016-10-18
      相关资源
      最近更新 更多