LibManifestPlugin.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const path = require("path");
  7. const asyncLib = require("neo-async");
  8. const SingleEntryDependency = require("./dependencies/SingleEntryDependency");
  9. class LibManifestPlugin {
  10. constructor(options) {
  11. this.options = options;
  12. }
  13. apply(compiler) {
  14. compiler.hooks.emit.tapAsync(
  15. "LibManifestPlugin",
  16. (compilation, callback) => {
  17. asyncLib.forEach(
  18. compilation.chunks,
  19. (chunk, callback) => {
  20. if (!chunk.isOnlyInitial()) {
  21. callback();
  22. return;
  23. }
  24. const targetPath = compilation.getPath(this.options.path, {
  25. hash: compilation.hash,
  26. chunk
  27. });
  28. const name =
  29. this.options.name &&
  30. compilation.getPath(this.options.name, {
  31. hash: compilation.hash,
  32. chunk
  33. });
  34. const manifest = {
  35. name,
  36. type: this.options.type,
  37. content: Array.from(chunk.modulesIterable, module => {
  38. if (
  39. this.options.entryOnly &&
  40. !module.reasons.some(
  41. r => r.dependency instanceof SingleEntryDependency
  42. )
  43. ) {
  44. return;
  45. }
  46. if (module.libIdent) {
  47. const ident = module.libIdent({
  48. context: this.options.context || compiler.options.context
  49. });
  50. if (ident) {
  51. return {
  52. ident,
  53. data: {
  54. id: module.id,
  55. buildMeta: module.buildMeta
  56. }
  57. };
  58. }
  59. }
  60. })
  61. .filter(Boolean)
  62. .reduce((obj, item) => {
  63. obj[item.ident] = item.data;
  64. return obj;
  65. }, Object.create(null))
  66. };
  67. // Apply formatting to content if format flag is true;
  68. const manifestContent = this.options.format
  69. ? JSON.stringify(manifest, null, 2)
  70. : JSON.stringify(manifest);
  71. const content = Buffer.from(manifestContent, "utf8");
  72. compiler.outputFileSystem.mkdirp(path.dirname(targetPath), err => {
  73. if (err) return callback(err);
  74. compiler.outputFileSystem.writeFile(
  75. targetPath,
  76. content,
  77. callback
  78. );
  79. });
  80. },
  81. callback
  82. );
  83. }
  84. );
  85. }
  86. }
  87. module.exports = LibManifestPlugin;