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.

289 lines
7.9 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 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(
  181. parser,
  182. strCode
  183. )(expr);
  184. }
  185. });
  186. }
  187. parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => {
  188. /**
  189. * this is needed in case there is a recursion in the DefinePlugin
  190. * to prevent an endless recursion
  191. * e.g.: new DefinePlugin({
  192. * "typeof a": "typeof b",
  193. * "typeof b": "typeof a"
  194. * });
  195. */
  196. if (recurseTypeof) return;
  197. recurseTypeof = true;
  198. const typeofCode = isTypeof
  199. ? toCode(code, parser)
  200. : "typeof (" + toCode(code, parser) + ")";
  201. const res = parser.evaluate(typeofCode);
  202. recurseTypeof = false;
  203. res.setRange(expr.range);
  204. return res;
  205. });
  206. parser.hooks.typeof.for(key).tap("DefinePlugin", expr => {
  207. const typeofCode = isTypeof
  208. ? toCode(code, parser)
  209. : "typeof (" + toCode(code, parser) + ")";
  210. const res = parser.evaluate(typeofCode);
  211. if (!res.isString()) return;
  212. return ParserHelpers.toConstantDependency(
  213. parser,
  214. JSON.stringify(res.string)
  215. ).bind(parser)(expr);
  216. });
  217. };
  218. /**
  219. * Apply Object
  220. * @param {string} key Key
  221. * @param {Object} obj Object
  222. * @returns {void}
  223. */
  224. const applyObjectDefine = (key, obj) => {
  225. parser.hooks.canRename
  226. .for(key)
  227. .tap("DefinePlugin", ParserHelpers.approve);
  228. parser.hooks.evaluateIdentifier
  229. .for(key)
  230. .tap("DefinePlugin", expr =>
  231. new BasicEvaluatedExpression().setTruthy().setRange(expr.range)
  232. );
  233. parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => {
  234. return ParserHelpers.evaluateToString("object")(expr);
  235. });
  236. parser.hooks.expression.for(key).tap("DefinePlugin", expr => {
  237. const strCode = stringifyObj(obj, parser);
  238. if (/__webpack_require__/.test(strCode)) {
  239. return ParserHelpers.toConstantDependencyWithWebpackRequire(
  240. parser,
  241. strCode
  242. )(expr);
  243. } else {
  244. return ParserHelpers.toConstantDependency(
  245. parser,
  246. strCode
  247. )(expr);
  248. }
  249. });
  250. parser.hooks.typeof.for(key).tap("DefinePlugin", expr => {
  251. return ParserHelpers.toConstantDependency(
  252. parser,
  253. JSON.stringify("object")
  254. )(expr);
  255. });
  256. };
  257. walkDefinitions(definitions, "");
  258. };
  259. normalModuleFactory.hooks.parser
  260. .for("javascript/auto")
  261. .tap("DefinePlugin", handler);
  262. normalModuleFactory.hooks.parser
  263. .for("javascript/dynamic")
  264. .tap("DefinePlugin", handler);
  265. normalModuleFactory.hooks.parser
  266. .for("javascript/esm")
  267. .tap("DefinePlugin", handler);
  268. }
  269. );
  270. }
  271. }
  272. module.exports = DefinePlugin;