1

I have been working in a project where I need to use the outputPath function from the file-loader, to emit files to different folders, but I had difficulties to understand and making it work.

Part of my code is as follows:

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}`;
                }
            }
        },


    ]
},

documentation says that resourcePath is the absolute path to assets, I am not sure about this, as my assets folder has another name not assets, does it matter? it looks like: /src/images. What is context not sure what is my context. When I do a console.log of these arguments it shows undefined, and it doesn't emit the images to the right folders.

1

1 Answer 1

4

You just need to add your folder name inside if statement. If your folder tree looks like this:

/src/images/subfolder/

Change your code to this:

outputPath: (url, resourcePath) => {
                 if (/subfolder/.test(resourcePath)) {
                     return `images/subfolder/${url}`;
                 }
             return `images/${url}`;
             }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.