在 Webpack 中重定向字体资源到自定义文件夹,可以通过配置 file-loader
或 url-loader
来实现。以下是几种常见的配置方法:
module.exports = {
module: {
rules: [
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/' // 自定义文件夹路径
}
}
]
}
]
}
};
module.exports = {
module: {
rules: [
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192, // 小于8KB的字体转为base64
name: '[name].[ext]',
outputPath: 'fonts/' // 自定义文件夹路径
}
}
]
}
]
}
};
如果你使用的是 Webpack 5,可以使用内置的资源模块:
module.exports = {
module: {
rules: [
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
generator: {
filename: 'fonts/[name][ext]' // 自定义文件夹路径
}
}
]
}
};
如果需要为字体资源添加公共路径:
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/',
publicPath: '../fonts/' // 相对于CSS文件的路径
}
}
name: '[name].[hash:8].[ext]'
以上配置可以根据你的具体项目需求进行调整。