Lowtrux
Lowtrux

Reputation: 208

Webpack4 : Moving / Importing Image Folder from "SRC folder" to "DIST folder"

I'm trying to import (move) my image folder from my src folder to my dist folder with Webpack 4 but unlike Gulp, this task looks SO complicated in Webpack even when I'm not even trying to mess around with the images at the moment, I just want Webpack to load them and put them on my dist/image folder.

I've seen that people import image by image on their index.js which I refuse to believe is the only solution, is there a way to just move the whole folder to the dist / production folder without having to import file by file on the index.js ?

This is my webpack config at the moment:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WebpackMd5Hash = require('webpack-md5-hash');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
    entry: path.resolve(__dirname, 'src/js/scripts.js'),
    output: {
        path: path.resolve(__dirname,'dist'),
        filename: '[name].[chunkhash].js'
    },
    module: {
        rules: [
            //JS
            {
                //Tipo de Archivo quiero reconocer
                test: /\.js$/,
                exclude: /node_modules/,
                //Que Loader se encarga del tipo de extension de archivo
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets:['babel-preset-env']
                    }
                },
            },           
            //IMAGES
            {
                test: /\.(jpg|png|gif)$/,
                use: {
                    loader: 'file-loader',
                    options: {
                        outputPath: 'images/',
                        name:'[name][hash].[ext]', 
                    }
                }
            },                       
            //SASS
            {
                test: /\.scss$/,
                use: ['style-loader', MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader']
            }           
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename:'css/style.min.[contenthash].css',
        }),
        new HtmlWebpackPlugin ({
            inject: false,
            hash: true,
            template: './src/index.html',
            filename: 'index.html'        
        }),
        new WebpackMd5Hash()   
    ]
}

I'm not pasting my index.js file because I just don't know what to do there since I won't be importing image by image. Looking forward for your thoughts.

Upvotes: 5

Views: 3386

Answers (1)

Legends
Legends

Reputation: 22662

The following statement should output all images in folder images to dist.

require.context("../images/", true, /\.(png|svg|jpg|gif)$/);

Upvotes: 3

Related Questions