loader.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  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. if (this.cacheable) {
  8. this.cacheable();
  9. }
  10. const allLoadersButThisOne = this.loaders.filter(function (loader) {
  11. // Loader API changed from `loader.module` to `loader.normal` in Webpack 2.
  12. return (loader.module || loader.normal) !== module.exports;
  13. });
  14. // This loader shouldn't kick in if there is any other loader
  15. if (allLoadersButThisOne.length > 0) {
  16. return source;
  17. }
  18. // Skip .js files
  19. if (/\.js$/.test(this.resourcePath)) {
  20. return source;
  21. }
  22. // The following part renders the template with lodash as aminimalistic loader
  23. //
  24. // Get templating options
  25. const options = this.query !== '' ? loaderUtils.getOptions(this) : {};
  26. const template = _.template(source, _.defaults(options, { interpolate: /<%=([\s\S]+?)%>/g, variable: 'data' }));
  27. // Require !!lodash - using !! will disable all loaders (e.g. babel)
  28. return 'var _ = require(' + loaderUtils.stringifyRequest(this, '!!' + require.resolve('lodash')) + ');' +
  29. 'module.exports = function (templateParams) { with(templateParams) {' +
  30. // Execute the lodash template
  31. 'return (' + template.source + ')();' +
  32. '}}';
  33. };