UNPKG

2.02 kBJavaScriptView Raw
1/* This loader renders the template with underscore if no other loader was found */
2'use strict';
3
4const _ = require('lodash');
5const loaderUtils = require('loader-utils');
6
7module.exports = function (source) {
8 if (this.cacheable) {
9 this.cacheable();
10 }
11 const allLoadersButThisOne = this.loaders.filter(function (loader) {
12 // Loader API changed from `loader.module` to `loader.normal` in Webpack 2.
13 return (loader.module || loader.normal) !== module.exports;
14 });
15 // This loader shouldn't kick in if there is any other loader
16 if (allLoadersButThisOne.length > 0) {
17 return source;
18 }
19 // Skip .js files
20 if (/\.js$/.test(this.resourcePath)) {
21 return source;
22 }
23
24 // The following part renders the tempalte with lodash as aminimalistic loader
25 //
26 // Get templating options
27 const options = this.query !== '' ? loaderUtils.parseQuery(this.query) : {};
28 // Webpack 2 does not allow with() statements, which lodash templates use to unwrap
29 // the parameters passed to the compiled template inside the scope. We therefore
30 // need to unwrap them ourselves here. This is essentially what lodash does internally
31 // To tell lodash it should not use with we set a variable
32 const template = _.template(source, _.defaults(options, { variable: 'data' }));
33 // All templateVariables which should be available
34 // @see HtmlWebpackPlugin.prototype.executeTemplate
35 const templateVariables = [
36 'compilation',
37 'webpack',
38 'webpackConfig',
39 'htmlWebpackPlugin'
40 ];
41 return 'var _ = require(' + loaderUtils.stringifyRequest(this, require.resolve('lodash')) + ');' +
42 'module.exports = function (templateParams) {' +
43 // Declare the template variables in the outer scope of the
44 // lodash template to unwrap them
45 templateVariables.map(function (variableName) {
46 return 'var ' + variableName + ' = templateParams.' + variableName;
47 }).join(';') + ';' +
48 // Execute the lodash template
49 'return (' + template.source + ')();' +
50 '}';
51};