簡體   English   中英

Webpack 文件加載器,如何使用 outputPath function

[英]Webpack file-loader, how to use outputPath function

我一直在一個項目中工作,我需要使用文件加載器中的 outputPath function 將文件發送到不同的文件夾,但我很難理解並使其工作。

我的部分代碼如下:

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 什么是上下文不確定我的上下文是什么。 當我對這些 arguments 執行 console.log 時,它顯示undefined ,並且不會將圖像發送到正確的文件夾。

您只需要在 if 語句中添加您的文件夾名稱。 如果您的文件夾樹如下所示:

/src/圖像/子文件夾/

將您的代碼更改為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM