選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

SetVarMainTemplatePlugin.js 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. class SetVarMainTemplatePlugin {
  9. /**
  10. * @param {string} varExpression the accessor where the library is exported
  11. * @param {boolean} copyObject specify copying the exports
  12. */
  13. constructor(varExpression, copyObject) {
  14. /** @type {string} */
  15. this.varExpression = varExpression;
  16. /** @type {boolean} */
  17. this.copyObject = copyObject;
  18. }
  19. /**
  20. * @param {Compilation} compilation the compilation instance
  21. * @returns {void}
  22. */
  23. apply(compilation) {
  24. const { mainTemplate, chunkTemplate } = compilation;
  25. const onRenderWithEntry = (source, chunk, hash) => {
  26. const varExpression = mainTemplate.getAssetPath(this.varExpression, {
  27. hash,
  28. chunk
  29. });
  30. if (this.copyObject) {
  31. return new ConcatSource(
  32. `(function(e, a) { for(var i in a) e[i] = a[i]; }(${varExpression}, `,
  33. source,
  34. "))"
  35. );
  36. } else {
  37. const prefix = `${varExpression} =\n`;
  38. return new ConcatSource(prefix, source);
  39. }
  40. };
  41. for (const template of [mainTemplate, chunkTemplate]) {
  42. template.hooks.renderWithEntry.tap(
  43. "SetVarMainTemplatePlugin",
  44. onRenderWithEntry
  45. );
  46. }
  47. mainTemplate.hooks.globalHashPaths.tap(
  48. "SetVarMainTemplatePlugin",
  49. paths => {
  50. if (this.varExpression) paths.push(this.varExpression);
  51. return paths;
  52. }
  53. );
  54. mainTemplate.hooks.hash.tap("SetVarMainTemplatePlugin", hash => {
  55. hash.update("set var");
  56. hash.update(`${this.varExpression}`);
  57. hash.update(`${this.copyObject}`);
  58. });
  59. }
  60. }
  61. module.exports = SetVarMainTemplatePlugin;