Git Product home page Git Product logo

webpack-remove-empty-scripts's Introduction

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 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

webpack-remove-empty-scripts's People

Contributors

fqborges avatar g-rath avatar lmcsu avatar mrrefactoring avatar thijstriemstra avatar webdiscus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

webpack-remove-empty-scripts's Issues

There's no up-to-date tracking of the version releases with tags and/or release

One of the projects I work on upgraded this package to a higher major version. Usually I have to verify the CHANGELOG to make sure the changes will not break the project.

I found a file in https://github.com/webdiscus/webpack-remove-empty-scripts/blob/master/CHANGELOG.md

But I also think it would be nice if you could track the changes using any the following:

  • branch for specific version
  • tag for the specific version
    • Seems like there were some tags, but they are out of date and the newer releases haven't been tagged. Last one was 0.8.0. Latest version on npmjs is 1.0.1
  • release entry (https://github.com/webdiscus/webpack-remove-empty-scripts/releases)
    • I saw the releases page is out of sync with the actual versions that have been released. Last one was for 0.8.0.

webpack-remove-empty-scripts is removing asset.php files

Describe the bug
The build process is running @WordPress/Scripts. This will also output an asset.php file for each CSS file generated.

I want to use that plugin to remove the .JS files that get created with the compiled CSS files. These .JS files are empty and just annoying to have in there.

When using the plugin it is also removing my asset.php files as well. I have tried the options including ignoring asset.php files but it still doesn't work.

Any ideas? Below is the code I have:

const otherStyleConfig = {
    ...defaultConfig,
    entry: {
        'blog': path.resolve( './src/sass', 'blog.scss' ),
    },
    module: {
        rules: [
        {
            test: /\.scss$/,
            exclude: /node_modules/,
            use: [
                MiniCssExtractPlugin.loader,
                {
                    loader: "css-loader",
                    options: {
                        url: false, //Don't do anything with image url's
                    },
                },
                {
                    loader: "postcss-loader",
                    options: {
                        postcssOptions: {
                            plugins: [
                                sortMediaQueries(),
                                presetEnv(),
                                mergeLonghand(),
                                mergeRules(),
                                cssnano( {
                                    reduceIdents: false,
                                    zindex: false,
                                    autoprefixer: false,
                                } ),
                            ],
                            options: {},
                        },
                     },
                },
                'resolve-url-loader',
                'sass-loader',
            ],
        },
        ],
    },
    output: {
        path: path.resolve(__dirname, 'build/css'),
    },
    devtool: 'source-map',
    plugins: [
        new MiniCssExtractPlugin(),
        new DependencyExtractionWebpackPlugin(),
        new RemoveEmptyScriptsPlugin({
            verbose: true,
            ignore: [
                /.*asset.php$/,
            ]
        }),
    ]
}

To Reproduce

  1. Create a simple SASS compile in Webpack config like the example above.
  2. Use @WordPress/Scripts for the build process. This should be in your package.json file "build": "wp-scripts build --mode=production",
  3. You will see the empty .js files are no longer there but the asset.php files are not there either. If you remove the plugin from the Webpack config you will see that the asset.php files are there and the empty .js files.

Expected behavior
To just remove the empty JS files and not asset.php files

Dev Environment (please complete the following information):

  • OS: MacOS
  • Node: v14.17.0

TypeScript support

Doesn't work with TS

import RemoveEmptyScriptsPlugin from 'webpack-remove-empty-scripts';

TS7016: Could not find a declaration file for module 'webpack-remove-empty-scripts'. '.../node_modules/webpack-remove-empty-scripts/src/index.js' implicitly has an 'any' type.

[BUG] removed empty file still processed by other plugins

Describe the bug
After upgrading to webpack-remove-empty-scripts v0.8.2 I'm facing this issue:

[webpack-cli] Error: ENOENT: no such file or directory, open 'static/js/css-06f62c46.bundle.min.js'
    at Object.openSync (node:fs:585:3)
    at Object.readFileSync (node:fs:453:35)
    at fileSum (/home/myuser/Devel/private/hugo/hugo-geekdoc/webpack.plugins.js:40:56)
    at calculateSRI (/home/myuser/Devel/private/hugo/hugo-geekdoc/webpack.plugins.js:42:25)
    at /home/myuser/Devel/private/hugo/hugo-geekdoc/webpack.plugins.js:46:29
    at Array.forEach (<anonymous>)
    at /home/myuser/Devel/private/hugo/hugo-geekdoc/webpack.plugins.js:44:25
    at Hook.eval [as callAsync] (eval at create (/home/myuser/Devel/private/hugo/hugo-geekdoc/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:9:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/home/myuser/Devel/private/hugo/hugo-geekdoc/node_modules/tapable/lib/Hook.js:18:14)
    at /home/myuser/Devel/private/hugo/hugo-geekdoc/node_modules/webpack/lib/Compiler.js:498:23 {
  errno: -2,
  syscall: 'open',
  code: 'ENOENT',
  path: 'static/js/css-06f62c46.bundle.min.js'
}

The static/js/css-06f62c46.bundle.min.js file is an empty js file created by a scss only entry in the webpack config:

  entry: {
    css: [
      path.resolve("src", "sass", "main.scss"),
      path.resolve("src", "sass", "mobile.scss"),
      path.resolve("src", "sass", "print.scss")
    ],

While everything was working as expected in v0.8.1 something has changed in v0.8.2+. Other plugins, In my case webpack-manifest-plugin, seems to be able to still see those empty scripts and try to process them even if webpack-remove-empty-scripts has successfully removed them, so this might be some kind of race condition. Looks like that's related to 0a5ec81. Any chance to get it fixed?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.