loader.js 1.3 KB

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