Détail du package

webpack-remove-empty-scripts

webdiscus797.5kISC1.0.4

Webpack plugin removes empty JavaScript files generated when using styles.

webpack, plugin, remove, empty

readme

webpack-remove-empty-scripts

The Webpack plugin removes empty JavaScript files generated when using styles.

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

changelog

1.0.4 (2023-08-28)

  • fix: remove needless double new lines in console output when the verbose option is enabled
  • chore: add Community Standards files
  • chore: update dev packages
  • test: remove the test strategy for node versions 12.x on GitHub to allows use the latest dev packages. The plugin is still compatible with node 12.x.
  • test: add the test strategies for node versions 18.x and 20.x on GitHub
  • test: refactor test utilities
  • test: add tests for alternative way using the html-bundler-webpack-plugin
  • docs: update readme

1.0.3 (2023-04-11)

  • fix: fix interface syntax in TS
  • fix: options in constructor now is optional parameter in types for TS.

1.0.2 (2023-04-07)

  • fix: correctly export types for TS when used CommonJS
  • chore: update dev packages
  • docs: update readme

1.0.1 (2022-09-19)

  • docs: update readme

1.0.0 (2022-09-12)

  • BREAKING CHANGE: reverted default behavior as in v0.8.1 - remove empty scripts before other plugins will be called. This change is needs for properly work of the vast majority of webpack plugins.

    For compatibility with v0.8.2 - v0.8.4, if you have an issue, use new stage option with the value:

    new RemoveEmptyScriptsPlugin({
      stage: RemoveEmptyScriptsPlugin.STAGE_AFTER_PROCESS_PLUGINS,
    })
  • feat: add new stage option. Webpack's 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.\ For example, using @wordpress/dependency-extraction-webpack-plugin the empty scripts must be removed after processing all plugins. Using webpack-manifest-plugin the empty scripts must be removed before processing other plugins.
  • chore: update packages
  • test: add the test for using with webpack-manifest-plugin
  • docs: update readme

0.8.4 (2022-09-08)

  • fix: fix last stable version of ansis in package.json to avoid issues in dependency

0.8.3 (2022-09-04)

  • docs: update readme

0.8.2 (2022-09-04)

  • fix: keep extracted wordpress dependencies, #9
  • test: refactor tests
  • chore: update npm packages

0.8.1 (2022-06-14)

  • fix: add supports for TypeScript
  • chore: update packages
  • docs: update readme

0.8.0 (2022-04-01)

  • feat: add new option remove to define custom RegExp for generated assets that must be removed
  • chore: update packages

0.7.3 (2022-01-30)

  • feat: add color verbose output via ANSI color library - ansis
  • feat: add the test case for styles imported from javascript

0.7.2 (2021-12-13)

  • feat: add new option enable to enable / disable the plugin, e.g. by development
  • feat: add supports of RegExp for option extensions
  • chore: remove deprecated option silent, use verbose to show process information (no braking change)
  • chore: add GitHub workflow + codecov
  • chore: update packages
  • docs: update readme

0.7.1 (2021-01-14)

  • fix: the issue infinite recursion by collect of resources from dependency modules by usage in react app some big components with many thousands dependencies

0.7.0 (2020-12-21)

  • chore: deprecate the silent option, it will be removed on Jun 30, 2021. Use option verbose: true to show in console each removed empty file. Defaults, verbose: false.
  • fix: issue Maximum call stack size exceeded in all cases, for example, by usage the webpack setting optimization.concatenateModules: true and:
    • import react
    • import redux
    • webpack setting externals.jquery: 'jQuery' or other external libs
  • fix: the issue if first in webpack entries are a styles and then a scripts

0.6.4 (2020-12-19)

  • feat: improve the option ignore:
    • it can be the array of string or RegExp
    • added default value of ignore as ['/node_modules/'] to ignore resources from node_modules path
  • fix: the error: Maximum call stack size exceeded with webpack setting optimization.concatenateModules: trueand usage in script imports from react and redux
  • test: add the test case for single style without a scripts in webpack config
  • test: add silent mode in tests to suppress output log info in the console
  • chore: update packages

0.6.3 (2020-10-25)

  • fix: BREAKING CHANGE in Webpack 5: no more changes should happen to Compilation.assets
  • refactor: update code according Webpack 5 API

0.6.2 (2020-10-24)

  • chore: update packages

0.6.1 (2020-10-20)

The fork of original webpack-fix-style-only-entries (ver. 0.6.0) for support only Webpack 5 and above. The Webpack 4 is no longer supported.

The changes from original version 0.6.0:

  • feat: considers the use hash after the .js and .mjs extension in file format like .js?[hash] or .mjs?[hash]. The idea and requirement belong to MatiasMorici from PR
  • fix: in Webpack 5 fixed deprecation messages:

    • DEP_WEBPACK_CHUNK_HAS_ENTRY_MODULE
    • DEP_WEBPACK_CHUNK_ENTRY_MODULE
    • DEP_WEBPACK_DEPRECATION_ARRAY_TO_SET
    • DEP_WEBPACK_MODULE_INDEX
  • fix: integration test script for using with Webpack 5

  • fix: issue using terser-webpack-plugin is generated the needless file vendor.js.LICENSE.txt in the production test vendor+multi-js-entry-css-entry
  • docs: corrected module structure in README.md
  • chore: update packages

0.6.0 (Oct 13, 2020)

Being overly careful here, this version is not breaking for almost all the existing users. It could possibly break in some edge cases, since it changes how modules are collected (from global to one each compilation) or if you have a workaround for a working webpack multi configuration.

  • BREAKING POSSIBLY: Use a dedicated cache for every compilation (Prevent arbitrary files deletion when using Webpack with multi configurations) (PR #39)

0.5.2 (Oct 07, 2020)

  • feat: supports Webpack 5 using ModuleGraph API (PR #38)
  • chore: npm audit fix: (ea9dd7)

0.5.1 (Jun 13, 2020)

  • fix: Maximum call stack size exceeded (PR #34)
  • chore: add CHANGELOG (3e3767)

0.5.0 (May 18, 2020)

0.4.0 (Sep 8, 2019)

  • feat: add support for module js files (PR #21)