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.

84 lines
2.2 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 ConstDependency = require("./dependencies/ConstDependency");
  7. const ParserHelpers = require("./ParserHelpers");
  8. const NullFactory = require("./NullFactory");
  9. /* eslint-disable camelcase */
  10. const REPLACEMENTS = {
  11. __webpack_require__: "__webpack_require__",
  12. __webpack_public_path__: "__webpack_require__.p",
  13. __webpack_modules__: "__webpack_require__.m",
  14. __webpack_chunk_load__: "__webpack_require__.e",
  15. __non_webpack_require__: "require",
  16. __webpack_nonce__: "__webpack_require__.nc",
  17. "require.onError": "__webpack_require__.oe"
  18. };
  19. const NO_WEBPACK_REQUIRE = {
  20. __non_webpack_require__: true
  21. };
  22. const REPLACEMENT_TYPES = {
  23. __webpack_public_path__: "string",
  24. __webpack_require__: "function",
  25. __webpack_modules__: "object",
  26. __webpack_chunk_load__: "function",
  27. __webpack_nonce__: "string"
  28. };
  29. /* eslint-enable camelcase */
  30. class APIPlugin {
  31. apply(compiler) {
  32. compiler.hooks.compilation.tap(
  33. "APIPlugin",
  34. (compilation, { normalModuleFactory }) => {
  35. compilation.dependencyFactories.set(ConstDependency, new NullFactory());
  36. compilation.dependencyTemplates.set(
  37. ConstDependency,
  38. new ConstDependency.Template()
  39. );
  40. const handler = parser => {
  41. Object.keys(REPLACEMENTS).forEach(key => {
  42. parser.hooks.expression
  43. .for(key)
  44. .tap(
  45. "APIPlugin",
  46. NO_WEBPACK_REQUIRE[key]
  47. ? ParserHelpers.toConstantDependency(
  48. parser,
  49. REPLACEMENTS[key]
  50. )
  51. : ParserHelpers.toConstantDependencyWithWebpackRequire(
  52. parser,
  53. REPLACEMENTS[key]
  54. )
  55. );
  56. const type = REPLACEMENT_TYPES[key];
  57. if (type) {
  58. parser.hooks.evaluateTypeof
  59. .for(key)
  60. .tap("APIPlugin", ParserHelpers.evaluateToString(type));
  61. }
  62. });
  63. };
  64. normalModuleFactory.hooks.parser
  65. .for("javascript/auto")
  66. .tap("APIPlugin", handler);
  67. normalModuleFactory.hooks.parser
  68. .for("javascript/dynamic")
  69. .tap("APIPlugin", handler);
  70. normalModuleFactory.hooks.parser
  71. .for("javascript/esm")
  72. .tap("APIPlugin", handler);
  73. }
  74. );
  75. }
  76. }
  77. module.exports = APIPlugin;