webpack - 使用 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-loader
为type: 'asset/resource'
. 我想知道我如何才能满足options
用于file-loader
. 如何设置公共和文件系统路径和文件名?
我曾尝试使用output
和generator.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 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]
。
推荐阅读
- javascript - Javascript SumOfTwo
- javascript - 将变量连接为函数内的输入名称
- codesandbox - 无法让 CSS 文件在 CodeSandbox 中工作
- php - Windows 上带有 xampp 1.5.5 和带有 apache 的 php 4.5 的本地网站。一些操作后,它不再工作了
- c# - 如何获取注入服务列表到控制器
- git - 提交到已合并的分支并打开新的拉取请求
- c++ - 试图引用已删除的函数 shared_ptr
- amazon-web-services - Elasticsearch 文档不可搜索
- java - 如何为包含 switch 语句的搜索方法返回 ArrayList
- java - SimpleStatement 作为 CQL