webpack-hasjs-plugin

1.0.4 • Public • Published

webpack-hasjs-plugin

This plugin performs has.js filtering on source modules based on a statically defined set of features. Feature conditionals who's values are defined in the static feature set are replaced with the value of the feature. The resulting dead code will then be pruned by the uglifier.

For example, the following code:

if (has('foo')) {
  console.log('foo');
} else {
  console.log('!foo');
}

with these options:

{
 features: {foo: true}
}

will yield the following output

if (true) {
  console.log('foo');
} else {
  console.log('!foo');
}

After the uglifier prunes dead code branches, only the call to console.log('foo') will remain. If a feature is not defined in the static feature set, then the code using that feature is unaffected unless the option coerceUndefinedToFalse is truthy, in which case the result will be as if the feature had been defined with a value of false. The values of the statically defined features may be number, boolean, or string. Any other types are ignored.

Install

npm i -D webpack-hasjs-plugin

Usage

// webpack.config.js
var HasJsPlugin = require('webpack-hasjs-plugin');

module.exports = {
  // ... snip ...
  plugins: [
    new HasJsPlugin({
			features: {
				foo: true,
				bar: false
			}
		})
  ],
  // ... snip ...
}

Options

features

Properties map of feature name/value pairs.

coerceUndefinedToFalse

If true, then any calls to the has function which specify a feature not declared in features will be treated as if the feature had been defined with a value of false.

Limitations

Due to limitations in the webpack parser, this plugin does not transform the source when the has() function call is a member of a comparison operator involving greater-than or less-than (e.g. if (has('ie') >= 10)), or, before webpack 5, if it used in an assignment (e.g. var foo = has('foo') && getFoo();). It does work, however, if the result of the ternary operator (e.g. var foo=has('foo')?getFoo():undefined;) is used in the assignment.

Fortunately, these problematic usage patterns are not common, and if they are encountered, the code is simply left alone, so they are not harmful.

Readme

Keywords

none

Package Sidebar

Install

npm i webpack-hasjs-plugin

Weekly Downloads

103

Version

1.0.4

License

(Apache-2.0)

Unpacked Size

6.6 kB

Total Files

7

Last publish

Collaborators

  • chuckdumont