loader.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /* This loader renders the template with underscore if no other loader was found */
  2. 'use strict';
  3. var _ = require('lodash');
  4. var loaderUtils = require('loader-utils');
  5. module.exports = function (source) {
  6. if (this.cacheable) {
  7. this.cacheable();
  8. }
  9. var 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. var options = loaderUtils.parseQuery(this.query);
  25. // Webpack 2 does not allow with() statements, which lodash templates use to unwrap
  26. // the parameters passed to the compiled template inside the scope. We therefore
  27. // need to unwrap them ourselves here. This is essentially what lodash does internally
  28. // To tell lodash it should not use with we set a variable
  29. var template = _.template(source, _.defaults(options, { variable: 'data' }));
  30. // All templateVariables which should be available
  31. // @see HtmlWebpackPlugin.prototype.executeTemplate
  32. var templateVariables = [
  33. 'compilation',
  34. 'webpack',
  35. 'webpackConfig',
  36. 'htmlWebpackPlugin'
  37. ];
  38. return 'var _ = require(' + loaderUtils.stringifyRequest(this, require.resolve('lodash')) + ');' +
  39. 'module.exports = function (templateParams) {' +
  40. // Declare the template variables in the outer scope of the
  41. // lodash template to unwrap them
  42. templateVariables.map(function (variableName) {
  43. return 'var ' + variableName + ' = templateParams.' + variableName;
  44. }).join(';') + ';' +
  45. // Execute the lodash template
  46. 'return (' + template.source + ')();' +
  47. '}';
  48. };