Move template.js into loader.js

This commit is contained in:
Jan Nicklas 2016-02-16 10:55:31 +01:00 committed by Jan Nicklas
parent a5174be6f2
commit c883a8663c
2 changed files with 25 additions and 26 deletions

View File

@ -3,7 +3,6 @@
var _ = require('lodash');
var loaderUtils = require('loader-utils');
var templateConstructor = require('./template');
module.exports = function (source) {
if (this.cacheable) {
@ -21,10 +20,31 @@ module.exports = function (source) {
if (/\.js$/.test(this.request)) {
return source;
}
// Use underscore for a minimalistic loader
// The following part renders the tempalte with lodash as aminimalistic loader
//
// Get templating options
var options = loaderUtils.parseQuery(this.query);
// Workaround for Webpack 1 & 2 compatibility.
// See issue#213.
// 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
// To tell lodash it should not use with we set a variable
var template = _.template(source, _.defaults(options, { variable: 'data' }));
return 'var _ = require(' + loaderUtils.stringifyRequest(this, require.resolve('lodash')) + ');module.exports = ' + templateConstructor(template);
// All templateVariables which should be available
// @see HtmlWebpackPlugin.prototype.executeTemplate
var templateVariables = [
'webpack',
'webpackConfig',
'htmlWebpackPlugin'
];
return 'var _ = require(' + loaderUtils.stringifyRequest(this, require.resolve('lodash')) + ');' +
'module.exports = function (templateParams) {' +
// Declare the template variables in the outer scope of the
// lodash template to unwrap them
templateVariables.map(function (variableName) {
return 'var ' + variableName + ' = templateParams.' + variableName;
}).join(';') + ';' +
// Execute the lodash template
'return (' + template.source + ')();' +
'}';
};

View File

@ -1,21 +0,0 @@
/* 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 */
};