我正在尝试将 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]',
}
},
]
},
]
}
};
Run Code Online (Sandbox Code Playgroud)
根据资产模块说明我应该更改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]'
}
},
]
}
};
Run Code Online (Sandbox Code Playgroud)
这对我有用。
// 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]',
}
},
]
},
]
}
};
Run Code Online (Sandbox Code Playgroud)
小智 13
以下是 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;
}
};
Run Code Online (Sandbox Code Playgroud)
注意不要在[hash]和之间添加句号[ext]。
您确定正确覆盖了 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
| 归档时间: |
|
| 查看次数: |
12981 次 |
| 最近记录: |