首页 > 解决方案 > 在 webpack 5 中保留子目录

问题描述

我有一个问题,我没有找到任何东西(对于 WebPack 5)我在我的文件
夹中创建了一个名为的文件夹,但是当 webpack 将它编译到该文件夹​​中时,所有图像都被展平到那个图像文件夹中。 有什么东西可以保存子目录吗?(在 webpack 5 中)svgimagesdist

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

谢谢

标签: webpacksubdirectorywebpack-5

解决方案


我找到了解决方案,
filename属性可以是一个函数,通过这个属性我们可以获得完整路径,只需进行一些更改就可以保留子目录。

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

感谢@felixmosh


推荐阅读