Repository: webpack-contrib/uglifyjs-webpack-plugin (js)

Issue:
Expose chunk to `options.<test|include|exclude>`
The `test`, `include` and `exclude` options only inspect the output filename, which has no value when the names are like `[hash].[ext]`. It would be very helpful to expose the associated chunk info as well.



Pull request:
feat: `chunkFilter` option for filtering chunks
<!--
  HOLY CRAP a Pull Request. We ❤️ those!

  If you remove or skip this template, you'll make the 🐼 sad and the mighty god
  of Github will appear and pile-drive the close button from a great height
  while making animal noises.

  Please place an x (no spaces!) in all [ ] that apply
-->

This PR contains a:

- [ ] **bugfix**
- [x] new **feature**
- [ ] **code refactor**
- [x] **test update** <!-- if bug or feature is checked, this should be too -->
- [ ] **typo fix**
- [ ] **metadata update**

### Motivation / Use-Case

Allowing to filter `chunks`

fixes #21

### Breaking Changes

No

### Additional Info

No

Patch:
diff --git a/README.md b/README.md
index 1743093..bccfef4 100644
--- a/README.md
+++ b/README.md
@@ -109,6 +109,35 @@ module.exports = {
 };
 ```
 
+### `chunkFilter`
+
+Type: `Function<(chunk) -> boolean>`
+Default: `() => true`
+
+Allowing to filter which chunks should be uglified (by default all chunks are uglified).
+Return `true` to uglify the chunk, `false` otherwise.
+
+**webpack.config.js**
+
+```js
+module.exports = {
+  optimization: {
+    minimizer: [
+      new UglifyJsPlugin({
+        chunkFilter: (chunk) => {
+          // Exclude uglification for the `vendor` chunk
+          if (chunk.name === 'vendor') {
+            return false;
+          }
+          
+          return true;
+        }
+      }),
+    ],
+  },
+};
+```
+
 ### `cache`
 
 Type: `Boolean|String`
diff --git a/src/index.js b/src/index.js
index ccb9e49..cbf498e 100644
--- a/src/index.js
+++ b/src/index.js
@@ -23,6 +23,7 @@ class UglifyJsPlugin {
       minify,
       uglifyOptions = {},
       test = /\.js(\?.*)?$/i,
+      chunkFilter = () => true,
       warningsFilter = () => true,
       extractComments = false,
       sourceMap = false,
@@ -35,6 +36,7 @@ class UglifyJsPlugin {
 
     this.options = {
       test,
+      chunkFilter,
       warningsFilter,
       extractComments,
       sourceMap,
@@ -165,7 +167,10 @@ class UglifyJsPlugin {
       const processedAssets = new WeakSet();
       const tasks = [];
 
+      const { chunkFilter } = this.options;
+
       Array.from(chunks)
+        .filter((chunk) => chunkFilter && chunkFilter(chunk))
         .reduce((acc, chunk) => acc.concat(chunk.files || []), [])
         .concat(compilation.additionalChunkAssets || [])
         .filter(ModuleFilenameHelpers.matchObject.bind(null, this.options))
diff --git a/src/options.json b/src/options.json
index 8cdf2e3..0e592b6 100644
--- a/src/options.json
+++ b/src/options.json
@@ -64,6 +64,9 @@
         }
       ]
     },
+    "chunkFilter": {
+      "instanceof": "Function"
+    },
     "cache": {
       "anyOf": [
         {


Test patch:
diff --git a/test/__snapshots__/chunkFilter-option.test.js.snap b/test/__snapshots__/chunkFilter-option.test.js.snap
new file mode 100644
index 0000000..263257d
--- /dev/null
+++ b/test/__snapshots__/chunkFilter-option.test.js.snap
@@ -0,0 +1,108 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`when applied with \`chunkFilter\` option matches snapshot for a single \`chunkFilter\`: entry.dd5931aa48f58d803916.js 1`] = `"!function(n){var r={};function o(e){if(r[e])return r[e].exports;var t=r[e]={i:e,l:!1,exports:{}};return n[e].call(t.exports,t,t.exports,o),t.l=!0,t.exports}o.m=n,o.c=r,o.d=function(e,t,n){o.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},o.r=function(e){\\"undefined\\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:\\"Module\\"}),Object.defineProperty(e,\\"__esModule\\",{value:!0})},o.t=function(t,e){if(1&e&&(t=o(t)),8&e)return t;if(4&e&&\\"object\\"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(o.r(n),Object.defineProperty(n,\\"default\\",{enumerable:!0,value:t}),2&e&&\\"string\\"!=typeof t)for(var r in t)o.d(n,r,function(e){return t[e]}.bind(null,r));return n},o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,\\"a\\",t),t},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},o.p=\\"\\",o(o.s=1)}([,function(e,t){e.exports=function(){console.log(7)}}]);"`;
+
+exports[`when applied with \`chunkFilter\` option matches snapshot for a single \`chunkFilter\`: errors 1`] = `Array []`;
+
+exports[`when applied with \`chunkFilter\` option matches snapshot for a single \`chunkFilter\`: included.246349b8cbc039f3eb25.js 1`] = `
+"/******/ (function(modules) { // webpackBootstrap
+/******/ 	// The module cache
+/******/ 	var installedModules = {};
+/******/
+/******/ 	// The require function
+/******/ 	function __webpack_require__(moduleId) {
+/******/
+/******/ 		// Check if module is in cache
+/******/ 		if(installedModules[moduleId]) {
+/******/ 			return installedModules[moduleId].exports;
+/******/ 		}
+/******/ 		// Create a new module (and put it into the cache)
+/******/ 		var module = installedModules[moduleId] = {
+/******/ 			i: moduleId,
+/******/ 			l: false,
+/******/ 			exports: {}
+/******/ 		};
+/******/
+/******/ 		// Execute the module function
+/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
+/******/
+/******/ 		// Flag the module as loaded
+/******/ 		module.l = true;
+/******/
+/******/ 		// Return the exports of the module
+/******/ 		return module.exports;
+/******/ 	}
+/******/
+/******/
+/******/ 	// expose the modules object (__webpack_modules__)
+/******/ 	__webpack_require__.m = modules;
+/******/
+/******/ 	// expose the module cache
+/******/ 	__webpack_require__.c = installedModules;
+/******/
+/******/ 	// define getter function for harmony exports
+/******/ 	__webpack_require__.d = function(exports, name, getter) {
+/******/ 		if(!__webpack_require__.o(exports, name)) {
+/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
+/******/ 		}
+/******/ 	};
+/******/
+/******/ 	// define __esModule on exports
+/******/ 	__webpack_require__.r = function(exports) {
+/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
+/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
+/******/ 		}
+/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
+/******/ 	};
+/******/
+/******/ 	// create a fake namespace object
+/******/ 	// mode & 1: value is a module id, require it
+/******/ 	// mode & 2: merge all properties of value into the ns
+/******/ 	// mode & 4: return value when already ns object
+/******/ 	// mode & 8|1: behave like require
+/******/ 	__webpack_require__.t = function(value, mode) {
+/******/ 		if(mode & 1) value = __webpack_require__(value);
+/******/ 		if(mode & 8) return value;
+/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
+/******/ 		var ns = Object.create(null);
+/******/ 		__webpack_require__.r(ns);
+/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
+/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
+/******/ 		return ns;
+/******/ 	};
+/******/
+/******/ 	// getDefaultExport function for compatibility with non-harmony modules
+/******/ 	__webpack_require__.n = function(module) {
+/******/ 		var getter = module && module.__esModule ?
+/******/ 			function getDefault() { return module['default']; } :
+/******/ 			function getModuleExports() { return module; };
+/******/ 		__webpack_require__.d(getter, 'a', getter);
+/******/ 		return getter;
+/******/ 	};
+/******/
+/******/ 	// Object.prototype.hasOwnProperty.call
+/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
+/******/
+/******/ 	// __webpack_public_path__
+/******/ 	__webpack_require__.p = \\"\\";
+/******/
+/******/
+/******/ 	// Load entry module and return exports
+/******/ 	return __webpack_require__(__webpack_require__.s = 0);
+/******/ })
+/************************************************************************/
+/******/ ([
+/* 0 */
+/***/ (function(module, exports) {
+
+module.exports = function Bar1() {
+  var b = 2 + 2;
+  console.log(b + 1 + 2);
+};
+
+
+/***/ })
+/******/ ]);"
+`;
+
+exports[`when applied with \`chunkFilter\` option matches snapshot for a single \`chunkFilter\`: warnings 1`] = `Array []`;
diff --git a/test/__snapshots__/validation.test.js.snap b/test/__snapshots__/validation.test.js.snap
index 863b203..49f6c53 100644
--- a/test/__snapshots__/validation.test.js.snap
+++ b/test/__snapshots__/validation.test.js.snap
@@ -3,20 +3,27 @@
 exports[`validation 1`] = `
 "UglifyJs Plugin Invalid Options
 
-options should NOT have additional properties
+options.chunkFilter should pass \\"instanceof\\" keyword validation
 "
 `;
 
 exports[`validation 2`] = `
 "UglifyJs Plugin Invalid Options
 
+options should NOT have additional properties
+"
+`;
+
+exports[`validation 3`] = `
+"UglifyJs Plugin Invalid Options
+
 options.cache should be boolean
 options.cache should be string
 options.cache should match some schema in anyOf
 "
 `;
 
