javascript - Webpack 文件加载器,如何使用 outputPath 函数
问题描述
我一直在一个项目中工作,我需要使用文件加载器中的 outputPath 函数,将文件发送到不同的文件夹,但我很难理解并使其工作。
我的部分代码如下:
const path = require('path');
const webpack = require('webpack');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const fs = require('fs'); // fs stands for file system, it helps accessing phyisical file systems
const BRANDS = {
br1: 'br1.local',
b22: 'br2.local'
};
module.exports = {
mode: 'production',
entry: {
main: './src/js/main.js'
},
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.(png|jpg|gif)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]',
outputPath: (url, resourcePath, context) => {
if (/my-custom-image\.png/.test(resourcePath)) {
return `other_output_path/${url}`;
}
if (/images/.test(context)) {
return `image_output_path/${url}`;
}
return `output_path/${url}`;
}
}
},
]
},
文档说resourcePath是资产的绝对路径,我对此不确定,因为我的资产文件夹有另一个名称而不是资产,这有关系吗?它看起来像:/src/images。什么是上下文不确定我的上下文是什么。当我对这些参数执行 console.log 时,它会显示undefined,并且不会将图像发送到正确的文件夹。
解决方案
您只需要在 if 语句中添加您的文件夹名称。如果您的文件夹树如下所示:
/src/图像/子文件夹/
将您的代码更改为:
outputPath: (url, resourcePath) => {
if (/subfolder/.test(resourcePath)) {
return `images/subfolder/${url}`;
}
return `images/${url}`;
}
推荐阅读
- java - 将解析的 JSONArray 加载到 recyclerView
- swift - 如何更新视图中结构的值
- java - ArrayList的Java While循环无法获取Array中的数据
- c# - 需要提升权限的应用程序的 DragDrop
- python - Python 在 Mac 上使用错误的版本
- html - 查看 HTML 过去是如何出现的?
- linux - 编译 HPL Linpack 基准测试时禁用矢量化
- flutter - 当在另一个有状态小部件中单击按钮时,如何在一个有状态小部件中设置状态?
- vb.net - 是否可以在 VB ListBox 中使用 MultipleColumn
- javascript - 为什么这个 if 语句会导致这个 JS 代码出现问题?