From a5174be6f20eb30b8b410c6f9ef1604e0e0430f7 Mon Sep 17 00:00:00 2001 From: Alexander Wesolowski Date: Thu, 11 Feb 2016 19:04:24 -0800 Subject: [PATCH] Fix Webpack2 compatibility. Closes #213. --- lib/loader.js | 7 +++++-- lib/template.js | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 lib/template.js diff --git a/lib/loader.js b/lib/loader.js index 21396c3..01a8715 100644 --- a/lib/loader.js +++ b/lib/loader.js @@ -3,6 +3,7 @@ var _ = require('lodash'); var loaderUtils = require('loader-utils'); +var templateConstructor = require('./template'); module.exports = function (source) { if (this.cacheable) { @@ -22,6 +23,8 @@ module.exports = function (source) { } // Use underscore for a minimalistic loader var options = loaderUtils.parseQuery(this.query); - var template = _.template(source, options); - return 'var _ = require(' + loaderUtils.stringifyRequest(this, require.resolve('lodash')) + ');module.exports = ' + template; + // Workaround for Webpack 1 & 2 compatibility. + // See issue#213. + var template = _.template(source, _.defaults(options, { variable: 'data' })); + return 'var _ = require(' + loaderUtils.stringifyRequest(this, require.resolve('lodash')) + ');module.exports = ' + templateConstructor(template); }; diff --git a/lib/template.js b/lib/template.js new file mode 100644 index 0000000..39fa8e7 --- /dev/null +++ b/lib/template.js @@ -0,0 +1,21 @@ +/* This module returns a function constructor. It is necessary to maintain + backward compatibility with Webpack 1 while supporting Webpack 2. + Webpack 2 does not allow with() statements, which lodash templates use to unwrap + the parameters passed to the compiled template inside the scope. We therefore + need to unwrap them ourselves here. This is essentially what lodash does internally + (see lodash/template). + + See issue#213 for more information. +*/ +'use strict'; + +module.exports = function (template) { + /* eslint-disable no-new-func */ + return Function('attr', + 'var webpack = attr.webpack;' + + 'var webpackConfig = attr.webpackConfig;' + + 'var htmlWebpackPlugin = attr.htmlWebpackPlugin;' + + 'return ' + template.source + '();' + ); + /* eslint-enable no-new-func */ +};