npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

webpack-remove-empty-scripts

v1.0.4

Published

Webpack plugin removes empty JavaScript files generated when using styles.

Downloads

746,120

Readme


npm node node Test codecov node

The problem this plugin solves

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

For example, you have a style file in the entry option:

module.exports = {
  entry: {
    styles: './styles.scss',
  },
}

The following files are generated in the output directory:

dist/styles.css
dist/styles.js // <= unexpected empty JS file

This plugin removes generated empty JS files.

Warning

This plugin is the Emergency Crutch 🩼 for the mini-css-extract-plugin issue.
The mini-css-extract-plugin extract CSS, but not eliminate a generated empty JS file.

Note

This plugin is compatible with Webpack 5. For Webpack 4 use webpack-fix-style-only-entries.

Install

npm install webpack-remove-empty-scripts --save-dev

Usage with mini-css-extract-plugin

The example of webpack.config.js:

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts');

module.exports = {
  entry: {
    'main' : './app/main.js',
    'styles': ['./common/styles.css', './app/styles.css']
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
        ]
      },
    ]
  },
  plugins: [
    // removes the empty `.js` files generated by webpack
    new RemoveEmptyScriptsPlugin(),
    new MiniCssExtractPlugin({
      filename: '[name].[chunkhash:8].css',
    }),
  ],
};

See the plugin options.


Usage with html-webpack-plugin

✅ It is recommended to use the new powerful html-bundler-webpack-plugin instead of:

  • html-webpack-plugin
  • mini-css-extract-plugin
  • webpack-remove-empty-scripts

Highlights of html-bundler-webpack-plugin

  • Prevents generating unexpected empty JS files.
  • An entry point can be an HTML template.
  • Source scripts and styles can be specified directly in HTML using <script> and <link>.
  • Extracts JS and CSS from their sources specified in HTML.
  • Resolving source assets specified in standard attributes href src srcset etc.
  • Inline JS, CSS, SVG, PNG without additional plugins and loaders.
  • Support for template engines such as Eta, EJS, Handlebars, Nunjucks, LiquidJS and others.

Simple usage example

Add source scripts and styles directly to HTML:

<html>
<head>
  <!-- specify source styles -->
  <link href="./style.scss" rel="stylesheet">
  <!-- specify source scripts here and/or in body -->
  <script src="./main.js" defer="defer"></script>
</head>
<body>
  <h1>Hello World!</h1>
  <!-- specify source images -->
  <img src="./logo.png">
</body>
</html>

The generated HTML contains the output filenames of the processed assets:

<html>
<head>
  <link href="assets/css/style.05e4dd86.css" rel="stylesheet">
  <script src="assets/js/main.f4b855d8.js" defer="defer"></script>
</head>
<body>
  <h1>Hello World!</h1>
  <img src="assets/img/logo.58b43bd8.png">
</body>
</html>

Add the HTML templates in the entry option:

const HtmlBundlerPlugin = require('html-bundler-webpack-plugin');

module.exports = {
  plugins: [
    new HtmlBundlerPlugin({
      // define a relative or absolute path to template pages
      entry: 'src/views/',
      // OR define templates manually
      entry: {
        index: 'src/views/home.html', // => dist/index.html
        'news/sport': 'src/views/news/sport/index.html', // => dist/news/sport.html
      },
    }),
  ],
  // ... loaders for styles, images, etc.
};

Options

enabled

Type: boolean Default: true Enable / disable the plugin. Tip: Use disable for development to improve performance.

stage

Type: number Values:

  • RemoveEmptyScriptsPlugin.STAGE_BEFORE_PROCESS_PLUGINS (default)
    Remove empty scripts before processing other plugins.
    For example, exact this stage needs for properly work of the webpack-manifest-plugin.
  • RemoveEmptyScriptsPlugin.STAGE_AFTER_PROCESS_PLUGINS
    Remove empty scripts after processing all other plugins.
    For example, exact this stage needs for properly work of the @wordpress/dependency-extraction-webpack-plugin.

Webpack plugins use different stages for their functionality. For properly work other plugins can be specified the stage when should be removed empty scripts: before or after processing of other Webpack plugins.

See usage example.

Warning

Because webpack-manifest-plugin and @wordpress/dependency-extraction-webpack-plugin needs different stages both plugins can't be used together with RemoveEmptyScriptsPlugin at one configuration.

extensions

Type: RegExp Default: /\.(css|scss|sass|less|styl)([?].*)?$/ Note: the Regexp should have the query part at end ([?].*)?$ to match assets like style.css?key=val Type: string[] Default: ['css', 'scss', 'sass', 'less', 'styl']. It is automatically converted to type RegExp.
Search for empty js files in source files only with these extensions.

ignore

Type: string | RegExp | string[] | RegExp[] Default: null Ignore source files.

remove

Type: RegExp Default: /\.(js|mjs)$/ Remove generated scripts.

verbose

Type: boolean Default: false Show process information.

Recipes

Show logs to console by development

const isProduction = process.env.NODE_ENV === 'production';
new RemoveEmptyScriptsPlugin({ verbose: isProduction !== true })

Disable plugin by development to improve performance

const isProduction = process.env.NODE_ENV === 'production';
new RemoveEmptyScriptsPlugin({ enabled: isProduction === true })

Specify stage for properly work some plugins

For example, using @wordpress/dependency-extraction-webpack-plugin the empty scripts must be removed after processing all plugins.

const path = require('path');
const DependencyExtractionWebpackPlugin = require('@wordpress/dependency-extraction-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts');

module.exports = {
  output: {
    path: path.join(__dirname, 'public'),
  },
  entry: {
    'main': './src/sass/main.scss',
  },
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin(),
    new DependencyExtractionWebpackPlugin(),
    new RemoveEmptyScriptsPlugin({
      stage: RemoveEmptyScriptsPlugin.STAGE_AFTER_PROCESS_PLUGINS, // <- use this option
    }),
  ],
};

Identify only .foo and .bar extensions as styles

new RemoveEmptyScriptsPlugin({ extensions: /\.(foo|bar)$/ })

Usage a javascript entry to styles

Give an especial extension to your file, for example .css.js:

new RemoveEmptyScriptsPlugin({ extensions: /\.(css.js)$/ })

Remove generated scripts *.js *.mjs except *.rem.js *.rem.mjs

new RemoveEmptyScriptsPlugin({ remove: /(?<!\.rem)\.(js|mjs)$/ })

Recursive ignore all js files from directory, for example my-workers/

new RemoveEmptyScriptsPlugin({
  ignore: [
    /my-workers\/.+\.js$/,
  ]
})

Usage webpack-hot-middleware

new RemoveEmptyScriptsPlugin({
  ignore: [
    'webpack-hot-middleware',
  ]
})

See the test case.

Testing

npm run test will run the unit and integration tests.
npm run test:coverage will run the tests with coverage.

Who use this plugin

Also See

  • ansis - The Node.js library for ANSI color styling of text in terminal.
  • html-bundler-webpack-plugin - HTML bundler plugin for webpack handels a template as an entry point, extracts CSS and JS from their sources specified in HTML, supports template engines like Eta, EJS, Handlebars, Nunjucks and others "out of the box".
  • pug-plugin - plugin for Webpack compiles Pug files to HTML, extracts CSS and JS from their sources specified in Pug.
  • pug-loader - loader for Webpack renders Pug to HTML or template function. Optimized for using with Vue.

License

ISC