You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.3 KiB

4 years ago
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { ConcatSource } = require("webpack-sources");
  7. /** @typedef {import("./Compilation")} Compilation */
  8. /**
  9. * @param {string[]} accessor the accessor to convert to path
  10. * @returns {string} the path
  11. */
  12. const accessorToObjectAccess = accessor => {
  13. return accessor.map(a => `[${JSON.stringify(a)}]`).join("");
  14. };
  15. class ExportPropertyMainTemplatePlugin {
  16. /**
  17. * @param {string|string[]} property the name of the property to export
  18. */
  19. constructor(property) {
  20. this.property = property;
  21. }
  22. /**
  23. * @param {Compilation} compilation the compilation instance
  24. * @returns {void}
  25. */
  26. apply(compilation) {
  27. const { mainTemplate, chunkTemplate } = compilation;
  28. const onRenderWithEntry = (source, chunk, hash) => {
  29. const postfix = `${accessorToObjectAccess([].concat(this.property))}`;
  30. return new ConcatSource(source, postfix);
  31. };
  32. for (const template of [mainTemplate, chunkTemplate]) {
  33. template.hooks.renderWithEntry.tap(
  34. "ExportPropertyMainTemplatePlugin",
  35. onRenderWithEntry
  36. );
  37. }
  38. mainTemplate.hooks.hash.tap("ExportPropertyMainTemplatePlugin", hash => {
  39. hash.update("export property");
  40. hash.update(`${this.property}`);
  41. });
  42. }
  43. }
  44. module.exports = ExportPropertyMainTemplatePlugin;