loader.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334
  1. /* This loader renders the template with underscore if no other loader was found */
  2. // @ts-nocheck
  3. 'use strict';
  4. const _ = require('lodash');
  5. const loaderUtils = require('loader-utils');
  6. module.exports = function (source) {
  7. // Get templating options
  8. const options = this.query !== '' ? loaderUtils.getOptions(this) : {};
  9. const force = options.force || false;
  10. const allLoadersButThisOne = this.loaders.filter(function (loader) {
  11. return 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. // Skip .js files (unless it's explicitly enforced)
  18. if (/\.js$/.test(this.resourcePath) && !force) {
  19. return source;
  20. }
  21. // The following part renders the template with lodash as a minimalistic loader
  22. //
  23. const template = _.template(source, _.defaults(options, { interpolate: /<%=([\s\S]+?)%>/g, variable: 'data' }));
  24. // Use __non_webpack_require__ to enforce using the native nodejs require
  25. // during template execution
  26. return 'var _ = __non_webpack_require__(' + JSON.stringify(require.resolve('lodash')) + ');' +
  27. 'module.exports = function (templateParams) { with(templateParams) {' +
  28. // Execute the lodash template
  29. 'return (' + template.source + ')();' +
  30. '}}';
  31. };