Search code examples
css-loaderwebpack-4mini-css-extract-plugin

How to skip Javascript output in Webpack 4?


I use Webpack 4 in a project where I only need to compile and bundle styles so far. There's no Javascript.

Here's the config I have:

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

module.exports = {
  entry: {
    'css/bundle': path.resolve(__dirname, 'static/scss/index.scss'),
  },
  output: {
    path: path.resolve(__dirname, 'static'),
  },
  module: {
    rules: [
      {
        test: /\.s[ac]ss$/,
        include: path.resolve(__dirname, 'static/scss'),
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin(),
  ],
};

The problem is that it outputs two files: bundle.css and bundle.js. Is there a way to configure Webpack so that it doesn't output the Javascript bundle? I tried to navigate the docs, tried a dozen different things, but it didn't really work.

One important note here is that if I remove the css-loader, bundling fails. So while css-loader is most likely responsible for outputting the bundle.js file, I'm not entirely sure how to avoid using it.


Solution

  • March 2021:

    In Webpack 5, on-build-webpack plugin did not work for me.

    I found this:

    Webpack Shell Plugin Next

    The project I’m working on we’re using Webpack 5 as a build tool for a CSS pattern library. Therefore, we didn’t need the main.js in our dist.

    Run npm i -D webpack-shell-plugin-next

    Then in webpack.config.ts (just showing the pertinent parts):

    import WebpackShellPluginNext from "webpack-shell-plugin-next";
    
    module.exports = {
        output: {
            path: path.resolve(__dirname, "static/dist")
        },
        plugins: [
            // Run commands before or after webpack 5 builds:
            new WebpackShellPluginNext({
                onBuildEnd: {
                    scripts: [
                        () => {
                            fs.unlinkSync(path.join(config.output.path, "main.js"));
                        }
                    ]
                }
            })
        ]
    };
    
    export default config;