inline-requires.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @format
  8. */
  9. 'use strict';
  10. /**
  11. * This transform inlines top-level require(...) aliases with to enable lazy
  12. * loading of dependencies. It is able to inline both single references and
  13. * child property references.
  14. *
  15. * For instance:
  16. * var Foo = require('foo');
  17. * f(Foo);
  18. *
  19. * Will be transformed into:
  20. * f(require('foo'));
  21. *
  22. * When the assigment expression has a property access, it will be inlined too,
  23. * keeping the property. For instance:
  24. * var Bar = require('foo').bar;
  25. * g(Bar);
  26. *
  27. * Will be transformed into:
  28. * g(require('foo').bar);
  29. *
  30. * Destructuring also works the same way. For instance:
  31. * const {Baz} = require('foo');
  32. * h(Baz);
  33. *
  34. * Is also successfully inlined into:
  35. * g(require('foo').Baz);
  36. */
  37. module.exports = babel => ({
  38. name: 'inline-requires',
  39. visitor: {
  40. Program: {
  41. exit(path, state) {
  42. const t = babel.types;
  43. const ignoredRequires = new Set();
  44. const inlineableCalls = new Set(['require']);
  45. if (state.opts != null) {
  46. if (state.opts.ignoredRequires != null) {
  47. for (const name of state.opts.ignoredRequires) {
  48. ignoredRequires.add(name);
  49. }
  50. }
  51. if (state.opts.inlineableCalls != null) {
  52. for (const name of state.opts.inlineableCalls) {
  53. inlineableCalls.add(name);
  54. }
  55. }
  56. }
  57. path.scope.crawl();
  58. path.traverse(
  59. {
  60. CallExpression(path, state) {
  61. const parseResult =
  62. parseInlineableAlias(path, state) ||
  63. parseInlineableMemberAlias(path, state);
  64. if (parseResult == null) {
  65. return;
  66. }
  67. const {
  68. declarationPath,
  69. moduleName,
  70. requireFnName,
  71. } = parseResult;
  72. const init = declarationPath.node.init;
  73. const name = declarationPath.node.id
  74. ? declarationPath.node.id.name
  75. : null;
  76. const binding = declarationPath.scope.getBinding(name);
  77. if (binding.constantViolations.length > 0) {
  78. return;
  79. }
  80. deleteLocation(init);
  81. babel.traverse(init, {
  82. noScope: true,
  83. enter: path => deleteLocation(path.node),
  84. });
  85. let thrown = false;
  86. for (const referencePath of binding.referencePaths) {
  87. excludeMemberAssignment(moduleName, referencePath, state);
  88. try {
  89. referencePath.scope.rename(requireFnName);
  90. referencePath.replaceWith(t.cloneDeep(init));
  91. } catch (error) {
  92. thrown = true;
  93. }
  94. }
  95. // If a replacement failed (e.g. replacing a type annotation),
  96. // avoid removing the initial require just to be safe.
  97. if (!thrown) {
  98. declarationPath.remove();
  99. }
  100. },
  101. },
  102. {
  103. ignoredRequires,
  104. inlineableCalls,
  105. membersAssigned: new Map(),
  106. },
  107. );
  108. },
  109. },
  110. },
  111. });
  112. function excludeMemberAssignment(moduleName, referencePath, state) {
  113. const assignment = referencePath.parentPath.parent;
  114. const isValid =
  115. assignment.type === 'AssignmentExpression' &&
  116. assignment.left.type === 'MemberExpression' &&
  117. assignment.left.object === referencePath.node;
  118. if (!isValid) {
  119. return;
  120. }
  121. const memberPropertyName = getMemberPropertyName(assignment.left);
  122. if (memberPropertyName == null) {
  123. return;
  124. }
  125. let membersAssigned = state.membersAssigned.get(moduleName);
  126. if (membersAssigned == null) {
  127. membersAssigned = new Set();
  128. state.membersAssigned.set(moduleName, membersAssigned);
  129. }
  130. membersAssigned.add(memberPropertyName);
  131. }
  132. function isExcludedMemberAssignment(moduleName, memberPropertyName, state) {
  133. const excludedAliases = state.membersAssigned.get(moduleName);
  134. return excludedAliases != null && excludedAliases.has(memberPropertyName);
  135. }
  136. function getMemberPropertyName(node) {
  137. if (node.type !== 'MemberExpression') {
  138. return null;
  139. }
  140. if (node.property.type === 'Identifier') {
  141. return node.property.name;
  142. }
  143. if (node.property.type === 'StringLiteral') {
  144. return node.property.value;
  145. }
  146. return null;
  147. }
  148. function deleteLocation(node) {
  149. delete node.start;
  150. delete node.end;
  151. delete node.loc;
  152. }
  153. function parseInlineableAlias(path, state) {
  154. const module = getInlineableModule(path, state);
  155. if (module == null) {
  156. return null;
  157. }
  158. const { moduleName, requireFnName } = module;
  159. const isValid =
  160. path.parent.type === 'VariableDeclarator' &&
  161. path.parent.id.type === 'Identifier' &&
  162. path.parentPath.parent.type === 'VariableDeclaration' &&
  163. path.parentPath.parentPath.parent.type === 'Program';
  164. return !isValid || path.parentPath.node == null
  165. ? null
  166. : {
  167. declarationPath: path.parentPath,
  168. moduleName,
  169. requireFnName,
  170. };
  171. }
  172. function parseInlineableMemberAlias(path, state) {
  173. const module = getInlineableModule(path, state);
  174. if (module == null) {
  175. return null;
  176. }
  177. const { moduleName, requireFnName } = module;
  178. const isValid =
  179. path.parent.type === 'MemberExpression' &&
  180. path.parentPath.parent.type === 'VariableDeclarator' &&
  181. path.parentPath.parent.id.type === 'Identifier' &&
  182. path.parentPath.parentPath.parent.type === 'VariableDeclaration' &&
  183. path.parentPath.parentPath.parentPath.parent.type === 'Program';
  184. const memberPropertyName = getMemberPropertyName(path.parent);
  185. return !isValid ||
  186. path.parentPath.parentPath.node == null ||
  187. isExcludedMemberAssignment(moduleName, memberPropertyName, state)
  188. ? null
  189. : {
  190. declarationPath: path.parentPath.parentPath,
  191. moduleName,
  192. requireFnName,
  193. };
  194. }
  195. function getInlineableModule(path, state) {
  196. const node = path.node;
  197. const isInlineable =
  198. node.type === 'CallExpression' &&
  199. node.callee.type === 'Identifier' &&
  200. state.inlineableCalls.has(node.callee.name) &&
  201. node['arguments'].length >= 1;
  202. if (!isInlineable) {
  203. return null;
  204. }
  205. // require('foo');
  206. let moduleName =
  207. node['arguments'][0].type === 'StringLiteral'
  208. ? node['arguments'][0].value
  209. : null;
  210. // require(require.resolve('foo'));
  211. if (moduleName == null) {
  212. moduleName =
  213. node['arguments'][0].type === 'CallExpression' &&
  214. node['arguments'][0].callee.type === 'MemberExpression' &&
  215. node['arguments'][0].callee.object.type === 'Identifier' &&
  216. state.inlineableCalls.has(node['arguments'][0].callee.object.name) &&
  217. node['arguments'][0].callee.property.type === 'Identifier' &&
  218. node['arguments'][0].callee.property.name === 'resolve' &&
  219. node['arguments'][0]['arguments'].length >= 1 &&
  220. node['arguments'][0]['arguments'][0].type === 'StringLiteral'
  221. ? node['arguments'][0]['arguments'][0].value
  222. : null;
  223. }
  224. // Check if require is in any parent scope
  225. const fnName = node.callee.name;
  226. const isRequireInScope = path.scope.getBinding(fnName) != null;
  227. return moduleName == null ||
  228. state.ignoredRequires.has(moduleName) ||
  229. isRequireInScope
  230. ? null
  231. : { moduleName, requireFnName: fnName };
  232. }