DefinePlugin.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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 = /__webpack_require__\s*(!?\.)/;
  293. const WEBPACK_REQUIRE_IDENTIFIER_REGEXP = /__webpack_require__/;
  294. class DefinePlugin {
  295. /**
  296. * Create a new define plugin
  297. * @param {Record<string, CodeValue>} definitions A map of global object definitions
  298. */
  299. constructor(definitions) {
  300. this.definitions = definitions;
  301. }
  302. /**
  303. * @param {function({ module: NormalModule, key: string, readonly version: string | undefined }): CodeValuePrimitive} fn generator function
  304. * @param {true | string[] | RuntimeValueOptions=} options options
  305. * @returns {RuntimeValue} runtime value
  306. */
  307. static runtimeValue(fn, options) {
  308. return new RuntimeValue(fn, options);
  309. }
  310. /**
  311. * Apply the plugin
  312. * @param {Compiler} compiler the compiler instance
  313. * @returns {void}
  314. */
  315. apply(compiler) {
  316. const definitions = this.definitions;
  317. compiler.hooks.compilation.tap(
  318. PLUGIN_NAME,
  319. (compilation, { normalModuleFactory }) => {
  320. const logger = compilation.getLogger("webpack.DefinePlugin");
  321. compilation.dependencyTemplates.set(
  322. ConstDependency,
  323. new ConstDependency.Template()
  324. );
  325. const { runtimeTemplate } = compilation;
  326. const mainHash = createHash(compilation.outputOptions.hashFunction);
  327. mainHash.update(
  328. /** @type {string} */ (
  329. compilation.valueCacheVersions.get(VALUE_DEP_MAIN)
  330. ) || ""
  331. );
  332. /**
  333. * Handler
  334. * @param {JavascriptParser} parser Parser
  335. * @returns {void}
  336. */
  337. const handler = parser => {
  338. const mainValue = compilation.valueCacheVersions.get(VALUE_DEP_MAIN);
  339. parser.hooks.program.tap(PLUGIN_NAME, () => {
  340. const buildInfo = /** @type {BuildInfo} */ (
  341. parser.state.module.buildInfo
  342. );
  343. if (!buildInfo.valueDependencies)
  344. buildInfo.valueDependencies = new Map();
  345. buildInfo.valueDependencies.set(VALUE_DEP_MAIN, mainValue);
  346. });
  347. /**
  348. * @param {string} key key
  349. */
  350. const addValueDependency = key => {
  351. const buildInfo = /** @type {BuildInfo} */ (
  352. parser.state.module.buildInfo
  353. );
  354. buildInfo.valueDependencies.set(
  355. VALUE_DEP_PREFIX + key,
  356. compilation.valueCacheVersions.get(VALUE_DEP_PREFIX + key)
  357. );
  358. };
  359. const withValueDependency =
  360. (key, fn) =>
  361. (...args) => {
  362. addValueDependency(key);
  363. return fn(...args);
  364. };
  365. /**
  366. * Walk definitions
  367. * @param {Record<string, CodeValue>} definitions Definitions map
  368. * @param {string} prefix Prefix string
  369. * @returns {void}
  370. */
  371. const walkDefinitions = (definitions, prefix) => {
  372. Object.keys(definitions).forEach(key => {
  373. const code = definitions[key];
  374. if (
  375. code &&
  376. typeof code === "object" &&
  377. !(code instanceof RuntimeValue) &&
  378. !(code instanceof RegExp)
  379. ) {
  380. walkDefinitions(
  381. /** @type {Record<string, CodeValue>} */ (code),
  382. prefix + key + "."
  383. );
  384. applyObjectDefine(prefix + key, code);
  385. return;
  386. }
  387. applyDefineKey(prefix, key);
  388. applyDefine(prefix + key, code);
  389. });
  390. };
  391. /**
  392. * Apply define key
  393. * @param {string} prefix Prefix
  394. * @param {string} key Key
  395. * @returns {void}
  396. */
  397. const applyDefineKey = (prefix, key) => {
  398. const splittedKey = key.split(".");
  399. splittedKey.slice(1).forEach((_, i) => {
  400. const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
  401. parser.hooks.canRename.for(fullKey).tap(PLUGIN_NAME, () => {
  402. addValueDependency(key);
  403. return true;
  404. });
  405. });
  406. };
  407. /**
  408. * Apply Code
  409. * @param {string} key Key
  410. * @param {CodeValue} code Code
  411. * @returns {void}
  412. */
  413. const applyDefine = (key, code) => {
  414. const originalKey = key;
  415. const isTypeof = TYPEOF_OPERATOR_REGEXP.test(key);
  416. if (isTypeof) key = key.replace(TYPEOF_OPERATOR_REGEXP, "");
  417. let recurse = false;
  418. let recurseTypeof = false;
  419. if (!isTypeof) {
  420. parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => {
  421. addValueDependency(originalKey);
  422. return true;
  423. });
  424. parser.hooks.evaluateIdentifier
  425. .for(key)
  426. .tap(PLUGIN_NAME, expr => {
  427. /**
  428. * this is needed in case there is a recursion in the DefinePlugin
  429. * to prevent an endless recursion
  430. * e.g.: new DefinePlugin({
  431. * "a": "b",
  432. * "b": "a"
  433. * });
  434. */
  435. if (recurse) return;
  436. addValueDependency(originalKey);
  437. recurse = true;
  438. const res = parser.evaluate(
  439. toCode(
  440. code,
  441. parser,
  442. compilation.valueCacheVersions,
  443. key,
  444. runtimeTemplate,
  445. logger,
  446. null
  447. )
  448. );
  449. recurse = false;
  450. res.setRange(/** @type {Range} */ (expr.range));
  451. return res;
  452. });
  453. parser.hooks.expression.for(key).tap(PLUGIN_NAME, expr => {
  454. addValueDependency(originalKey);
  455. let strCode = toCode(
  456. code,
  457. parser,
  458. compilation.valueCacheVersions,
  459. originalKey,
  460. runtimeTemplate,
  461. logger,
  462. !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
  463. parser.destructuringAssignmentPropertiesFor(expr)
  464. );
  465. if (parser.scope.inShorthand) {
  466. strCode = parser.scope.inShorthand + ":" + strCode;
  467. }
  468. if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
  469. return toConstantDependency(parser, strCode, [
  470. RuntimeGlobals.require
  471. ])(expr);
  472. } else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) {
  473. return toConstantDependency(parser, strCode, [
  474. RuntimeGlobals.requireScope
  475. ])(expr);
  476. } else {
  477. return toConstantDependency(parser, strCode)(expr);
  478. }
  479. });
  480. }
  481. parser.hooks.evaluateTypeof.for(key).tap(PLUGIN_NAME, expr => {
  482. /**
  483. * this is needed in case there is a recursion in the DefinePlugin
  484. * to prevent an endless recursion
  485. * e.g.: new DefinePlugin({
  486. * "typeof a": "typeof b",
  487. * "typeof b": "typeof a"
  488. * });
  489. */
  490. if (recurseTypeof) return;
  491. recurseTypeof = true;
  492. addValueDependency(originalKey);
  493. const codeCode = toCode(
  494. code,
  495. parser,
  496. compilation.valueCacheVersions,
  497. originalKey,
  498. runtimeTemplate,
  499. logger,
  500. null
  501. );
  502. const typeofCode = isTypeof
  503. ? codeCode
  504. : "typeof (" + codeCode + ")";
  505. const res = parser.evaluate(typeofCode);
  506. recurseTypeof = false;
  507. res.setRange(/** @type {Range} */ (expr.range));
  508. return res;
  509. });
  510. parser.hooks.typeof.for(key).tap(PLUGIN_NAME, expr => {
  511. addValueDependency(originalKey);
  512. const codeCode = toCode(
  513. code,
  514. parser,
  515. compilation.valueCacheVersions,
  516. originalKey,
  517. runtimeTemplate,
  518. logger,
  519. null
  520. );
  521. const typeofCode = isTypeof
  522. ? codeCode
  523. : "typeof (" + codeCode + ")";
  524. const res = parser.evaluate(typeofCode);
  525. if (!res.isString()) return;
  526. return toConstantDependency(
  527. parser,
  528. JSON.stringify(res.string)
  529. ).bind(parser)(expr);
  530. });
  531. };
  532. /**
  533. * Apply Object
  534. * @param {string} key Key
  535. * @param {Object} obj Object
  536. * @returns {void}
  537. */
  538. const applyObjectDefine = (key, obj) => {
  539. parser.hooks.canRename.for(key).tap(PLUGIN_NAME, () => {
  540. addValueDependency(key);
  541. return true;
  542. });
  543. parser.hooks.evaluateIdentifier.for(key).tap(PLUGIN_NAME, expr => {
  544. addValueDependency(key);
  545. return new BasicEvaluatedExpression()
  546. .setTruthy()
  547. .setSideEffects(false)
  548. .setRange(/** @type {Range} */ (expr.range));
  549. });
  550. parser.hooks.evaluateTypeof
  551. .for(key)
  552. .tap(
  553. PLUGIN_NAME,
  554. withValueDependency(key, evaluateToString("object"))
  555. );
  556. parser.hooks.expression.for(key).tap(PLUGIN_NAME, expr => {
  557. addValueDependency(key);
  558. let strCode = stringifyObj(
  559. obj,
  560. parser,
  561. compilation.valueCacheVersions,
  562. key,
  563. runtimeTemplate,
  564. logger,
  565. !parser.isAsiPosition(/** @type {Range} */ (expr.range)[0]),
  566. parser.destructuringAssignmentPropertiesFor(expr)
  567. );
  568. if (parser.scope.inShorthand) {
  569. strCode = parser.scope.inShorthand + ":" + strCode;
  570. }
  571. if (WEBPACK_REQUIRE_FUNCTION_REGEXP.test(strCode)) {
  572. return toConstantDependency(parser, strCode, [
  573. RuntimeGlobals.require
  574. ])(expr);
  575. } else if (WEBPACK_REQUIRE_IDENTIFIER_REGEXP.test(strCode)) {
  576. return toConstantDependency(parser, strCode, [
  577. RuntimeGlobals.requireScope
  578. ])(expr);
  579. } else {
  580. return toConstantDependency(parser, strCode)(expr);
  581. }
  582. });
  583. parser.hooks.typeof
  584. .for(key)
  585. .tap(
  586. PLUGIN_NAME,
  587. withValueDependency(
  588. key,
  589. toConstantDependency(parser, JSON.stringify("object"))
  590. )
  591. );
  592. };
  593. walkDefinitions(definitions, "");
  594. };
  595. normalModuleFactory.hooks.parser
  596. .for(JAVASCRIPT_MODULE_TYPE_AUTO)
  597. .tap(PLUGIN_NAME, handler);
  598. normalModuleFactory.hooks.parser
  599. .for(JAVASCRIPT_MODULE_TYPE_DYNAMIC)
  600. .tap(PLUGIN_NAME, handler);
  601. normalModuleFactory.hooks.parser
  602. .for(JAVASCRIPT_MODULE_TYPE_ESM)
  603. .tap(PLUGIN_NAME, handler);
  604. /**
  605. * Walk definitions
  606. * @param {Record<string, CodeValue>} definitions Definitions map
  607. * @param {string} prefix Prefix string
  608. * @returns {void}
  609. */
  610. const walkDefinitionsForValues = (definitions, prefix) => {
  611. Object.keys(definitions).forEach(key => {
  612. const code = definitions[key];
  613. const version = toCacheVersion(code);
  614. const name = VALUE_DEP_PREFIX + prefix + key;
  615. mainHash.update("|" + prefix + key);
  616. const oldVersion = compilation.valueCacheVersions.get(name);
  617. if (oldVersion === undefined) {
  618. compilation.valueCacheVersions.set(name, version);
  619. } else if (oldVersion !== version) {
  620. const warning = new WebpackError(
  621. `${PLUGIN_NAME}\nConflicting values for '${prefix + key}'`
  622. );
  623. warning.details = `'${oldVersion}' !== '${version}'`;
  624. warning.hideStack = true;
  625. compilation.warnings.push(warning);
  626. }
  627. if (
  628. code &&
  629. typeof code === "object" &&
  630. !(code instanceof RuntimeValue) &&
  631. !(code instanceof RegExp)
  632. ) {
  633. walkDefinitionsForValues(
  634. /** @type {Record<string, CodeValue>} */ (code),
  635. prefix + key + "."
  636. );
  637. }
  638. });
  639. };
  640. walkDefinitionsForValues(definitions, "");
  641. compilation.valueCacheVersions.set(
  642. VALUE_DEP_MAIN,
  643. /** @type {string} */ (mainHash.digest("hex").slice(0, 8))
  644. );
  645. }
  646. );
  647. }
  648. }
  649. module.exports = DefinePlugin;