DefinePlugin.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { SyncWaterfallHook } = require("tapable");
  7. const {
  8. JAVASCRIPT_MODULE_TYPE_AUTO,
  9. JAVASCRIPT_MODULE_TYPE_DYNAMIC,
  10. JAVASCRIPT_MODULE_TYPE_ESM
  11. } = require("./ModuleTypeConstants");
  12. const RuntimeGlobals = require("./RuntimeGlobals");
  13. const WebpackError = require("./WebpackError");
  14. const ConstDependency = require("./dependencies/ConstDependency");
  15. const BasicEvaluatedExpression = require("./javascript/BasicEvaluatedExpression");
  16. const { VariableInfo } = require("./javascript/JavascriptParser");
  17. const {
  18. evaluateToString,
  19. toConstantDependency
  20. } = require("./javascript/JavascriptParserHelpers");
  21. const createHash = require("./util/createHash");
  22. /** @typedef {import("estree").Expression} Expression */
  23. /** @typedef {import("./Compiler")} Compiler */
  24. /** @typedef {import("./Module").BuildInfo} BuildInfo */
  25. /** @typedef {import("./Module").ValueCacheVersion} ValueCacheVersion */
  26. /** @typedef {import("./Module").ValueCacheVersions} ValueCacheVersions */
  27. /** @typedef {import("./NormalModule")} NormalModule */
  28. /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
  29. /** @typedef {import("./javascript/JavascriptParser")} JavascriptParser */
  30. /** @typedef {import("./javascript/JavascriptParser").DestructuringAssignmentProperties} DestructuringAssignmentProperties */
  31. /** @typedef {import("./javascript/JavascriptParser").Range} Range */
  32. /** @typedef {import("./logging/Logger").Logger} Logger */
  33. /** @typedef {import("./Compilation")} Compilation */
  34. /** @typedef {null | undefined | RegExp | EXPECTED_FUNCTION | string | number | boolean | bigint | undefined} CodeValuePrimitive */
  35. /** @typedef {RecursiveArrayOrRecord<CodeValuePrimitive | RuntimeValue>} CodeValue */
  36. /**
  37. * Defines the runtime value options type used by this module.
  38. * @typedef {object} RuntimeValueOptions
  39. * @property {string[]=} fileDependencies
  40. * @property {string[]=} contextDependencies
  41. * @property {string[]=} missingDependencies
  42. * @property {string[]=} buildDependencies
  43. * @property {string | (() => string)=} version
  44. */
  45. /** @typedef {(value: { module: NormalModule, key: string, readonly version: ValueCacheVersion }) => CodeValuePrimitive} GeneratorFn */
  46. class RuntimeValue {
  47. /**
  48. * Creates an instance of RuntimeValue.
  49. * @param {GeneratorFn} fn generator function
  50. * @param {true | string[] | RuntimeValueOptions=} options options
  51. */
  52. constructor(fn, options) {
  53. /** @type {GeneratorFn} */
  54. this.fn = fn;
  55. if (Array.isArray(options)) {
  56. options = {
  57. fileDependencies: options
  58. };
  59. }
  60. /** @type {true | RuntimeValueOptions} */
  61. this.options = options || {};
  62. }
  63. get fileDependencies() {
  64. return this.options === true ? true : this.options.fileDependencies;
  65. }
  66. /**
  67. * Returns code.
  68. * @param {JavascriptParser} parser the parser
  69. * @param {ValueCacheVersions} valueCacheVersions valueCacheVersions
  70. * @param {string} key the defined key
  71. * @returns {CodeValuePrimitive} code
  72. */
  73. exec(parser, valueCacheVersions, key) {
  74. const buildInfo = /** @type {BuildInfo} */ (parser.state.module.buildInfo);
  75. if (this.options === true) {
  76. buildInfo.cacheable = false;
  77. } else {
  78. if (this.options.fileDependencies) {
  79. for (const dep of this.options.fileDependencies) {
  80. /** @type {NonNullable<BuildInfo["fileDependencies"]>} */
  81. (buildInfo.fileDependencies).add(dep);
  82. }
  83. }
  84. if (this.options.contextDependencies) {
  85. for (const dep of this.options.contextDependencies) {
  86. /** @type {NonNullable<BuildInfo["contextDependencies"]>} */
  87. (buildInfo.contextDependencies).add(dep);
  88. }
  89. }
  90. if (this.options.missingDependencies) {
  91. for (const dep of this.options.missingDependencies) {
  92. /** @type {NonNullable<BuildInfo["missingDependencies"]>} */
  93. (buildInfo.missingDependencies).add(dep);
  94. }
  95. }
  96. if (this.options.buildDependencies) {
  97. for (const dep of this.options.buildDependencies) {
  98. /** @type {NonNullable<BuildInfo["buildDependencies"]>} */
  99. (buildInfo.buildDependencies).add(dep);
  100. }
  101. }
  102. }
  103. return this.fn({
  104. module: parser.state.module,
  105. key,
  106. get version() {
  107. return /** @type {ValueCacheVersion} */ (
  108. valueCacheVersions.get(VALUE_DEP_PREFIX + key)
  109. );
  110. }
  111. });
  112. }
  113. getCacheVersion() {
  114. return this.options === true
  115. ? undefined
  116. : (typeof this.options.version === "function"
  117. ? this.options.version()
  118. : this.options.version) || "unset";
  119. }
  120. }
  121. /**
  122. * Returns used keys.
  123. * @param {DestructuringAssignmentProperties | undefined} properties properties
  124. * @returns {Set<string> | undefined} used keys
  125. */
  126. function getObjKeys(properties) {
  127. if (!properties) return;
  128. return new Set([...properties].map((p) => p.id));
  129. }
  130. /** @typedef {Set<string> | null} ObjKeys */
  131. /** @typedef {boolean | undefined | null} AsiSafe */
  132. /**
  133. * Returns code converted to string that evaluates.
  134. * @param {EXPECTED_ANY[] | { [k: string]: EXPECTED_ANY }} obj obj
  135. * @param {JavascriptParser} parser Parser
  136. * @param {ValueCacheVersions} valueCacheVersions valueCacheVersions
  137. * @param {string} key the defined key
  138. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  139. * @param {Logger} logger the logger object
  140. * @param {AsiSafe=} asiSafe asi safe (undefined: unknown, null: unneeded)
  141. * @param {ObjKeys=} objKeys used keys
  142. * @returns {string} code converted to string that evaluates
  143. */
  144. const stringifyObj = (
  145. obj,
  146. parser,
  147. valueCacheVersions,
  148. key,
  149. runtimeTemplate,
  150. logger,
  151. asiSafe,
  152. objKeys
  153. ) => {
  154. /** @type {string} */
  155. let code;
  156. const arr = Array.isArray(obj);
  157. if (arr) {
  158. code = `[${obj
  159. .map((code) =>
  160. toCode(
  161. code,
  162. parser,
  163. valueCacheVersions,
  164. key,
  165. runtimeTemplate,
  166. logger,
  167. null
  168. )
  169. )
  170. .join(",")}]`;
  171. } else {
  172. let keys = Object.keys(obj);
  173. if (objKeys) {
  174. keys = objKeys.size === 0 ? [] : keys.filter((k) => objKeys.has(k));
  175. }
  176. code = `{${keys
  177. .map((key) => {
  178. const code = obj[key];
  179. return `${key === "__proto__" ? '["__proto__"]' : JSON.stringify(key)}:${toCode(
  180. code,
  181. parser,
  182. valueCacheVersions,
  183. key,
  184. runtimeTemplate,
  185. logger,
  186. null
  187. )}`;
  188. })
  189. .join(",")}}`;
  190. }
  191. switch (asiSafe) {
  192. case null:
  193. return code;
  194. case true:
  195. return arr ? code : `(${code})`;
  196. case false:
  197. return arr ? `;${code}` : `;(${code})`;
  198. default:
  199. return `/*#__PURE__*/Object(${code})`;
  200. }
  201. };
  202. /**
  203. * Convert code to a string that evaluates
  204. * @param {CodeValue} code Code to evaluate
  205. * @param {JavascriptParser} parser Parser
  206. * @param {ValueCacheVersions} valueCacheVersions valueCacheVersions
  207. * @param {string} key the defined key
  208. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  209. * @param {Logger} logger the logger object
  210. * @param {boolean | undefined | null=} asiSafe asi safe (undefined: unknown, null: unneeded)
  211. * @param {ObjKeys=} objKeys used keys
  212. * @returns {string} code converted to string that evaluates
  213. */
  214. const toCode = (
  215. code,
  216. parser,
  217. valueCacheVersions,
  218. key,
  219. runtimeTemplate,
  220. logger,
  221. asiSafe,
  222. objKeys
  223. ) => {
  224. const transformToCode = () => {
  225. if (code === null) {
  226. return "null";
  227. }
  228. if (code === undefined) {
  229. return "undefined";
  230. }
  231. if (Object.is(code, -0)) {
  232. return "-0";
  233. }
  234. if (code instanceof RuntimeValue) {
  235. return toCode(
  236. code.exec(parser, valueCacheVersions, key),
  237. parser,
  238. valueCacheVersions,
  239. key,
  240. runtimeTemplate,
  241. logger,
  242. asiSafe
  243. );
  244. }
  245. if (code instanceof RegExp && code.toString) {
  246. return code.toString();
  247. }
  248. if (typeof code === "function" && code.toString) {
  249. return `(${code.toString()})`;
  250. }
  251. if (typeof code === "object") {
  252. return stringifyObj(
  253. code,
  254. parser,
  255. valueCacheVersions,
  256. key,
  257. runtimeTemplate,
  258. logger,
  259. asiSafe,
  260. objKeys
  261. );
  262. }
  263. if (typeof code === "bigint") {
  264. return runtimeTemplate.supportsBigIntLiteral()
  265. ? `${code}n`
  266. : `BigInt("${code}")`;
  267. }
  268. return `${code}`;
  269. };
  270. const strCode = transformToCode();
  271. logger.debug(`Replaced "${key}" with "${strCode}"`);
  272. return strCode;
  273. };
  274. /**
  275. * Returns result.
  276. * @param {CodeValue} code code
  277. * @returns {string | undefined} result
  278. */
  279. const toCacheVersion = (code) => {
  280. if (code === null) {
  281. return "null";
  282. }
  283. if (code === undefined) {
  284. return "undefined";
  285. }
  286. if (Object.is(code, -0)) {
  287. return "-0";
  288. }
  289. if (code instanceof RuntimeValue) {
  290. return code.getCacheVersion();
  291. }
  292. if (code instanceof RegExp && code.toString) {
  293. return code.toString();
  294. }
  295. if (typeof code === "function" && code.toString) {
  296. return `(${code.toString()})`;
  297. }
  298. if (typeof code === "object") {
  299. const items = Object.keys(code).map((key) => ({
  300. key,
  301. value: toCacheVersion(
  302. /** @type {Record<string, EXPECTED_ANY>} */
  303. (code)[key]
  304. )
  305. }));
  306. if (items.some(({ value }) => value === undefined)) return;
  307. return `{${items.map(({ key, value }) => `${key}: ${value}`).join(", ")}}`;
  308. }
  309. if (typeof code === "bigint") {
  310. return `${code}n`;
  311. }
  312. return `${code}`;
  313. };
  314. const PLUGIN_NAME = "DefinePlugin";
  315. const VALUE_DEP_PREFIX = `webpack/${PLUGIN_NAME} `;
  316. const VALUE_DEP_MAIN = `webpack/${PLUGIN_NAME}_hash`;
  317. const TYPEOF_OPERATOR_REGEXP = /^typeof\s+/;
  318. const WEBPACK_REQUIRE_FUNCTION_REGEXP = new RegExp(
  319. `${RuntimeGlobals.require}\\s*(!?\\.)`
  320. );
  321. const WEBPACK_REQUIRE_IDENTIFIER_REGEXP = new RegExp(RuntimeGlobals.require);
  322. /**
  323. * Defines the define plugin hooks type used by this module.
  324. * @typedef {object} DefinePluginHooks
  325. * @property {SyncWaterfallHook<[Record<string, CodeValue>]>} definitions
  326. */
  327. /** @typedef {Record<string, CodeValue>} Definitions */
  328. /** @type {WeakMap<Compilation, DefinePluginHooks>} */
  329. const compilationHooksMap = new WeakMap();
  330. class DefinePlugin {
  331. /**
  332. * Returns the attached hooks.
  333. * @param {Compilation} compilation the compilation
  334. * @returns {DefinePluginHooks} the attached hooks
  335. */
  336. static getCompilationHooks(compilation) {
  337. let hooks = compilationHooksMap.get(compilation);
  338. if (hooks === undefined) {
  339. hooks = {
  340. definitions: new SyncWaterfallHook(["definitions"])
  341. };
  342. compilationHooksMap.set(compilation, hooks);
  343. }
  344. return hooks;
  345. }
  346. /**
  347. * Create a new define plugin
  348. * @param {Definitions} definitions A map of global object definitions
  349. */
  350. constructor(definitions) {
  351. /** @type {Definitions} */
  352. this.definitions = definitions;
  353. }
  354. /**
  355. * Returns runtime value.
  356. * @param {GeneratorFn} fn generator function
  357. * @param {true | string[] | RuntimeValueOptions=} options options
  358. * @returns {RuntimeValue} runtime value
  359. */
  360. static runtimeValue(fn, options) {
  361. return new RuntimeValue(fn, options);
  362. }
  363. /**
  364. * Applies the plugin by registering its hooks on the compiler.
  365. * @param {Compiler} compiler the compiler instance
  366. * @returns {void}
  367. */
  368. apply(compiler) {
  369. compiler.hooks.compilation.tap(
  370. PLUGIN_NAME,
  371. (compilation, { normalModuleFactory }) => {
  372. const definitions = this.definitions;
  373. const hooks = DefinePlugin.getCompilationHooks(compilation);
  374. hooks.definitions.tap(PLUGIN_NAME, (previousDefinitions) => ({
  375. ...previousDefinitions,
  376. ...definitions
  377. }));
  378. /**
  379. * @type {Map<string, Set<string>>}
  380. */
  381. const finalByNestedKey = new Map();
  382. /**
  383. * @type {Map<string, Set<string>>}
  384. */
  385. const nestedByFinalKey = new Map();
  386. const logger = compilation.getLogger("webpack.DefinePlugin");
  387. compilation.dependencyTemplates.set(
  388. ConstDependency,
  389. new ConstDependency.Template()
  390. );
  391. const { runtimeTemplate } = compilation;
  392. const mainHash = createHash(compilation.outputOptions.hashFunction);
  393. mainHash.update(
  394. /** @type {string} */
  395. (compilation.valueCacheVersions.get(VALUE_DEP_MAIN)) || ""
  396. );
  397. /**
  398. * Handles the hook callback for this code path.
  399. * @param {JavascriptParser} parser Parser
  400. * @returns {void}
  401. */
  402. const handler = (parser) => {
  403. /** @type {Set<string>} */
  404. const hooked = new Set();
  405. const mainValue =
  406. /** @type {ValueCacheVersion} */
  407. (compilation.valueCacheVersions.get(VALUE_DEP_MAIN));
  408. parser.hooks.program.tap(PLUGIN_NAME, () => {
  409. const buildInfo = /** @type {BuildInfo} */ (
  410. parser.state.module.buildInfo
  411. );
  412. if (!buildInfo.valueDependencies) {
  413. buildInfo.valueDependencies = new Map();
  414. }
  415. buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue);
  416. });
  417. /**
  418. * Adds value dependency.
  419. * @param {string} key key
  420. */
  421. const addValueDependency = (key) => {
  422. const buildInfo =
  423. /** @type {BuildInfo} */
  424. (parser.state.module.buildInfo);
  425. /** @type {NonNullable<BuildInfo["valueDependencies"]>} */
  426. (buildInfo.valueDependencies).set(
  427. VALUE_DEP_PREFIX + key,
  428. /** @type {ValueCacheVersion} */
  429. (compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key))
  430. );
  431. };
  432. /**
  433. * With value dependency.
  434. * @template T
  435. * @param {string} key key
  436. * @param {(expression: Expression) => T} fn fn
  437. * @returns {(expression: Expression) => T} result
  438. */
  439. const withValueDependency =
  440. (key, fn) =>
  441. (...args) => {
  442. addValueDependency(key);
  443. return fn(...args);
  444. };
  445. /**
  446. * Processes the provided definition.
  447. * @param {Definitions} definitions Definitions map
  448. * @param {string} prefix Prefix string
  449. * @returns {void}
  450. */
  451. const walkDefinitions = (definitions, prefix) => {
  452. for (const key of Object.keys(definitions)) {
  453. const code = definitions[key];
  454. if (
  455. code &&
  456. typeof code === "object" &&
  457. !(code instanceof RuntimeValue) &&
  458. !(code instanceof RegExp)
  459. ) {
  460. walkDefinitions(
  461. /** @type {Definitions} */ (code),
  462. `${prefix + key}.`
  463. );
  464. applyObjectDefine(prefix + key, code);
  465. continue;
  466. }
  467. applyDefineKey(prefix, key);
  468. applyDefine(prefix + key, code);
  469. }
  470. };
  471. /**
  472. * Processes the provided prefix.
  473. * @param {string} prefix Prefix
  474. * @param {string} key Key
  475. * @returns {void}
  476. */
  477. const applyDefineKey = (prefix, key) => {
  478. const splittedKey = key.split(".");
  479. const firstKey = splittedKey[0];
  480. for (const [i, _] of splittedKey.slice(1).entries()) {
  481. const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
  482. parser.hooks.canRename.for(fullKey).tap(PLUGIN_NAME, () => {
  483. addValueDependency(key);
  484. if (
  485. parser.scope.definitions.get(firstKey) instanceof VariableInfo
  486. ) {
  487. return false;
  488. }
  489. return true;
  490. });
  491. }
  492. if (prefix === "") {
  493. const final = splittedKey[splittedKey.length - 1];
  494. const nestedSet = nestedByFinalKey.get(final);
  495. if (!nestedSet || nestedSet.size <= 0) return;
  496. for (const nested of /** @type {Set<string>} */ (nestedSet)) {
  497. if (nested && !hooked.has(nested)) {
  498. // only detect the same nested key once
  499. hooked.add(nested);
  500. parser.hooks.collectDestructuringAssignmentProperties.tap(
  501. PLUGIN_NAME,
  502. (expr) => {
  503. const nameInfo = parser.getNameForExpression(expr);
  504. if (nameInfo && nameInfo.name === nested) return true;
  505. }
  506. );
  507. parser.hooks.expression.for(nested).tap(
  508. {
  509. name: PLUGIN_NAME,
  510. // why 100? Ensures it runs after object define
  511. stage: 100
  512. },
  513. (expr) => {
  514. const destructed =
  515. parser.destructuringAssignmentPropertiesFor(expr);
  516. if (destructed === undefined) {
  517. return;
  518. }
  519. /** @type {Definitions} */
  520. const obj = Object.create(null);
  521. const finalSet = finalByNestedKey.get(nested);
  522. for (const { id } of destructed) {
  523. const fullKey = `${nested}.${id}`;
  524. if (
  525. !finalSet ||
  526. !finalSet.has(id) ||
  527. !definitions[fullKey]
  528. ) {
  529. return;
  530. }
  531. obj[id] = definitions[fullKey];
  532. }
  533. let strCode = stringifyObj(
  534. obj,
  535. parser,
  536. compilation.valueCacheVersions,
  537. key,
  538. runtimeTemplate,
  539. logger,
  540. !parser.isAsiPosition(
  541. /** @type {Range} */ (expr.range)[0]
  542. ),
  543. getObjKeys(destructed)
  544. );
  545. if (parser.scope.inShorthand) {
  546. strCode = `${parser.scope.inShorthand}:${strCode}`;
  547. }
  548. return toConstantDependency(parser, strCode)(expr);
  549. }
  550. );
  551. }
  552. }
  553. }
  554. };
  555. /**
  556. * Processes the provided key.
  557. * @param {string} key Key
  558. * @param {CodeValue} code Code
  559. * @returns {void}
  560. */
  561. const applyDefine = (key, code) => {
  562. const originalKey = key;
  563. const isTypeof = TYPEOF_OPERATOR_REGEXP.test(key);
  564. if (isTypeof) key = key.replace(TYPEOF_OPERATOR_REGEXP, "");
  565. let recurse = false;
  566. let recurseTypeof = false;
  567. if (!isTypeof) {
  568. parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => {
  569. addValueDependency(originalKey);
  570. return true;
  571. });
  572. parser.hooks.evaluateIdentifier
  573. .for(key)
  574. .tap(PLUGIN_NAME, (expr) => {
  575. /**
  576. * this is needed in case there is a recursion in the DefinePlugin
  577. * to prevent an endless recursion
  578. * e.g.: new DefinePlugin({
  579. * "a": "b",
  580. * "b": "a"
  581. * });
  582. */
  583. if (recurse) return;
  584. addValueDependency(originalKey);
  585. recurse = true;
  586. const res = parser.evaluate(
  587. toCode(
  588. code,
  589. parser,
  590. compilation.valueCacheVersions,
  591. key,
  592. runtimeTemplate,
  593. logger,
  594. null
  595. )
  596. );
  597. recurse = false;
  598. res.setRange(/** @type {Range} */ (expr.range));
  599. return res;
  600. });
  601. parser.hooks.expression.for(key).tap(PLUGIN_NAME, (expr) => {
  602. addValueDependency(originalKey);
  603. let strCode = toCode(
  604. code,
  605. parser,
  606. compilation.valueCacheVersions,
  607. originalKey,
  608. runtimeTemplate,
  609. logger,
  610. !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
  611. null
  612. );
  613. if (parser.scope.inShorthand) {
  614. strCode = `${parser.scope.inShorthand}:${strCode}`;
  615. }
  616. if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
  617. return toConstantDependency(parser, strCode, [
  618. RuntimeGlobals.require
  619. ])(expr);
  620. } else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) {
  621. return toConstantDependency(parser, strCode, [
  622. RuntimeGlobals.requireScope
  623. ])(expr);
  624. }
  625. return toConstantDependency(parser, strCode)(expr);
  626. });
  627. }
  628. parser.hooks.evaluateTypeof.for(key).tap(PLUGIN_NAME, (expr) => {
  629. /**
  630. * this is needed in case there is a recursion in the DefinePlugin
  631. * to prevent an endless recursion
  632. * e.g.: new DefinePlugin({
  633. * "typeof a": "typeof b",
  634. * "typeof b": "typeof a"
  635. * });
  636. */
  637. if (recurseTypeof) return;
  638. recurseTypeof = true;
  639. addValueDependency(originalKey);
  640. const codeCode = toCode(
  641. code,
  642. parser,
  643. compilation.valueCacheVersions,
  644. originalKey,
  645. runtimeTemplate,
  646. logger,
  647. null
  648. );
  649. const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`;
  650. const res = parser.evaluate(typeofCode);
  651. recurseTypeof = false;
  652. res.setRange(/** @type {Range} */ (expr.range));
  653. return res;
  654. });
  655. parser.hooks.typeof.for(key).tap(PLUGIN_NAME, (expr) => {
  656. addValueDependency(originalKey);
  657. const codeCode = toCode(
  658. code,
  659. parser,
  660. compilation.valueCacheVersions,
  661. originalKey,
  662. runtimeTemplate,
  663. logger,
  664. null
  665. );
  666. const typeofCode = isTypeof ? codeCode : `typeof (${codeCode})`;
  667. const res = parser.evaluate(typeofCode);
  668. if (!res.isString()) return;
  669. return toConstantDependency(
  670. parser,
  671. JSON.stringify(res.string)
  672. ).bind(parser)(expr);
  673. });
  674. };
  675. /**
  676. * Processes the provided key.
  677. * @param {string} key Key
  678. * @param {object} obj Object
  679. * @returns {void}
  680. */
  681. const applyObjectDefine = (key, obj) => {
  682. parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => {
  683. addValueDependency(key);
  684. return true;
  685. });
  686. parser.hooks.evaluateIdentifier
  687. .for(key)
  688. .tap(PLUGIN_NAME, (expr) => {
  689. addValueDependency(key);
  690. return new BasicEvaluatedExpression()
  691. .setTruthy()
  692. .setSideEffects(false)
  693. .setRange(/** @type {Range} */ (expr.range));
  694. });
  695. parser.hooks.evaluateTypeof
  696. .for(key)
  697. .tap(
  698. PLUGIN_NAME,
  699. withValueDependency(key, evaluateToString("object"))
  700. );
  701. parser.hooks.collectDestructuringAssignmentProperties.tap(
  702. PLUGIN_NAME,
  703. (expr) => {
  704. const nameInfo = parser.getNameForExpression(expr);
  705. if (nameInfo && nameInfo.name === key) return true;
  706. }
  707. );
  708. parser.hooks.expression.for(key).tap(PLUGIN_NAME, (expr) => {
  709. addValueDependency(key);
  710. let strCode = stringifyObj(
  711. obj,
  712. parser,
  713. compilation.valueCacheVersions,
  714. key,
  715. runtimeTemplate,
  716. logger,
  717. !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
  718. getObjKeys(parser.destructuringAssignmentPropertiesFor(expr))
  719. );
  720. if (parser.scope.inShorthand) {
  721. strCode = `${parser.scope.inShorthand}:${strCode}`;
  722. }
  723. if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
  724. return toConstantDependency(parser, strCode, [
  725. RuntimeGlobals.require
  726. ])(expr);
  727. } else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) {
  728. return toConstantDependency(parser, strCode, [
  729. RuntimeGlobals.requireScope
  730. ])(expr);
  731. }
  732. return toConstantDependency(parser, strCode)(expr);
  733. });
  734. parser.hooks.typeof
  735. .for(key)
  736. .tap(
  737. PLUGIN_NAME,
  738. withValueDependency(
  739. key,
  740. toConstantDependency(parser, JSON.stringify("object"))
  741. )
  742. );
  743. };
  744. walkDefinitions(definitions, "");
  745. };
  746. normalModuleFactory.hooks.parser
  747. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  748. .tap(PLUGIN_NAME, handler);
  749. normalModuleFactory.hooks.parser
  750. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  751. .tap(PLUGIN_NAME, handler);
  752. normalModuleFactory.hooks.parser
  753. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  754. .tap(PLUGIN_NAME, handler);
  755. /**
  756. * Processes the provided definition.
  757. * @param {Definitions} definitions Definitions map
  758. * @param {string} prefix Prefix string
  759. * @returns {void}
  760. */
  761. const walkDefinitionsForValues = (definitions, prefix) => {
  762. for (const key of Object.keys(definitions)) {
  763. const code = definitions[key];
  764. const version = /** @type {string} */ (toCacheVersion(code));
  765. const name = VALUE_DEP_PREFIX + prefix + key;
  766. mainHash.update(`|${prefix}${key}`);
  767. const oldVersion = compilation.valueCacheVersions.get(name);
  768. if (oldVersion === undefined) {
  769. compilation.valueCacheVersions.set(name, version);
  770. } else if (oldVersion !== version) {
  771. const warning = new WebpackError(
  772. `${PLUGIN_NAME}\nConflicting values for '${prefix + key}'`
  773. );
  774. warning.details = `'${oldVersion}' !== '${version}'`;
  775. warning.hideStack = true;
  776. compilation.warnings.push(warning);
  777. }
  778. if (
  779. code &&
  780. typeof code === "object" &&
  781. !(code instanceof RuntimeValue) &&
  782. !(code instanceof RegExp)
  783. ) {
  784. walkDefinitionsForValues(
  785. /** @type {Definitions} */ (code),
  786. `${prefix + key}.`
  787. );
  788. }
  789. }
  790. };
  791. /**
  792. * Walk definitions for keys.
  793. * @param {Definitions} definitions Definitions map
  794. * @returns {void}
  795. */
  796. const walkDefinitionsForKeys = (definitions) => {
  797. /**
  798. * Adds the provided map to the define plugin.
  799. * @param {Map<string, Set<string>>} map Map
  800. * @param {string} key key
  801. * @param {string} value v
  802. * @returns {void}
  803. */
  804. const addToMap = (map, key, value) => {
  805. if (map.has(key)) {
  806. /** @type {Set<string>} */
  807. (map.get(key)).add(value);
  808. } else {
  809. map.set(key, new Set([value]));
  810. }
  811. };
  812. for (const key of Object.keys(definitions)) {
  813. const code = definitions[key];
  814. if (
  815. !code ||
  816. typeof code === "object" ||
  817. TYPEOF_OPERATOR_REGEXP.test(key)
  818. ) {
  819. continue;
  820. }
  821. const idx = key.lastIndexOf(".");
  822. if (idx <= 0 || idx >= key.length - 1) {
  823. continue;
  824. }
  825. const nested = key.slice(0, idx);
  826. const final = key.slice(idx + 1);
  827. addToMap(finalByNestedKey, nested, final);
  828. addToMap(nestedByFinalKey, final, nested);
  829. }
  830. };
  831. walkDefinitionsForKeys(definitions);
  832. walkDefinitionsForValues(definitions, "");
  833. compilation.valueCacheVersions.set(
  834. VALUE_DEP_MAIN,
  835. mainHash.digest("hex").slice(0, 8)
  836. );
  837. }
  838. );
  839. }
  840. }
  841. module.exports = DefinePlugin;