loader.js 1.6 KB

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