CompatibilityPlugin.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const {
  7. JAVASCRIPT_MODULE_TYPE_AUTO,
  8. JAVASCRIPT_MODULE_TYPE_DYNAMIC,
  9. JAVASCRIPT_MODULE_TYPE_ESM
  10. } = require("./ModuleTypeConstants");
  11. const RuntimeGlobals = require("./RuntimeGlobals");
  12. const ConstDependency = require("./dependencies/ConstDependency");
  13. /** @import { CallExpression } from "estree" */
  14. /** @import Compiler from "./Compiler" */
  15. /** @import { DependencyLocation } from "./Dependency" */
  16. /** @import ContextDependency from "./dependencies/ContextDependency" */
  17. /** @import JavascriptParser, { Range } from "./javascript/JavascriptParser" */
  18. /**
  19. * Captures the source range of a renamed compatibility binding so it can be
  20. * rewritten exactly once.
  21. * @typedef {object} CompatibilitySettingsDeclaration
  22. * @property {boolean} updated
  23. * @property {DependencyLocation} loc
  24. * @property {Range} range
  25. */
  26. /**
  27. * Stores the replacement variable name and the declaration metadata tracked
  28. * for a compatibility rewrite.
  29. * @typedef {object} CompatibilitySettings
  30. * @property {string} name
  31. * @property {CompatibilitySettingsDeclaration} declaration
  32. */
  33. const nestedWebpackIdentifierTag = Symbol("nested webpack identifier");
  34. const PLUGIN_NAME = "CompatibilityPlugin";
  35. /**
  36. * Adds parser-time compatibility rewrites for legacy runtime patterns that
  37. * webpack still needs to recognize in user and generated code.
  38. */
  39. class CompatibilityPlugin {
  40. /**
  41. * Installs parser hooks that preserve compatibility with legacy patterns
  42. * such as nested `__webpack_require__` bindings and hashbang handling.
  43. * @param {Compiler} compiler the compiler instance
  44. * @returns {void}
  45. */
  46. apply(compiler) {
  47. compiler.hooks.compilation.tap(
  48. PLUGIN_NAME,
  49. (compilation, { normalModuleFactory }) => {
  50. compilation.dependencyTemplates.set(
  51. ConstDependency,
  52. new ConstDependency.Template()
  53. );
  54. normalModuleFactory.hooks.parser
  55. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  56. .tap(PLUGIN_NAME, (parser, parserOptions) => {
  57. if (
  58. parserOptions.browserify !== undefined &&
  59. !parserOptions.browserify
  60. ) {
  61. return;
  62. }
  63. parser.hooks.call.for("require").tap(
  64. PLUGIN_NAME,
  65. /**
  66. * Rewrites browserify-style delegated `require` calls into a
  67. * plain webpack require reference and removes the synthetic
  68. * context dependency created for the delegator pattern.
  69. * @param {CallExpression} expr call expression
  70. * @returns {boolean | void} true when need to handle
  71. */
  72. (expr) => {
  73. // support for browserify style require delegator: "require(o, !0)"
  74. if (expr.arguments.length !== 2) return;
  75. const second = parser.evaluateExpression(expr.arguments[1]);
  76. if (!second.isBoolean()) return;
  77. if (second.asBool() !== true) return;
  78. const dep = new ConstDependency(
  79. "require",
  80. /** @type {Range} */ (expr.callee.range)
  81. );
  82. dep.loc = parser.getLocation(expr);
  83. if (parser.state.current.dependencies.length > 0) {
  84. const last =
  85. /** @type {ContextDependency} */
  86. (
  87. parser.state.current.dependencies[
  88. parser.state.current.dependencies.length - 1
  89. ]
  90. );
  91. if (
  92. last.critical &&
  93. last.options &&
  94. last.options.request === "." &&
  95. last.userRequest === "." &&
  96. last.options.recursive
  97. ) {
  98. parser.state.current.dependencies.pop();
  99. }
  100. }
  101. parser.state.module.addPresentationalDependency(dep);
  102. return true;
  103. }
  104. );
  105. });
  106. /**
  107. * Attaches the compatibility rewrites for a JavaScript parser
  108. * instance.
  109. * @param {JavascriptParser} parser the parser
  110. * @returns {void}
  111. */
  112. const handler = (parser) => {
  113. // Handle nested requires
  114. parser.hooks.preStatementByType
  115. .for("FunctionDeclaration")
  116. .tap(PLUGIN_NAME, (statement) => {
  117. if (
  118. statement.type === "FunctionDeclaration" &&
  119. statement.id &&
  120. statement.id.name === RuntimeGlobals.require
  121. ) {
  122. const newName = `__nested_webpack_require_${
  123. /** @type {Range} */
  124. (statement.range)[0]
  125. }__`;
  126. parser.tagVariable(
  127. statement.id.name,
  128. nestedWebpackIdentifierTag,
  129. {
  130. name: newName,
  131. declaration: {
  132. updated: false,
  133. loc: parser.getLocation(statement.id),
  134. range: /** @type {Range} */ (statement.id.range)
  135. }
  136. }
  137. );
  138. return true;
  139. }
  140. });
  141. parser.hooks.pattern
  142. .for(RuntimeGlobals.require)
  143. .tap(PLUGIN_NAME, (pattern) => {
  144. const newName = `__nested_webpack_require_${
  145. /** @type {Range} */ (pattern.range)[0]
  146. }__`;
  147. parser.tagVariable(pattern.name, nestedWebpackIdentifierTag, {
  148. name: newName,
  149. declaration: {
  150. updated: false,
  151. loc: parser.getLocation(pattern),
  152. range: /** @type {Range} */ (pattern.range)
  153. }
  154. });
  155. if (parser.scope.topLevelScope !== true) {
  156. return true;
  157. }
  158. });
  159. parser.hooks.pattern
  160. .for(RuntimeGlobals.exports)
  161. .tap(PLUGIN_NAME, (pattern) => {
  162. const newName = "__nested_webpack_exports__";
  163. parser.tagVariable(pattern.name, nestedWebpackIdentifierTag, {
  164. name: newName,
  165. declaration: {
  166. updated: false,
  167. loc: parser.getLocation(pattern),
  168. range: /** @type {Range} */ (pattern.range)
  169. }
  170. });
  171. return true;
  172. });
  173. // `const`/`let` are block-pre-walked, by which point the name is no
  174. // longer free and `hooks.pattern` is not dispatched for it — tag
  175. // them through the kind-specific declaration hooks instead.
  176. // Returning nothing lets the variable be defined, keeping the tag.
  177. for (const hookMap of [
  178. parser.hooks.varDeclarationConst,
  179. parser.hooks.varDeclarationLet
  180. ]) {
  181. hookMap.for(RuntimeGlobals.require).tap(PLUGIN_NAME, (ident) => {
  182. parser.tagVariable(ident.name, nestedWebpackIdentifierTag, {
  183. name: `__nested_webpack_require_${
  184. /** @type {Range} */ (ident.range)[0]
  185. }__`,
  186. declaration: {
  187. updated: false,
  188. loc: parser.getLocation(ident),
  189. range: /** @type {Range} */ (ident.range)
  190. }
  191. });
  192. });
  193. hookMap.for(RuntimeGlobals.exports).tap(PLUGIN_NAME, (ident) => {
  194. parser.tagVariable(ident.name, nestedWebpackIdentifierTag, {
  195. name: "__nested_webpack_exports__",
  196. declaration: {
  197. updated: false,
  198. loc: parser.getLocation(ident),
  199. range: /** @type {Range} */ (ident.range)
  200. }
  201. });
  202. });
  203. }
  204. // Update single `var __webpack_require__ = {};` and `var __webpack_exports__ = {};` without expression
  205. parser.hooks.declarator.tap(PLUGIN_NAME, (declarator) => {
  206. if (
  207. declarator.id.type === "Identifier" &&
  208. (declarator.id.name === RuntimeGlobals.exports ||
  209. declarator.id.name === RuntimeGlobals.require)
  210. ) {
  211. const tagData = /** @type {CompatibilitySettings | undefined} */ (
  212. parser.getTagData(
  213. declarator.id.name,
  214. nestedWebpackIdentifierTag
  215. )
  216. );
  217. if (!tagData) return;
  218. const { name, declaration } = tagData;
  219. if (!declaration.updated) {
  220. const dep = new ConstDependency(name, declaration.range);
  221. dep.loc = declaration.loc;
  222. parser.state.module.addPresentationalDependency(dep);
  223. declaration.updated = true;
  224. }
  225. }
  226. });
  227. parser.hooks.expression
  228. .for(nestedWebpackIdentifierTag)
  229. .tap(PLUGIN_NAME, (expr) => {
  230. const { name, declaration } =
  231. /** @type {CompatibilitySettings} */
  232. (parser.currentTagData);
  233. if (!declaration.updated) {
  234. const dep = new ConstDependency(name, declaration.range);
  235. dep.loc = declaration.loc;
  236. parser.state.module.addPresentationalDependency(dep);
  237. declaration.updated = true;
  238. }
  239. const dep = new ConstDependency(
  240. name,
  241. /** @type {Range} */ (expr.range)
  242. );
  243. dep.loc = parser.getLocation(expr);
  244. parser.state.module.addPresentationalDependency(dep);
  245. return true;
  246. });
  247. // Handle hashbang
  248. parser.hooks.program.tap(PLUGIN_NAME, (program, comments) => {
  249. if (comments.length === 0) return;
  250. const c = comments[0];
  251. if (c.type === "Line" && /** @type {Range} */ (c.range)[0] === 0) {
  252. if (parser.state.source.slice(0, 2).toString() !== "#!") return;
  253. // this is a hashbang comment
  254. const dep = new ConstDependency("//", 0);
  255. dep.loc = parser.getLocation(c);
  256. parser.state.module.addPresentationalDependency(dep);
  257. }
  258. });
  259. };
  260. normalModuleFactory.hooks.parser
  261. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  262. .tap(PLUGIN_NAME, handler);
  263. normalModuleFactory.hooks.parser
  264. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  265. .tap(PLUGIN_NAME, handler);
  266. normalModuleFactory.hooks.parser
  267. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  268. .tap(PLUGIN_NAME, handler);
  269. }
  270. );
  271. }
  272. }
  273. CompatibilityPlugin.nestedWebpackIdentifierTag = nestedWebpackIdentifierTag;
  274. module.exports = CompatibilityPlugin;