Search code examples
webpacksubdirectorywebpack-5

Preserve subdirectories in webpack 5


I had a question and I did not find anything (for WebPack 5)
I created a folder called svg inside of my images folder, but when webpack compiles it into the dist folder, all of the images get flattened into that one images folder.
Is there something to be able preserve subdirectories? (in webpack 5)

{
    test: /\.(png|jpe?g|gif|webp)$/i,
    type: "asset/resource",
    generator: {
        filename: "images/[name][ext]",
    },
}

Thanks


Solution

  • I found the solution,
    The filename property can be a function, and with this property we can get the full path, which with a few changes can preserve subdirectories.

    {
        test: /\.(png|jpe?g|gif|webp)$/i,
        type: "asset/resource",
        generator: {
            filename: (name) => {
                /**
                 * @description Remove first & last item from ${path} array.
                 * @example
                 *      Orginal Path: 'src/images/avatar/image.jpg'
                 *      Changed To: 'images/avatar'
                 */
                const path = name.filename.split("/").slice(1, -1).join("/");
                return `${path}/[name][ext]`;
            },
        },
    }
    

    Thanks to @felixmosh