diff --git a/lib/loader.js b/lib/loader.js index 592e45b4..ef8d2abd 100644 --- a/lib/loader.js +++ b/lib/loader.js @@ -8,13 +8,20 @@ module.exports = function (source) { const options = this.getOptions(); const force = options.force || false; - const allLoadersButThisOne = this.loaders.filter(function (loader) { - return loader.normal !== module.exports; - }); + const allLoadersButThisOne = this.loaders.filter((loader) => loader.normal !== module.exports); + // This loader shouldn't kick in if there is any other loader (unless it's explicitly enforced) if (allLoadersButThisOne.length > 0 && !force) { return source; } + + // Allow only one html-webpack-plugin loader to allow loader options in the webpack config + const htmlWebpackPluginLoaders = this.loaders.filter((loader) => loader.normal === module.exports); + const lastHtmlWebpackPluginLoader = htmlWebpackPluginLoaders[htmlWebpackPluginLoaders.length - 1]; + if (this.loaders[this.loaderIndex] !== lastHtmlWebpackPluginLoader) { + return source; + } + // Skip .js files (unless it's explicitly enforced) if (/\.js$/.test(this.resourcePath) && !force) { return source; @@ -22,7 +29,7 @@ module.exports = function (source) { // The following part renders the template with lodash as a minimalistic loader // - const template = _.template(source, _.defaults(options, { interpolate: /<%=([\s\S]+?)%>/g, variable: 'data' })); + const template = _.template(source, { interpolate: /<%=([\s\S]+?)%>/g, variable: 'data', ...options }); // Use __non_webpack_require__ to enforce using the native nodejs require // during template execution return 'var _ = __non_webpack_require__(' + JSON.stringify(require.resolve('lodash')) + ');' + diff --git a/spec/basic.spec.js b/spec/basic.spec.js index 3cb646d5..572d7740 100644 --- a/spec/basic.spec.js +++ b/spec/basic.spec.js @@ -2750,4 +2750,36 @@ describe('HtmlWebpackPlugin', () => { ] }, [''], null, done); }); + + it('allows to set custom loader interpolation settings', done => { + testHtmlPlugin({ + mode: 'production', + entry: { + app: path.join(__dirname, 'fixtures/index.js') + }, + output: { + path: OUTPUT_DIR, + filename: '[name]_bundle.js' + }, + module: { + rules: [ + { + test: /\.html$/, + loader: require.resolve('../lib/loader.js'), + options: { + interpolate: /\{%=([\s\S]+?)%\}/g + } + } + ] + }, + plugins: [ + new HtmlWebpackPlugin({ + title: 'Interpolation Demo', + template: path.join(__dirname, 'fixtures/interpolation.html') + }) + ] + }, ['Interpolation Demo'], null, () => { + done(); + }); + }); }); diff --git a/spec/fixtures/legacy.html b/spec/fixtures/interpolation.html similarity index 58% rename from spec/fixtures/legacy.html rename to spec/fixtures/interpolation.html index 3611c961..5647aec2 100644 --- a/spec/fixtures/legacy.html +++ b/spec/fixtures/interpolation.html @@ -2,10 +2,9 @@ - Test + {%= htmlWebpackPlugin.options.title %}

Some unique text

-