首页 > 解决方案 > 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,并且不会将图像发送到正确的文件夹。

标签: javascriptwebpack

解决方案


您只需要在 if 语句中添加您的文件夹名称。如果您的文件夹树如下所示:

/src/图像/子文件夹/

将您的代码更改为:

outputPath: (url, resourcePath) => {
                 if (/subfolder/.test(resourcePath)) {
                     return `images/subfolder/${url}`;
                 }
             return `images/${url}`;
             }

推荐阅读