Webpack outputting too many files

23 Views Asked by At

Here is my webpack file:

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  entry: {
    index: './src/js/index.es6.js', // Entry point of your application
    edit: './src/scss/edit.scss',
    style: './src/scss/style.scss'
  },
  mode: 'development', // or 'production'
  output: {
    filename: '[name].js', // Use [name] placeholder to generate unique filenames
    path: path.resolve(__dirname, 'dist') // Output directory
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react']
          }
        }
      },
      {
        test: /\.svg$/,
        loader: 'file-loader' // or any other loader you want to use for SVG files
      },
      {
        test: /\.scss$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              publicPath: '../' // Adjust the public path for CSS files
            }
          },
          'css-loader',   // Turn CSS into CommonJS
          'sass-loader'   // Compile Sass to CSS
        ]
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: (pathData) => {
        // Use entry point name for CSS filenames
        return pathData.chunk.name === 'index' ? 'index.css' : `${pathData.chunk.name}.css`;
      }
    })
  ],
  devtool: 'source-map' // Generate CSS source maps
};

Here is my file structure:

  • /src/js/index.es6.js
  • /src/scss/edit.scss
  • /src/scss/style.scss

I want to out just the following files:

  • /dist/index.js
  • /dist/edit.css
  • /dist/style.css

But instead I'm getting additional files:

  • /dist/index.css
  • /dist/edit.js
  • /dist/style.js
1

There are 1 best solutions below

0
biodiscus On

Webpack generates a JS file for each resource defined in the entry option.

The mini-css-extract-plugin extract CSS from SCSS file defined in entry, but not eliminate a generated empty JS file.

To fix it, you can use the webpack-remove-empty-scripts plugin.

  1. Install
npm install webpack-remove-empty-scripts --save-dev
  1. Add the plugin in your Webpack config:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts'); // <= add it

module.exports = {
  entry: {
    index: './src/js/index.es6.js', // Entry point of your application
    edit: './src/scss/edit.scss',
    style: './src/scss/style.scss'
  },
  // ...
  plugins: [
    // removes the empty `.js` files generated by webpack
    new RemoveEmptyScriptsPlugin(),// <= add it here
    new MiniCssExtractPlugin({
      // ...
    })
  ],
  // ...
};