DefinePlugin.js 18 KB

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