Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain src folder structure into dist folder with Webpack?

I'm studying Webpack and I am facing this issue. When i run the build task "npm run build", webpack creates the dist folder. The problem is that the dist folder doesn't respect the src folder, and Webpack puts all files into the root folder (the dist folder). So I have *.html pages near the style file and all the images. I want html files inside dist, images inside img (img inside dist) and so on...

This is my webpack.config.js file:

const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [{
      test: /\.js$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
      },
    },
    {
      test: /\.html$/,
      use: [{
        loader: 'html-loader',
        options: {
          minimize: true,
        },
      }],
    },
    {
      test: /\.(css|scss)$/,
      use: [
        MiniCssExtractPlugin.loader,
        {
          loader: 'css-loader',
          options: {
            importLoaders: 1,
            sourceMap: true,
            url: false,
            minimize: true,
          },
        },
        {
          loader: 'postcss-loader',
          options: {
            sourceMap: true,
          },
        },
        {
          loader: 'sass-loader',
        },
      ],
    },
    {
      test: /\.(png|svg|jpg|gif)$/,
      use: [{
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
        },
      }],
    },
    ],
  },
  plugins: [
    new HtmlWebPackPlugin({
      template: './src/index.html',
      filename: 'index.html',
    }),
    new HtmlWebPackPlugin({
      template: './src/work.html',
      filename: 'work.html',
    }),
    new MiniCssExtractPlugin({
      filename: '[name].[hash].css',
    }),
    new CleanWebpackPlugin(['dist']),
  ],
};

I found something on the Internet but all solutions didn't work. Maybe I made something wrong? Please help me.

like image 475
lewis Avatar asked Oct 26 '25 09:10

lewis


1 Answers

  ...
  module: {
    rules: [
     ...
    {
      test: /\.(png|svg|jpg|gif)$/,
      use: [{
        loader: 'file-loader',
        options: {
          name: 'img/[name].[ext]',
        },
      }],
    },
    ],
  },
  plugins: [
    ...
    new MiniCssExtractPlugin({
      filename: 'styles/[name].[contenthash].css',
    }),
  ],
};

You just add paths to the name

like image 124
PlayMa256 Avatar answered Oct 28 '25 22:10

PlayMa256



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!