Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

DefinePlugin.js 7.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
  8. const ParserHelpers = require("./ParserHelpers");
  9. const NullFactory = require("./NullFactory");
  10. /** @typedef {import("./Compiler")} Compiler */
  11. /** @typedef {import("./Parser")} Parser */
  12. /** @typedef {null|undefined|RegExp|Function|string|number} CodeValuePrimitive */
  13. /** @typedef {CodeValuePrimitive|Record<string, CodeValuePrimitive>|RuntimeValue} CodeValue */
  14. class RuntimeValue {
  15. constructor(fn, fileDependencies) {
  16. this.fn = fn;
  17. this.fileDependencies = fileDependencies || [];
  18. }
  19. exec(parser) {
  20. if (this.fileDependencies === true) {
  21. parser.state.module.buildInfo.cacheable = false;
  22. } else {
  23. for (const fileDependency of this.fileDependencies) {
  24. parser.state.module.buildInfo.fileDependencies.add(fileDependency);
  25. }
  26. }
  27. return this.fn({ module: parser.state.module });
  28. }
  29. }
  30. const stringifyObj = (obj, parser) => {
  31. return (
  32. "Object({" +
  33. Object.keys(obj)
  34. .map(key => {
  35. const code = obj[key];
  36. return JSON.stringify(key) + ":" + toCode(code, parser);
  37. })
  38. .join(",") +
  39. "})"
  40. );
  41. };
  42. /**
  43. * Convert code to a string that evaluates
  44. * @param {CodeValue} code Code to evaluate
  45. * @param {Parser} parser Parser
  46. * @returns {string} code converted to string that evaluates
  47. */
  48. const toCode = (code, parser) => {
  49. if (code === null) {
  50. return "null";
  51. }
  52. if (code === undefined) {
  53. return "undefined";
  54. }
  55. if (code instanceof RuntimeValue) {
  56. return toCode(code.exec(parser), parser);
  57. }
  58. if (code instanceof RegExp && code.toString) {
  59. return code.toString();
  60. }
  61. if (typeof code === "function" && code.toString) {
  62. return "(" + code.toString() + ")";
  63. }
  64. if (typeof code === "object") {
  65. return stringifyObj(code, parser);
  66. }
  67. return code + "";
  68. };
  69. class DefinePlugin {
  70. /**
  71. * Create a new define plugin
  72. * @param {Record<string, CodeValue>} definitions A map of global object definitions
  73. */
  74. constructor(definitions) {
  75. this.definitions = definitions;
  76. }
  77. static runtimeValue(fn, fileDependencies) {
  78. return new RuntimeValue(fn, fileDependencies);
  79. }
  80. /**
  81. * Apply the plugin
  82. * @param {Compiler} compiler Webpack compiler
  83. * @returns {void}
  84. */
  85. apply(compiler) {
  86. const definitions = this.definitions;
  87. compiler.hooks.compilation.tap(
  88. "DefinePlugin",
  89. (compilation, { normalModuleFactory }) => {
  90. compilation.dependencyFactories.set(ConstDependency, new NullFactory());
  91. compilation.dependencyTemplates.set(
  92. ConstDependency,
  93. new ConstDependency.Template()
  94. );
  95. /**
  96. * Handler
  97. * @param {Parser} parser Parser
  98. * @returns {void}
  99. */
  100. const handler = parser => {
  101. /**
  102. * Walk definitions
  103. * @param {Object} definitions Definitions map
  104. * @param {string} prefix Prefix string
  105. * @returns {void}
  106. */
  107. const walkDefinitions = (definitions, prefix) => {
  108. Object.keys(definitions).forEach(key => {
  109. const code = definitions[key];
  110. if (
  111. code &&
  112. typeof code === "object" &&
  113. !(code instanceof RuntimeValue) &&
  114. !(code instanceof RegExp)
  115. ) {
  116. walkDefinitions(code, prefix + key + ".");
  117. applyObjectDefine(prefix + key, code);
  118. return;
  119. }
  120. applyDefineKey(prefix, key);
  121. applyDefine(prefix + key, code);
  122. });
  123. };
  124. /**
  125. * Apply define key
  126. * @param {string} prefix Prefix
  127. * @param {string} key Key
  128. * @returns {void}
  129. */
  130. const applyDefineKey = (prefix, key) => {
  131. const splittedKey = key.split(".");
  132. splittedKey.slice(1).forEach((_, i) => {
  133. const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
  134. parser.hooks.canRename
  135. .for(fullKey)
  136. .tap("DefinePlugin", ParserHelpers.approve);
  137. });
  138. };
  139. /**
  140. * Apply Code
  141. * @param {string} key Key
  142. * @param {CodeValue} code Code
  143. * @returns {void}
  144. */
  145. const applyDefine = (key, code) => {
  146. const isTypeof = /^typeof\s+/.test(key);
  147. if (isTypeof) key = key.replace(/^typeof\s+/, "");
  148. let recurse = false;
  149. let recurseTypeof = false;
  150. if (!isTypeof) {
  151. parser.hooks.canRename
  152. .for(key)
  153. .tap("DefinePlugin", ParserHelpers.approve);
  154. parser.hooks.evaluateIdentifier
  155. .for(key)
  156. .tap("DefinePlugin", expr => {
  157. /**
  158. * this is needed in case there is a recursion in the DefinePlugin
  159. * to prevent an endless recursion
  160. * e.g.: new DefinePlugin({
  161. * "a": "b",
  162. * "b": "a"
  163. * });
  164. */
  165. if (recurse) return;
  166. recurse = true;
  167. const res = parser.evaluate(toCode(code, parser));
  168. recurse = false;
  169. res.setRange(expr.range);
  170. return res;
  171. });
  172. parser.hooks.expression.for(key).tap("DefinePlugin", expr => {
  173. const strCode = toCode(code, parser);
  174. if (/__webpack_require__/.test(strCode)) {
  175. return ParserHelpers.toConstantDependencyWithWebpackRequire(
  176. parser,
  177. strCode
  178. )(expr);
  179. } else {
  180. return ParserHelpers.toConstantDependency(parser, strCode)(
  181. expr
  182. );
  183. }
  184. });
  185. }
  186. parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => {
  187. /**
  188. * this is needed in case there is a recursion in the DefinePlugin
  189. * to prevent an endless recursion
  190. * e.g.: new DefinePlugin({
  191. * "typeof a": "typeof b",
  192. * "typeof b": "typeof a"
  193. * });
  194. */
  195. if (recurseTypeof) return;
  196. recurseTypeof = true;
  197. const typeofCode = isTypeof
  198. ? toCode(code, parser)
  199. : "typeof (" + toCode(code, parser) + ")";
  200. const res = parser.evaluate(typeofCode);
  201. recurseTypeof = false;
  202. res.setRange(expr.range);
  203. return res;
  204. });
  205. parser.hooks.typeof.for(key).tap("DefinePlugin", expr => {
  206. const typeofCode = isTypeof
  207. ? toCode(code, parser)
  208. : "typeof (" + toCode(code, parser) + ")";
  209. const res = parser.evaluate(typeofCode);
  210. if (!res.isString()) return;
  211. return ParserHelpers.toConstantDependency(
  212. parser,
  213. JSON.stringify(res.string)
  214. ).bind(parser)(expr);
  215. });
  216. };
  217. /**
  218. * Apply Object
  219. * @param {string} key Key
  220. * @param {Object} obj Object
  221. * @returns {void}
  222. */
  223. const applyObjectDefine = (key, obj) => {
  224. parser.hooks.canRename
  225. .for(key)
  226. .tap("DefinePlugin", ParserHelpers.approve);
  227. parser.hooks.evaluateIdentifier
  228. .for(key)
  229. .tap("DefinePlugin", expr =>
  230. new BasicEvaluatedExpression().setTruthy().setRange(expr.range)
  231. );
  232. parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => {
  233. return ParserHelpers.evaluateToString("object")(expr);
  234. });
  235. parser.hooks.expression.for(key).tap("DefinePlugin", expr => {
  236. const strCode = stringifyObj(obj, parser);
  237. if (/__webpack_require__/.test(strCode)) {
  238. return ParserHelpers.toConstantDependencyWithWebpackRequire(
  239. parser,
  240. strCode
  241. )(expr);
  242. } else {
  243. return ParserHelpers.toConstantDependency(parser, strCode)(
  244. expr
  245. );
  246. }
  247. });
  248. parser.hooks.typeof.for(key).tap("DefinePlugin", expr => {
  249. return ParserHelpers.toConstantDependency(
  250. parser,
  251. JSON.stringify("object")
  252. )(expr);
  253. });
  254. };
  255. walkDefinitions(definitions, "");
  256. };
  257. normalModuleFactory.hooks.parser
  258. .for("javascript/auto")
  259. .tap("DefinePlugin", handler);
  260. normalModuleFactory.hooks.parser
  261. .for("javascript/dynamic")
  262. .tap("DefinePlugin", handler);
  263. normalModuleFactory.hooks.parser
  264. .for("javascript/esm")
  265. .tap("DefinePlugin", handler);
  266. }
  267. );
  268. }
  269. }
  270. module.exports = DefinePlugin;