Fix Webpack2 compatibility. Closes #213.

This commit is contained in:
Alexander Wesolowski 2016-02-11 19:04:24 -08:00 committed by Jan Nicklas
parent 617abd6a4d
commit a5174be6f2
2 changed files with 26 additions and 2 deletions

View File

@ -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);
};

21
lib/template.js Normal file
View File

@ -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 */
};