DefinePlugin.js 19 KB

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