From c90e2de4c1c6fde039affa3f35323cfa6d928c62 Mon Sep 17 00:00:00 2001 From: Jack Brown Date: Tue, 14 May 2019 14:36:43 +1000 Subject: [PATCH] fix prependTo so that it is a whitelist and add the ability to pass in a Regex --- README.md | 31 +++++++++++++++++++++++++++++-- src/index.js | 21 +++++++++++++++++++-- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 453db39..15a2b87 100644 --- a/README.md +++ b/README.md @@ -182,10 +182,37 @@ This project's Git repository comes with a working demo project. ## Options ### `prependTo` -* *Type:* `array|string` +* *Type:* `string` | `regex` | `(regex|string)[]` -By default we prepend the player to the first file with a `.js` extension that is listed as an output. If you only want to prepend to certain file(s) pass an array or string along with the filename of the files you want to prepend the player to. +By default we prepend the player to the first file with a `.js` extension that is listed as an output. +If you only want to prepend to certain file(s) you may pass a string or regex that will be used to match against webpacks output filenames array. You can optionally pass an array in `prependTo`, and the player will be prepended to any file that matches any item in the array (regex or string). + +```js +// Example of matching files output by webpack when code splitting +const filenames = ['bundle.js', 'bundle.1.js', 'bundle.2.js', 'playerBundle.js']; + +// webpack.config.js +module.exports = { + + // ... Additional configuration for entry, output, etc. + + plugins: [ + new PlayerLoader({ + accountId: '12345678910', + // matches bundle.js only + // prependTo: 'bundle.js', + + // matches all files starting with bundle + // prependTo: /^bundle/, + + // matches both bundle.js and playerBundle.js only + // prependTo: [/^bundle\.js/, /^player/], + }) + ] +}; + +``` ### `accountId` * **REQUIRED** diff --git a/src/index.js b/src/index.js index ce55eca..06255d3 100644 --- a/src/index.js +++ b/src/index.js @@ -56,8 +56,25 @@ class PlayerLoaderPlugin { assets = [assets[0]]; // if prependTo is specified though, we prepend to anything that is listed - } else { - assets = assets.filter((filename) => this.settings_.prependTo.indexOf(filename) === -1); + } else if (this.settings_.prependTo.length > 0) { + const matches = []; + + assets.forEach((outputFilename) => { + this.settings_.prependTo.forEach(filter => { + if (filter instanceof RegExp) { + // filter is a regex + if (filter.test(outputFilename)) { + matches.push(outputFilename); + } + } + // filter is a string + if (outputFilename.indexOf(filter) > -1) { + matches.push(outputFilename); + } + }); + }); + + assets = matches; } if (!assets.length) {