AssignLibraryPlugin.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { ConcatSource } = require("webpack-sources");
  7. const { UsageState } = require("../ExportsInfo");
  8. const RuntimeGlobals = require("../RuntimeGlobals");
  9. const Template = require("../Template");
  10. const propertyAccess = require("../util/propertyAccess");
  11. const { getEntryRuntime } = require("../util/runtime");
  12. const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
  13. /** @typedef {import("webpack-sources").Source} Source */
  14. /** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
  15. /** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */
  16. /** @typedef {import("../Chunk")} Chunk */
  17. /** @typedef {import("../Compilation")} Compilation */
  18. /** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */
  19. /** @typedef {import("../Module")} Module */
  20. /** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
  21. /** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */
  22. /** @typedef {import("../util/Hash")} Hash */
  23. /** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext<T>} LibraryContext<T> */
  24. const KEYWORD_REGEX =
  25. /^(await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|super|switch|static|this|throw|try|true|typeof|var|void|while|with|yield)$/;
  26. const IDENTIFIER_REGEX =
  27. /^[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$/iu;
  28. /**
  29. * Validates the library name by checking for keywords and valid characters
  30. * @param {string} name name to be validated
  31. * @returns {boolean} true, when valid
  32. */
  33. const isNameValid = name =>
  34. !KEYWORD_REGEX.test(name) && IDENTIFIER_REGEX.test(name);
  35. /**
  36. * @param {string[]} accessor variable plus properties
  37. * @param {number} existingLength items of accessor that are existing already
  38. * @param {boolean=} initLast if the last property should also be initialized to an object
  39. * @returns {string} code to access the accessor while initializing
  40. */
  41. const accessWithInit = (accessor, existingLength, initLast = false) => {
  42. // This generates for [a, b, c, d]:
  43. // (((a = typeof a === "undefined" ? {} : a).b = a.b || {}).c = a.b.c || {}).d
  44. const base = accessor[0];
  45. if (accessor.length === 1 && !initLast) return base;
  46. let current =
  47. existingLength > 0
  48. ? base
  49. : `(${base} = typeof ${base} === "undefined" ? {} : ${base})`;
  50. // i is the current position in accessor that has been printed
  51. let i = 1;
  52. // all properties printed so far (excluding base)
  53. /** @type {string[] | undefined} */
  54. let propsSoFar;
  55. // if there is existingLength, print all properties until this position as property access
  56. if (existingLength > i) {
  57. propsSoFar = accessor.slice(1, existingLength);
  58. i = existingLength;
  59. current += propertyAccess(propsSoFar);
  60. } else {
  61. propsSoFar = [];
  62. }
  63. // all remaining properties (except the last one when initLast is not set)
  64. // should be printed as initializer
  65. const initUntil = initLast ? accessor.length : accessor.length - 1;
  66. for (; i < initUntil; i++) {
  67. const prop = accessor[i];
  68. propsSoFar.push(prop);
  69. current = `(${current}${propertyAccess([prop])} = ${base}${propertyAccess(
  70. propsSoFar
  71. )} || {})`;
  72. }
  73. // print the last property as property access if not yet printed
  74. if (i < accessor.length) {
  75. current = `${current}${propertyAccess([accessor[accessor.length - 1]])}`;
  76. }
  77. return current;
  78. };
  79. /**
  80. * @typedef {object} AssignLibraryPluginOptions
  81. * @property {LibraryType} type
  82. * @property {string[] | "global"} prefix name prefix
  83. * @property {string | false} declare declare name as variable
  84. * @property {"error"|"static"|"copy"|"assign"} unnamed behavior for unnamed library name
  85. * @property {"copy"|"assign"=} named behavior for named library name
  86. */
  87. /**
  88. * @typedef {object} AssignLibraryPluginParsed
  89. * @property {string | string[]} name
  90. * @property {string | string[] | undefined} export
  91. */
  92. /**
  93. * @typedef {AssignLibraryPluginParsed} T
  94. * @extends {AbstractLibraryPlugin<AssignLibraryPluginParsed>}
  95. */
  96. class AssignLibraryPlugin extends AbstractLibraryPlugin {
  97. /**
  98. * @param {AssignLibraryPluginOptions} options the plugin options
  99. */
  100. constructor(options) {
  101. super({
  102. pluginName: "AssignLibraryPlugin",
  103. type: options.type
  104. });
  105. this.prefix = options.prefix;
  106. this.declare = options.declare;
  107. this.unnamed = options.unnamed;
  108. this.named = options.named || "assign";
  109. }
  110. /**
  111. * @param {LibraryOptions} library normalized library option
  112. * @returns {T | false} preprocess as needed by overriding
  113. */
  114. parseOptions(library) {
  115. const { name } = library;
  116. if (this.unnamed === "error") {
  117. if (typeof name !== "string" && !Array.isArray(name)) {
  118. throw new Error(
  119. `Library name must be a string or string array. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}`
  120. );
  121. }
  122. } else if (name && typeof name !== "string" && !Array.isArray(name)) {
  123. throw new Error(
  124. `Library name must be a string, string array or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}`
  125. );
  126. }
  127. const _name = /** @type {string | string[]} */ (name);
  128. return {
  129. name: _name,
  130. export: library.export
  131. };
  132. }
  133. /**
  134. * @param {Module} module the exporting entry module
  135. * @param {string} entryName the name of the entrypoint
  136. * @param {LibraryContext<T>} libraryContext context
  137. * @returns {void}
  138. */
  139. finishEntryModule(
  140. module,
  141. entryName,
  142. { options, compilation, compilation: { moduleGraph } }
  143. ) {
  144. const runtime = getEntryRuntime(compilation, entryName);
  145. if (options.export) {
  146. const exportsInfo = moduleGraph.getExportInfo(
  147. module,
  148. Array.isArray(options.export) ? options.export[0] : options.export
  149. );
  150. exportsInfo.setUsed(UsageState.Used, runtime);
  151. exportsInfo.canMangleUse = false;
  152. } else {
  153. const exportsInfo = moduleGraph.getExportsInfo(module);
  154. exportsInfo.setUsedInUnknownWay(runtime);
  155. }
  156. moduleGraph.addExtraReason(module, "used as library export");
  157. }
  158. /**
  159. * @param {Compilation} compilation the compilation
  160. * @returns {string[]} the prefix
  161. */
  162. _getPrefix(compilation) {
  163. return this.prefix === "global"
  164. ? [compilation.runtimeTemplate.globalObject]
  165. : this.prefix;
  166. }
  167. /**
  168. * @param {AssignLibraryPluginParsed} options the library options
  169. * @param {Chunk} chunk the chunk
  170. * @param {Compilation} compilation the compilation
  171. * @returns {Array<string>} the resolved full name
  172. */
  173. _getResolvedFullName(options, chunk, compilation) {
  174. const prefix = this._getPrefix(compilation);
  175. const fullName = options.name
  176. ? [
  177. ...prefix,
  178. ...(Array.isArray(options.name) ? options.name : [options.name])
  179. ]
  180. : prefix;
  181. return fullName.map(n =>
  182. compilation.getPath(n, {
  183. chunk
  184. })
  185. );
  186. }
  187. /**
  188. * @param {Source} source source
  189. * @param {RenderContext} renderContext render context
  190. * @param {LibraryContext<T>} libraryContext context
  191. * @returns {Source} source with library export
  192. */
  193. render(source, { chunk }, { options, compilation }) {
  194. const fullNameResolved = this._getResolvedFullName(
  195. options,
  196. chunk,
  197. compilation
  198. );
  199. if (this.declare) {
  200. const base = fullNameResolved[0];
  201. if (!isNameValid(base)) {
  202. throw new Error(
  203. `Library name base (${base}) must be a valid identifier when using a var declaring library type. Either use a valid identifier (e. g. ${Template.toIdentifier(
  204. base
  205. )}) or use a different library type (e. g. 'type: "global"', which assign a property on the global scope instead of declaring a variable). ${
  206. AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE
  207. }`
  208. );
  209. }
  210. source = new ConcatSource(`${this.declare} ${base};\n`, source);
  211. }
  212. return source;
  213. }
  214. /**
  215. * @param {Module} module the exporting entry module
  216. * @param {RenderContext} renderContext render context
  217. * @param {LibraryContext<T>} libraryContext context
  218. * @returns {string | undefined} bailout reason
  219. */
  220. embedInRuntimeBailout(
  221. module,
  222. { chunk, codeGenerationResults },
  223. { options, compilation }
  224. ) {
  225. const { data } = codeGenerationResults.get(module, chunk.runtime);
  226. const topLevelDeclarations =
  227. (data && data.get("topLevelDeclarations")) ||
  228. (module.buildInfo && module.buildInfo.topLevelDeclarations);
  229. if (!topLevelDeclarations) {
  230. return "it doesn't tell about top level declarations.";
  231. }
  232. const fullNameResolved = this._getResolvedFullName(
  233. options,
  234. chunk,
  235. compilation
  236. );
  237. const base = fullNameResolved[0];
  238. if (topLevelDeclarations.has(base)) {
  239. return `it declares '${base}' on top-level, which conflicts with the current library output.`;
  240. }
  241. }
  242. /**
  243. * @param {RenderContext} renderContext render context
  244. * @param {LibraryContext<T>} libraryContext context
  245. * @returns {string | undefined} bailout reason
  246. */
  247. strictRuntimeBailout({ chunk }, { options, compilation }) {
  248. if (
  249. this.declare ||
  250. this.prefix === "global" ||
  251. this.prefix.length > 0 ||
  252. !options.name
  253. ) {
  254. return;
  255. }
  256. return "a global variable is assign and maybe created";
  257. }
  258. /**
  259. * @param {Source} source source
  260. * @param {Module} module module
  261. * @param {StartupRenderContext} renderContext render context
  262. * @param {LibraryContext<T>} libraryContext context
  263. * @returns {Source} source with library export
  264. */
  265. renderStartup(
  266. source,
  267. module,
  268. { moduleGraph, chunk },
  269. { options, compilation }
  270. ) {
  271. const fullNameResolved = this._getResolvedFullName(
  272. options,
  273. chunk,
  274. compilation
  275. );
  276. const staticExports = this.unnamed === "static";
  277. const exportAccess = options.export
  278. ? propertyAccess(
  279. Array.isArray(options.export) ? options.export : [options.export]
  280. )
  281. : "";
  282. const result = new ConcatSource(source);
  283. if (staticExports) {
  284. const exportsInfo = moduleGraph.getExportsInfo(module);
  285. const exportTarget = accessWithInit(
  286. fullNameResolved,
  287. this._getPrefix(compilation).length,
  288. true
  289. );
  290. /** @type {string[]} */
  291. const provided = [];
  292. for (const exportInfo of exportsInfo.orderedExports) {
  293. if (!exportInfo.provided) continue;
  294. const nameAccess = propertyAccess([exportInfo.name]);
  295. result.add(
  296. `${exportTarget}${nameAccess} = ${RuntimeGlobals.exports}${exportAccess}${nameAccess};\n`
  297. );
  298. provided.push(exportInfo.name);
  299. }
  300. const webpackExportTarget = accessWithInit(
  301. fullNameResolved,
  302. this._getPrefix(compilation).length,
  303. true
  304. );
  305. /** @type {string} */
  306. let exports = RuntimeGlobals.exports;
  307. if (exportAccess) {
  308. result.add(
  309. `var __webpack_exports_export__ = ${RuntimeGlobals.exports}${exportAccess};\n`
  310. );
  311. exports = "__webpack_exports_export__";
  312. }
  313. result.add(`for(var __webpack_i__ in ${exports}) {\n`);
  314. const hasProvided = provided.length > 0;
  315. if (hasProvided) {
  316. result.add(
  317. ` if (${JSON.stringify(provided)}.indexOf(__webpack_i__) === -1) {\n`
  318. );
  319. }
  320. result.add(
  321. ` ${
  322. hasProvided ? " " : ""
  323. }${webpackExportTarget}[__webpack_i__] = ${exports}[__webpack_i__];\n`
  324. );
  325. if (hasProvided) {
  326. result.add(" }\n");
  327. }
  328. result.add("}\n");
  329. result.add(
  330. `Object.defineProperty(${exportTarget}, "__esModule", { value: true });\n`
  331. );
  332. } else if (options.name ? this.named === "copy" : this.unnamed === "copy") {
  333. result.add(
  334. `var __webpack_export_target__ = ${accessWithInit(
  335. fullNameResolved,
  336. this._getPrefix(compilation).length,
  337. true
  338. )};\n`
  339. );
  340. /** @type {string} */
  341. let exports = RuntimeGlobals.exports;
  342. if (exportAccess) {
  343. result.add(
  344. `var __webpack_exports_export__ = ${RuntimeGlobals.exports}${exportAccess};\n`
  345. );
  346. exports = "__webpack_exports_export__";
  347. }
  348. result.add(
  349. `for(var __webpack_i__ in ${exports}) __webpack_export_target__[__webpack_i__] = ${exports}[__webpack_i__];\n`
  350. );
  351. result.add(
  352. `if(${exports}.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });\n`
  353. );
  354. } else {
  355. result.add(
  356. `${accessWithInit(
  357. fullNameResolved,
  358. this._getPrefix(compilation).length,
  359. false
  360. )} = ${RuntimeGlobals.exports}${exportAccess};\n`
  361. );
  362. }
  363. return result;
  364. }
  365. /**
  366. * @param {Chunk} chunk the chunk
  367. * @param {Set<string>} set runtime requirements
  368. * @param {LibraryContext<T>} libraryContext context
  369. * @returns {void}
  370. */
  371. runtimeRequirements(chunk, set, libraryContext) {
  372. set.add(RuntimeGlobals.exports);
  373. }
  374. /**
  375. * @param {Chunk} chunk the chunk
  376. * @param {Hash} hash hash
  377. * @param {ChunkHashContext} chunkHashContext chunk hash context
  378. * @param {LibraryContext<T>} libraryContext context
  379. * @returns {void}
  380. */
  381. chunkHash(chunk, hash, chunkHashContext, { options, compilation }) {
  382. hash.update("AssignLibraryPlugin");
  383. const fullNameResolved = this._getResolvedFullName(
  384. options,
  385. chunk,
  386. compilation
  387. );
  388. if (options.name ? this.named === "copy" : this.unnamed === "copy") {
  389. hash.update("copy");
  390. }
  391. if (this.declare) {
  392. hash.update(this.declare);
  393. }
  394. hash.update(fullNameResolved.join("."));
  395. if (options.export) {
  396. hash.update(`${options.export}`);
  397. }
  398. }
  399. }
  400. module.exports = AssignLibraryPlugin;