ImportMetaPlugin.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Ivan Kopeykin @vankop
  4. */
  5. "use strict";
  6. const { pathToFileURL } = require("url");
  7. const ModuleDependencyWarning = require("../ModuleDependencyWarning");
  8. const {
  9. JAVASCRIPT_MODULE_TYPE_AUTO,
  10. JAVASCRIPT_MODULE_TYPE_ESM
  11. } = require("../ModuleTypeConstants");
  12. const Template = require("../Template");
  13. const BasicEvaluatedExpression = require("../javascript/BasicEvaluatedExpression");
  14. const {
  15. evaluateToIdentifier,
  16. toConstantDependency,
  17. evaluateToString,
  18. evaluateToNumber
  19. } = require("../javascript/JavascriptParserHelpers");
  20. const memoize = require("../util/memoize");
  21. const propertyAccess = require("../util/propertyAccess");
  22. const ConstDependency = require("./ConstDependency");
  23. /** @typedef {import("estree").MemberExpression} MemberExpression */
  24. /** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
  25. /** @typedef {import("../Compiler")} Compiler */
  26. /** @typedef {import("../Dependency").DependencyLocation} DependencyLocation */
  27. /** @typedef {import("../NormalModule")} NormalModule */
  28. /** @typedef {import("../javascript/JavascriptParser")} Parser */
  29. /** @typedef {import("../javascript/JavascriptParser").Range} Range */
  30. const getCriticalDependencyWarning = memoize(() =>
  31. require("./CriticalDependencyWarning")
  32. );
  33. const PLUGIN_NAME = "ImportMetaPlugin";
  34. class ImportMetaPlugin {
  35. /**
  36. * @param {Compiler} compiler compiler
  37. */
  38. apply(compiler) {
  39. compiler.hooks.compilation.tap(
  40. PLUGIN_NAME,
  41. (compilation, { normalModuleFactory }) => {
  42. /**
  43. * @param {NormalModule} module module
  44. * @returns {string} file url
  45. */
  46. const getUrl = module => {
  47. return pathToFileURL(module.resource).toString();
  48. };
  49. /**
  50. * @param {Parser} parser parser parser
  51. * @param {JavascriptParserOptions} parserOptions parserOptions
  52. * @returns {void}
  53. */
  54. const parserHandler = (parser, { importMeta }) => {
  55. if (importMeta === false) {
  56. const { importMetaName } = compilation.outputOptions;
  57. if (importMetaName === "import.meta") return;
  58. parser.hooks.expression
  59. .for("import.meta")
  60. .tap(PLUGIN_NAME, metaProperty => {
  61. const dep = new ConstDependency(
  62. /** @type {string} */ (importMetaName),
  63. /** @type {Range} */ (metaProperty.range)
  64. );
  65. dep.loc = /** @type {DependencyLocation} */ (metaProperty.loc);
  66. parser.state.module.addPresentationalDependency(dep);
  67. return true;
  68. });
  69. return;
  70. }
  71. /// import.meta direct ///
  72. const webpackVersion = parseInt(
  73. require("../../package.json").version,
  74. 10
  75. );
  76. const importMetaUrl = () =>
  77. JSON.stringify(getUrl(parser.state.module));
  78. const importMetaWebpackVersion = () => JSON.stringify(webpackVersion);
  79. /**
  80. * @param {string[]} members members
  81. * @returns {string} error message
  82. */
  83. const importMetaUnknownProperty = members =>
  84. `${Template.toNormalComment(
  85. "unsupported import.meta." + members.join(".")
  86. )} undefined${propertyAccess(members, 1)}`;
  87. parser.hooks.typeof
  88. .for("import.meta")
  89. .tap(
  90. PLUGIN_NAME,
  91. toConstantDependency(parser, JSON.stringify("object"))
  92. );
  93. parser.hooks.expression
  94. .for("import.meta")
  95. .tap(PLUGIN_NAME, metaProperty => {
  96. const referencedPropertiesInDestructuring =
  97. parser.destructuringAssignmentPropertiesFor(metaProperty);
  98. if (!referencedPropertiesInDestructuring) {
  99. const CriticalDependencyWarning =
  100. getCriticalDependencyWarning();
  101. parser.state.module.addWarning(
  102. new ModuleDependencyWarning(
  103. parser.state.module,
  104. new CriticalDependencyWarning(
  105. "Accessing import.meta directly is unsupported (only property access or destructuring is supported)"
  106. ),
  107. /** @type {DependencyLocation} */ (metaProperty.loc)
  108. )
  109. );
  110. const dep = new ConstDependency(
  111. `${
  112. parser.isAsiPosition(
  113. /** @type {Range} */ (metaProperty.range)[0]
  114. )
  115. ? ";"
  116. : ""
  117. }({})`,
  118. /** @type {Range} */ (metaProperty.range)
  119. );
  120. dep.loc = /** @type {DependencyLocation} */ (metaProperty.loc);
  121. parser.state.module.addPresentationalDependency(dep);
  122. return true;
  123. }
  124. let str = "";
  125. for (const { id: prop } of referencedPropertiesInDestructuring) {
  126. switch (prop) {
  127. case "url":
  128. str += `url: ${importMetaUrl()},`;
  129. break;
  130. case "webpack":
  131. str += `webpack: ${importMetaWebpackVersion()},`;
  132. break;
  133. default:
  134. str += `[${JSON.stringify(
  135. prop
  136. )}]: ${importMetaUnknownProperty([prop])},`;
  137. break;
  138. }
  139. }
  140. const dep = new ConstDependency(
  141. `({${str}})`,
  142. /** @type {Range} */ (metaProperty.range)
  143. );
  144. dep.loc = /** @type {DependencyLocation} */ (metaProperty.loc);
  145. parser.state.module.addPresentationalDependency(dep);
  146. return true;
  147. });
  148. parser.hooks.evaluateTypeof
  149. .for("import.meta")
  150. .tap(PLUGIN_NAME, evaluateToString("object"));
  151. parser.hooks.evaluateIdentifier.for("import.meta").tap(
  152. PLUGIN_NAME,
  153. evaluateToIdentifier("import.meta", "import.meta", () => [], true)
  154. );
  155. /// import.meta.url ///
  156. parser.hooks.typeof
  157. .for("import.meta.url")
  158. .tap(
  159. PLUGIN_NAME,
  160. toConstantDependency(parser, JSON.stringify("string"))
  161. );
  162. parser.hooks.expression
  163. .for("import.meta.url")
  164. .tap(PLUGIN_NAME, expr => {
  165. const dep = new ConstDependency(
  166. importMetaUrl(),
  167. /** @type {Range} */ (expr.range)
  168. );
  169. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  170. parser.state.module.addPresentationalDependency(dep);
  171. return true;
  172. });
  173. parser.hooks.evaluateTypeof
  174. .for("import.meta.url")
  175. .tap(PLUGIN_NAME, evaluateToString("string"));
  176. parser.hooks.evaluateIdentifier
  177. .for("import.meta.url")
  178. .tap(PLUGIN_NAME, expr => {
  179. return new BasicEvaluatedExpression()
  180. .setString(getUrl(parser.state.module))
  181. .setRange(/** @type {Range} */ (expr.range));
  182. });
  183. /// import.meta.webpack ///
  184. parser.hooks.typeof
  185. .for("import.meta.webpack")
  186. .tap(
  187. PLUGIN_NAME,
  188. toConstantDependency(parser, JSON.stringify("number"))
  189. );
  190. parser.hooks.expression
  191. .for("import.meta.webpack")
  192. .tap(
  193. PLUGIN_NAME,
  194. toConstantDependency(parser, importMetaWebpackVersion())
  195. );
  196. parser.hooks.evaluateTypeof
  197. .for("import.meta.webpack")
  198. .tap(PLUGIN_NAME, evaluateToString("number"));
  199. parser.hooks.evaluateIdentifier
  200. .for("import.meta.webpack")
  201. .tap(PLUGIN_NAME, evaluateToNumber(webpackVersion));
  202. /// Unknown properties ///
  203. parser.hooks.unhandledExpressionMemberChain
  204. .for("import.meta")
  205. .tap(PLUGIN_NAME, (expr, members) => {
  206. const dep = new ConstDependency(
  207. importMetaUnknownProperty(members),
  208. /** @type {Range} */ (expr.range)
  209. );
  210. dep.loc = /** @type {DependencyLocation} */ (expr.loc);
  211. parser.state.module.addPresentationalDependency(dep);
  212. return true;
  213. });
  214. parser.hooks.evaluate
  215. .for("MemberExpression")
  216. .tap(PLUGIN_NAME, expression => {
  217. const expr = /** @type {MemberExpression} */ (expression);
  218. if (
  219. expr.object.type === "MetaProperty" &&
  220. expr.object.meta.name === "import" &&
  221. expr.object.property.name === "meta" &&
  222. expr.property.type ===
  223. (expr.computed ? "Literal" : "Identifier")
  224. ) {
  225. return new BasicEvaluatedExpression()
  226. .setUndefined()
  227. .setRange(/** @type {Range} */ (expr.range));
  228. }
  229. });
  230. };
  231. normalModuleFactory.hooks.parser
  232. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  233. .tap(PLUGIN_NAME, parserHandler);
  234. normalModuleFactory.hooks.parser
  235. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  236. .tap(PLUGIN_NAME, parserHandler);
  237. }
  238. );
  239. }
  240. }
  241. module.exports = ImportMetaPlugin;