DefinePlugin.js 17 KB

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