【问题标题】:Webpack file-loader, how to use outputPath functionWebpack 文件加载器,如何使用 outputPath 函数
【发布时间】:2020-03-15 22:57:50
【问题描述】:

我一直在一个项目中工作,我需要使用文件加载器中的 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,并且不会将图像发送到正确的文件夹。

【问题讨论】:

标签: javascript webpack


【解决方案1】:

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

/src/images/子文件夹/

将您的代码更改为:

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

【讨论】:

    猜你喜欢
    • 2019-05-20
    • 2016-10-06
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    • 2022-10-30
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    相关资源
    最近更新 更多