loader.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /* This loader renders the template with underscore if no other loader was found */
  2. // @ts-nocheck
  3. "use strict";
  4. const _template = require("lodash/template");
  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(
  10. (loader) => loader.normal !== module.exports,
  11. );
  12. // This loader shouldn't kick in if there is any other loader (unless it's explicitly enforced)
  13. if (allLoadersButThisOne.length > 0 && !force) {
  14. return source;
  15. }
  16. // Allow only one html-webpack-plugin loader to allow loader options in the webpack config
  17. const htmlWebpackPluginLoaders = this.loaders.filter(
  18. (loader) => loader.normal === module.exports,
  19. );
  20. const lastHtmlWebpackPluginLoader =
  21. htmlWebpackPluginLoaders[htmlWebpackPluginLoaders.length - 1];
  22. if (this.loaders[this.loaderIndex] !== lastHtmlWebpackPluginLoader) {
  23. return source;
  24. }
  25. // Skip .js files (unless it's explicitly enforced)
  26. if (/\.(c|m)?js$/.test(this.resourcePath) && !force) {
  27. return source;
  28. }
  29. // The following part renders the template with lodash as a minimalistic loader
  30. //
  31. const template = _template(source, {
  32. interpolate: /<%=([\s\S]+?)%>/g,
  33. variable: "data",
  34. ...options,
  35. });
  36. // Use `eval("require")("lodash")` to enforce using the native nodejs require
  37. // during template execution
  38. return (
  39. 'var _ = eval("require")(' +
  40. JSON.stringify(require.resolve("lodash")) +
  41. ");" +
  42. "module.exports = function (templateParams) { with(templateParams) {" +
  43. // Execute the lodash template
  44. "return (" +
  45. template.source +
  46. ")();" +
  47. "}}"
  48. );
  49. };