UNPKG

1.37 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');
5const loaderUtils = require('loader-utils');
6
7module.exports = function (source) {
8 // Get templating options
9 const options = this.query !== '' ? loaderUtils.getOptions(this) : {};
10 const force = options.force || false;
11
12 const allLoadersButThisOne = this.loaders.filter(function (loader) {
13 return loader.normal !== module.exports;
14 });
15 // This loader shouldn't kick in if there is any other loader (unless it's explicitly enforced)
16 if (allLoadersButThisOne.length > 0 && !force) {
17 return source;
18 }
19 // Skip .js files (unless it's explicitly enforced)
20 if (/\.js$/.test(this.resourcePath) && !force) {
21 return source;
22 }
23
24 // The following part renders the template with lodash as a minimalistic loader
25 //
26 const template = _.template(source, _.defaults(options, { interpolate: /<%=([\s\S]+?)%>/g, variable: 'data' }));
27 // Use __non_webpack_require__ to enforce using the native nodejs require
28 // during template execution
29 return 'var _ = __non_webpack_require__(' + JSON.stringify(require.resolve('lodash')) + ');' +
30 'module.exports = function (templateParams) { with(templateParams) {' +
31 // Execute the lodash template
32 'return (' + template.source + ')();' +
33 '}}';
34};