UNPKG

1.65 kBJavaScriptView Raw
1/* This loader renders the template with underscore if no other loader was found */
2// @ts-nocheck
3'use strict';
4const _ = require('lodash');
5
6module.exports = function (source) {
7 // Get templating options
8 const options = this.getOptions();
9 const force = options.force || false;
10
11 const allLoadersButThisOne = this.loaders.filter((loader) => loader.normal !== module.exports);
12
13 // This loader shouldn't kick in if there is any other loader (unless it's explicitly enforced)
14 if (allLoadersButThisOne.length > 0 && !force) {
15 return source;
16 }
17
18 // Allow only one html-webpack-plugin loader to allow loader options in the webpack config
19 const htmlWebpackPluginLoaders = this.loaders.filter((loader) => loader.normal === module.exports);
20 const lastHtmlWebpackPluginLoader = htmlWebpackPluginLoaders[htmlWebpackPluginLoaders.length - 1];
21 if (this.loaders[this.loaderIndex] !== lastHtmlWebpackPluginLoader) {
22 return source;
23 }
24
25 // Skip .js files (unless it's explicitly enforced)
26 if (/\.js$/.test(this.resourcePath) && !force) {
27 return source;
28 }
29
30 // The following part renders the template with lodash as a minimalistic loader
31 //
32 const template = _.template(source, { interpolate: /<%=([\s\S]+?)%>/g, variable: 'data', ...options });
33 // Use __non_webpack_require__ to enforce using the native nodejs require
34 // during template execution
35 return 'var _ = __non_webpack_require__(' + JSON.stringify(require.resolve('lodash')) + ');' +
36 'module.exports = function (templateParams) { with(templateParams) {' +
37 // Execute the lodash template
38 'return (' + template.source + ')();' +
39 '}}';
40};