DefinePlugin.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const RuntimeGlobals = require("./RuntimeGlobals");
  7. const WebpackError = require("./WebpackError");
  8. const ConstDependency = require("./dependencies/ConstDependency");
  9. const BasicEvaluatedExpression = require("./javascript/BasicEvaluatedExpression");
  10. const {
  11. evaluateToString,
  12. toConstantDependency
  13. } = require("./javascript/JavascriptParserHelpers");
  14. const createHash = require("./util/createHash");
  15. /** @typedef {import("estree").Expression} Expression */
  16. /** @typedef {import("./Compiler")} Compiler */
  17. /** @typedef {import("./NormalModule")} NormalModule */
  18. /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
  19. /** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
  20. /** @typedef {null|undefined|RegExp|Function|string|number|boolean|bigint|undefined} CodeValuePrimitive */
  21. /** @typedef {RecursiveArrayOrRecord<CodeValuePrimitive|RuntimeValue>} CodeValue */
  22. /**
  23. * @typedef {Object} RuntimeValueOptions
  24. * @property {string[]=} fileDependencies
  25. * @property {string[]=} contextDependencies
  26. * @property {string[]=} missingDependencies
  27. * @property {string[]=} buildDependencies
  28. * @property {string|function(): string=} version
  29. */
  30. class RuntimeValue {
  31. /**
  32. * @param {function({ module: NormalModule, key: string, readonly version: string | undefined }): CodeValuePrimitive} fn generator function
  33. * @param {true | string[] | RuntimeValueOptions=} options options
  34. */
  35. constructor(fn, options) {
  36. this.fn = fn;
  37. if (Array.isArray(options)) {
  38. options = {
  39. fileDependencies: options
  40. };
  41. }
  42. this.options = options || {};
  43. }
  44. get fileDependencies() {
  45. return this.options === true ? true : this.options.fileDependencies;
  46. }
  47. /**
  48. * @param {JavascriptParser} parser the parser
  49. * @param {Map<string, string | Set<string>>} valueCacheVersions valueCacheVersions
  50. * @param {string} key the defined key
  51. * @returns {CodeValuePrimitive} code
  52. */
  53. exec(parser, valueCacheVersions, key) {
  54. const buildInfo = parser.state.module.buildInfo;
  55. if (this.options === true) {
  56. buildInfo.cacheable = false;
  57. } else {
  58. if (this.options.fileDependencies) {
  59. for (const dep of this.options.fileDependencies) {
  60. buildInfo.fileDependencies.add(dep);
  61. }
  62. }
  63. if (this.options.contextDependencies) {
  64. for (const dep of this.options.contextDependencies) {
  65. buildInfo.contextDependencies.add(dep);
  66. }
  67. }
  68. if (this.options.missingDependencies) {
  69. for (const dep of this.options.missingDependencies) {
  70. buildInfo.missingDependencies.add(dep);
  71. }
  72. }
  73. if (this.options.buildDependencies) {
  74. for (const dep of this.options.buildDependencies) {
  75. buildInfo.buildDependencies.add(dep);
  76. }
  77. }
  78. }
  79. return this.fn({
  80. module: parser.state.module,
  81. key,
  82. get version() {
  83. return /** @type {string} */ (
  84. valueCacheVersions.get(VALUE_DEP_PREFIX + key)
  85. );
  86. }
  87. });
  88. }
  89. getCacheVersion() {
  90. return this.options === true
  91. ? undefined
  92. : (typeof this.options.version === "function"
  93. ? this.options.version()
  94. : this.options.version) || "unset";
  95. }
  96. }
  97. /**
  98. * @param {any[]|{[k: string]: any}} obj obj
  99. * @param {JavascriptParser} parser Parser
  100. * @param {Map<string, string | Set<string>>} valueCacheVersions valueCacheVersions
  101. * @param {string} key the defined key
  102. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  103. * @param {boolean|undefined|null=} asiSafe asi safe (undefined: unknown, null: unneeded)
  104. * @returns {string} code converted to string that evaluates
  105. */
  106. const stringifyObj = (
  107. obj,
  108. parser,
  109. valueCacheVersions,
  110. key,
  111. runtimeTemplate,
  112. asiSafe
  113. ) => {
  114. let code;
  115. let arr = Array.isArray(obj);
  116. if (arr) {
  117. code = `[${obj
  118. .map(code =>
  119. toCode(code, parser, valueCacheVersions, key, runtimeTemplate, null)
  120. )
  121. .join(",")}]`;
  122. } else {
  123. code = `{${Object.keys(obj)
  124. .map(key => {
  125. const code = obj[key];
  126. return (
  127. JSON.stringify(key) +
  128. ":" +
  129. toCode(code, parser, valueCacheVersions, key, runtimeTemplate, null)
  130. );
  131. })
  132. .join(",")}}`;
  133. }
  134. switch (asiSafe) {
  135. case null:
  136. return code;
  137. case true:
  138. return arr ? code : `(${code})`;
  139. case false:
  140. return arr ? `;${code}` : `;(${code})`;
  141. default:
  142. return `/*#__PURE__*/Object(${code})`;
  143. }
  144. };
  145. /**
  146. * Convert code to a string that evaluates
  147. * @param {CodeValue} code Code to evaluate
  148. * @param {JavascriptParser} parser Parser
  149. * @param {Map<string, string | Set<string>>} valueCacheVersions valueCacheVersions
  150. * @param {string} key the defined key
  151. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  152. * @param {boolean|undefined|null=} asiSafe asi safe (undefined: unknown, null: unneeded)
  153. * @returns {string} code converted to string that evaluates
  154. */
  155. const toCode = (
  156. code,
  157. parser,
  158. valueCacheVersions,
  159. key,
  160. runtimeTemplate,
  161. asiSafe
  162. ) => {
  163. if (code === null) {
  164. return "null";
  165. }
  166. if (code === undefined) {
  167. return "undefined";
  168. }
  169. if (Object.is(code, -0)) {
  170. return "-0";
  171. }
  172. if (code instanceof RuntimeValue) {
  173. return toCode(
  174. code.exec(parser, valueCacheVersions, key),
  175. parser,
  176. valueCacheVersions,
  177. key,
  178. runtimeTemplate,
  179. asiSafe
  180. );
  181. }
  182. if (code instanceof RegExp && code.toString) {
  183. return code.toString();
  184. }
  185. if (typeof code === "function" && code.toString) {
  186. return "(" + code.toString() + ")";
  187. }
  188. if (typeof code === "object") {
  189. return stringifyObj(
  190. code,
  191. parser,
  192. valueCacheVersions,
  193. key,
  194. runtimeTemplate,
  195. asiSafe
  196. );
  197. }
  198. if (typeof code === "bigint") {
  199. return runtimeTemplate.supportsBigIntLiteral()
  200. ? `${code}n`
  201. : `BigInt("${code}")`;
  202. }
  203. return code + "";
  204. };
  205. const toCacheVersion = code => {
  206. if (code === null) {
  207. return "null";
  208. }
  209. if (code === undefined) {
  210. return "undefined";
  211. }
  212. if (Object.is(code, -0)) {
  213. return "-0";
  214. }
  215. if (code instanceof RuntimeValue) {
  216. return code.getCacheVersion();
  217. }
  218. if (code instanceof RegExp && code.toString) {
  219. return code.toString();
  220. }
  221. if (typeof code === "function" && code.toString) {
  222. return "(" + code.toString() + ")";
  223. }
  224. if (typeof code === "object") {
  225. const items = Object.keys(code).map(key => ({
  226. key,
  227. value: toCacheVersion(code[key])
  228. }));
  229. if (items.some(({ value }) => value === undefined)) return undefined;
  230. return `{${items.map(({ key, value }) => `${key}: ${value}`).join(", ")}}`;
  231. }
  232. if (typeof code === "bigint") {
  233. return `${code}n`;
  234. }
  235. return code + "";
  236. };
  237. const VALUE_DEP_PREFIX = "webpack/DefinePlugin ";
  238. const VALUE_DEP_MAIN = "webpack/DefinePlugin_hash";
  239. class DefinePlugin {
  240. /**
  241. * Create a new define plugin
  242. * @param {Record<string, CodeValue>} definitions A map of global object definitions
  243. */
  244. constructor(definitions) {
  245. this.definitions = definitions;
  246. }
  247. /**
  248. * @param {function({ module: NormalModule, key: string, readonly version: string | undefined }): CodeValuePrimitive} fn generator function
  249. * @param {true | string[] | RuntimeValueOptions=} options options
  250. * @returns {RuntimeValue} runtime value
  251. */
  252. static runtimeValue(fn, options) {
  253. return new RuntimeValue(fn, options);
  254. }
  255. /**
  256. * Apply the plugin
  257. * @param {Compiler} compiler the compiler instance
  258. * @returns {void}
  259. */
  260. apply(compiler) {
  261. const definitions = this.definitions;
  262. compiler.hooks.compilation.tap(
  263. "DefinePlugin",
  264. (compilation, { normalModuleFactory }) => {
  265. compilation.dependencyTemplates.set(
  266. ConstDependency,
  267. new ConstDependency.Template()
  268. );
  269. const { runtimeTemplate } = compilation;
  270. const mainHash = createHash(compilation.outputOptions.hashFunction);
  271. mainHash.update(
  272. /** @type {string} */ (
  273. compilation.valueCacheVersions.get(VALUE_DEP_MAIN)
  274. ) || ""
  275. );
  276. /**
  277. * Handler
  278. * @param {JavascriptParser} parser Parser
  279. * @returns {void}
  280. */
  281. const handler = parser => {
  282. const mainValue = compilation.valueCacheVersions.get(VALUE_DEP_MAIN);
  283. parser.hooks.program.tap("DefinePlugin", () => {
  284. const { buildInfo } = parser.state.module;
  285. if (!buildInfo.valueDependencies)
  286. buildInfo.valueDependencies = new Map();
  287. buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue);
  288. });
  289. const addValueDependency = key => {
  290. const { buildInfo } = parser.state.module;
  291. buildInfo.valueDependencies.set(
  292. VALUE_DEP_PREFIX + key,
  293. compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key)
  294. );
  295. };
  296. const withValueDependency =
  297. (key, fn) =>
  298. (...args) => {
  299. addValueDependency(key);
  300. return fn(...args);
  301. };
  302. /**
  303. * Walk definitions
  304. * @param {Object} definitions Definitions map
  305. * @param {string} prefix Prefix string
  306. * @returns {void}
  307. */
  308. const walkDefinitions = (definitions, prefix) => {
  309. Object.keys(definitions).forEach(key => {
  310. const code = definitions[key];
  311. if (
  312. code &&
  313. typeof code === "object" &&
  314. !(code instanceof RuntimeValue) &&
  315. !(code instanceof RegExp)
  316. ) {
  317. walkDefinitions(code, prefix + key + ".");
  318. applyObjectDefine(prefix + key, code);
  319. return;
  320. }
  321. applyDefineKey(prefix, key);
  322. applyDefine(prefix + key, code);
  323. });
  324. };
  325. /**
  326. * Apply define key
  327. * @param {string} prefix Prefix
  328. * @param {string} key Key
  329. * @returns {void}
  330. */
  331. const applyDefineKey = (prefix, key) => {
  332. const splittedKey = key.split(".");
  333. splittedKey.slice(1).forEach((_, i) => {
  334. const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
  335. parser.hooks.canRename.for(fullKey).tap("DefinePlugin", () => {
  336. addValueDependency(key);
  337. return true;
  338. });
  339. });
  340. };
  341. /**
  342. * Apply Code
  343. * @param {string} key Key
  344. * @param {CodeValue} code Code
  345. * @returns {void}
  346. */
  347. const applyDefine = (key, code) => {
  348. const originalKey = key;
  349. const isTypeof = /^typeof\s+/.test(key);
  350. if (isTypeof) key = key.replace(/^typeof\s+/, "");
  351. let recurse = false;
  352. let recurseTypeof = false;
  353. if (!isTypeof) {
  354. parser.hooks.canRename.for(key).tap("DefinePlugin", () => {
  355. addValueDependency(originalKey);
  356. return true;
  357. });
  358. parser.hooks.evaluateIdentifier
  359. .for(key)
  360. .tap("DefinePlugin", expr => {
  361. /**
  362. * this is needed in case there is a recursion in the DefinePlugin
  363. * to prevent an endless recursion
  364. * e.g.: new DefinePlugin({
  365. * "a": "b",
  366. * "b": "a"
  367. * });
  368. */
  369. if (recurse) return;
  370. addValueDependency(originalKey);
  371. recurse = true;
  372. const res = parser.evaluate(
  373. toCode(
  374. code,
  375. parser,
  376. compilation.valueCacheVersions,
  377. key,
  378. runtimeTemplate,
  379. null
  380. )
  381. );
  382. recurse = false;
  383. res.setRange(expr.range);
  384. return res;
  385. });
  386. parser.hooks.expression.for(key).tap("DefinePlugin", expr => {
  387. addValueDependency(originalKey);
  388. const strCode = toCode(
  389. code,
  390. parser,
  391. compilation.valueCacheVersions,
  392. originalKey,
  393. runtimeTemplate,
  394. !parser.isAsiPosition(expr.range[0])
  395. );
  396. if (/__webpack_require__\s*(!?\.)/.test(strCode)) {
  397. return toConstantDependency(parser, strCode, [
  398. RuntimeGlobals.require
  399. ])(expr);
  400. } else if (/__webpack_require__/.test(strCode)) {
  401. return toConstantDependency(parser, strCode, [
  402. RuntimeGlobals.requireScope
  403. ])(expr);
  404. } else {
  405. return toConstantDependency(parser, strCode)(expr);
  406. }
  407. });
  408. }
  409. parser.hooks.evaluateTypeof.for(key).tap("DefinePlugin", expr => {
  410. /**
  411. * this is needed in case there is a recursion in the DefinePlugin
  412. * to prevent an endless recursion
  413. * e.g.: new DefinePlugin({
  414. * "typeof a": "typeof b",
  415. * "typeof b": "typeof a"
  416. * });
  417. */
  418. if (recurseTypeof) return;
  419. recurseTypeof = true;
  420. addValueDependency(originalKey);
  421. const codeCode = toCode(
  422. code,
  423. parser,
  424. compilation.valueCacheVersions,
  425. originalKey,
  426. runtimeTemplate,
  427. null
  428. );
  429. const typeofCode = isTypeof
  430. ? codeCode
  431. : "typeof (" + codeCode + ")";
  432. const res = parser.evaluate(typeofCode);
  433. recurseTypeof = false;
  434. res.setRange(expr.range);
  435. return res;
  436. });
  437. parser.hooks.typeof.for(key).tap("DefinePlugin", expr => {
  438. addValueDependency(originalKey);
  439. const codeCode = toCode(
  440. code,
  441. parser,
  442. compilation.valueCacheVersions,
  443. originalKey,
  444. runtimeTemplate,
  445. null
  446. );
  447. const typeofCode = isTypeof
  448. ? codeCode
  449. : "typeof (" + codeCode + ")";
  450. const res = parser.evaluate(typeofCode);
  451. if (!res.isString()) return;
  452. return toConstantDependency(
  453. parser,
  454. JSON.stringify(res.string)
  455. ).bind(parser)(expr);
  456. });
  457. };
  458. /**
  459. * Apply Object
  460. * @param {string} key Key
  461. * @param {Object} obj Object
  462. * @returns {void}
  463. */
  464. const applyObjectDefine = (key, obj) => {
  465. parser.hooks.canRename.for(key).tap("DefinePlugin", () => {
  466. addValueDependency(key);
  467. return true;
  468. });
  469. parser.hooks.evaluateIdentifier
  470. .for(key)
  471. .tap("DefinePlugin", expr => {
  472. addValueDependency(key);
  473. return new BasicEvaluatedExpression()
  474. .setTruthy()
  475. .setSideEffects(false)
  476. .setRange(expr.range);
  477. });
  478. parser.hooks.evaluateTypeof
  479. .for(key)
  480. .tap(
  481. "DefinePlugin",
  482. withValueDependency(key, evaluateToString("object"))
  483. );
  484. parser.hooks.expression.for(key).tap("DefinePlugin", expr => {
  485. addValueDependency(key);
  486. const strCode = stringifyObj(
  487. obj,
  488. parser,
  489. compilation.valueCacheVersions,
  490. key,
  491. runtimeTemplate,
  492. !parser.isAsiPosition(expr.range[0])
  493. );
  494. if (/__webpack_require__\s*(!?\.)/.test(strCode)) {
  495. return toConstantDependency(parser, strCode, [
  496. RuntimeGlobals.require
  497. ])(expr);
  498. } else if (/__webpack_require__/.test(strCode)) {
  499. return toConstantDependency(parser, strCode, [
  500. RuntimeGlobals.requireScope
  501. ])(expr);
  502. } else {
  503. return toConstantDependency(parser, strCode)(expr);
  504. }
  505. });
  506. parser.hooks.typeof
  507. .for(key)
  508. .tap(
  509. "DefinePlugin",
  510. withValueDependency(
  511. key,
  512. toConstantDependency(parser, JSON.stringify("object"))
  513. )
  514. );
  515. };
  516. walkDefinitions(definitions, "");
  517. };
  518. normalModuleFactory.hooks.parser
  519. .for("javascript/auto")
  520. .tap("DefinePlugin", handler);
  521. normalModuleFactory.hooks.parser
  522. .for("javascript/dynamic")
  523. .tap("DefinePlugin", handler);
  524. normalModuleFactory.hooks.parser
  525. .for("javascript/esm")
  526. .tap("DefinePlugin", handler);
  527. /**
  528. * Walk definitions
  529. * @param {Object} definitions Definitions map
  530. * @param {string} prefix Prefix string
  531. * @returns {void}
  532. */
  533. const walkDefinitionsForValues = (definitions, prefix) => {
  534. Object.keys(definitions).forEach(key => {
  535. const code = definitions[key];
  536. const version = toCacheVersion(code);
  537. const name = VALUE_DEP_PREFIX + prefix + key;
  538. mainHash.update("|" + prefix + key);
  539. const oldVersion = compilation.valueCacheVersions.get(name);
  540. if (oldVersion === undefined) {
  541. compilation.valueCacheVersions.set(name, version);
  542. } else if (oldVersion !== version) {
  543. const warning = new WebpackError(
  544. `DefinePlugin\nConflicting values for '${prefix + key}'`
  545. );
  546. warning.details = `'${oldVersion}' !== '${version}'`;
  547. warning.hideStack = true;
  548. compilation.warnings.push(warning);
  549. }
  550. if (
  551. code &&
  552. typeof code === "object" &&
  553. !(code instanceof RuntimeValue) &&
  554. !(code instanceof RegExp)
  555. ) {
  556. walkDefinitionsForValues(code, prefix + key + ".");
  557. }
  558. });
  559. };
  560. walkDefinitionsForValues(definitions, "");
  561. compilation.valueCacheVersions.set(
  562. VALUE_DEP_MAIN,
  563. /** @type {string} */ (mainHash.digest("hex").slice(0, 8))
  564. );
  565. }
  566. );
  567. }
  568. }
  569. module.exports = DefinePlugin;