ExtendedAPIPlugin.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const ConstDependency = require("./dependencies/ConstDependency");
  7. const ParserHelpers = require("./ParserHelpers");
  8. const NullFactory = require("./NullFactory");
  9. const REPLACEMENTS = {
  10. __webpack_hash__: "__webpack_require__.h", // eslint-disable-line camelcase
  11. __webpack_chunkname__: "__webpack_require__.cn" // eslint-disable-line camelcase
  12. };
  13. const REPLACEMENT_TYPES = {
  14. __webpack_hash__: "string", // eslint-disable-line camelcase
  15. __webpack_chunkname__: "string" // eslint-disable-line camelcase
  16. };
  17. class ExtendedAPIPlugin {
  18. apply(compiler) {
  19. compiler.plugin("compilation", (compilation, params) => {
  20. compilation.dependencyFactories.set(ConstDependency, new NullFactory());
  21. compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
  22. compilation.mainTemplate.plugin("require-extensions", function(source, chunk, hash) {
  23. const buf = [source];
  24. buf.push("");
  25. buf.push("// __webpack_hash__");
  26. buf.push(`${this.requireFn}.h = ${JSON.stringify(hash)};`);
  27. buf.push("");
  28. buf.push("// __webpack_chunkname__");
  29. buf.push(`${this.requireFn}.cn = ${JSON.stringify(chunk.name)};`);
  30. return this.asString(buf);
  31. });
  32. compilation.mainTemplate.plugin("global-hash", () => true);
  33. params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
  34. Object.keys(REPLACEMENTS).forEach(key => {
  35. parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
  36. parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
  37. });
  38. });
  39. });
  40. }
  41. }
  42. module.exports = ExtendedAPIPlugin;