-exports[`validation 3`] = `
+exports[`validation 4`] = `
 "UglifyJs Plugin Invalid Options
 
 options.parallel should be boolean
@@ -25,7 +32,7 @@ options.parallel should match some schema in anyOf
 "
 `;
 
-exports[`validation 4`] = `
+exports[`validation 5`] = `
 "UglifyJs Plugin Invalid Options
 
 options.parallel should be boolean
@@ -34,21 +41,21 @@ options.parallel should match some schema in anyOf
 "
 `;
 
-exports[`validation 5`] = `
+exports[`validation 6`] = `
 "UglifyJs Plugin Invalid Options
 
 options.sourceMap should be boolean
 "
 `;
 
-exports[`validation 6`] = `
+exports[`validation 7`] = `
 "UglifyJs Plugin Invalid Options
 
 options.uglifyOptions should be object
 "
 `;
 
-exports[`validation 7`] = `
+exports[`validation 8`] = `
 "UglifyJs Plugin Invalid Options
 
 options.warningsFilter should pass \\"instanceof\\" keyword validation
diff --git a/test/chunkFilter-option.test.js b/test/chunkFilter-option.test.js
new file mode 100644
index 0000000..c6bdfb8
--- /dev/null
+++ b/test/chunkFilter-option.test.js
@@ -0,0 +1,44 @@
+import UglifyJsPlugin from '../src/index';
+
+import { cleanErrorStack, createCompiler, compile } from './helpers';
+
+describe('when applied with `chunkFilter` option', () => {
+  let compiler;
+
+  beforeEach(() => {
+    compiler = createCompiler({
+      entry: {
+        included: `${__dirname}/fixtures/included1.js`,
+        entry: `${__dirname}/fixtures/entry.js`,
+      },
+    });
+  });
+
+  it('matches snapshot for a single `chunkFilter`', () => {
+    new UglifyJsPlugin({
+      chunkFilter: (chunk) => {
+        if (chunk.name === 'included') {
+          return false;
+        }
+
+        return true;
+      },
+    }).apply(compiler);
+
+    return compile(compiler).then((stats) => {
+      const errors = stats.compilation.errors.map(cleanErrorStack);
+      const warnings = stats.compilation.warnings.map(cleanErrorStack);
+
+      expect(errors).toMatchSnapshot('errors');
+      expect(warnings).toMatchSnapshot('warnings');
+
+      for (const file in stats.compilation.assets) {
+        if (
+          Object.prototype.hasOwnProperty.call(stats.compilation.assets, file)
+        ) {
+          expect(stats.compilation.assets[file].source()).toMatchSnapshot(file);
+        }
+      }
+    });
+  });
+});
diff --git a/test/validation.test.js b/test/validation.test.js
index 900274e..130c774 100644
--- a/test/validation.test.js
+++ b/test/validation.test.js
@@ -26,6 +26,14 @@ it('validation', () => {
     new UglifyJsPlugin({ exclude: [/foo/] });
   }).not.toThrow();
 
+  expect(() => {
+    new UglifyJsPlugin({ chunkFilter: () => {} });
+  }).not.toThrow();
+
+  expect(() => {
+    new UglifyJsPlugin({ chunkFilter: true });
+  }).toThrowErrorMatchingSnapshot();
+
   expect(() => {
     new UglifyJsPlugin({ doesntExist: true });
   }).toThrowErrorMatchingSnapshot();