AssignLibraryPlugin.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. return current;
  77. };
  78. /**
  79. * @typedef {object} AssignLibraryPluginOptions
  80. * @property {LibraryType} type
  81. * @property {string[] | "global"} prefix name prefix
  82. * @property {string | false} declare declare name as variable
  83. * @property {"error"|"static"|"copy"|"assign"} unnamed behavior for unnamed library name
  84. * @property {"copy"|"assign"=} named behavior for named library name
  85. */
  86. /**
  87. * @typedef {object} AssignLibraryPluginParsed
  88. * @property {string | string[]} name
  89. * @property {string | string[] | undefined} export
  90. */
  91. /**
  92. * @typedef {AssignLibraryPluginParsed} T
  93. * @extends {AbstractLibraryPlugin<AssignLibraryPluginParsed>}
  94. */
  95. class AssignLibraryPlugin extends AbstractLibraryPlugin {
  96. /**
  97. * @param {AssignLibraryPluginOptions} options the plugin options
  98. */
  99. constructor(options) {
  100. super({
  101. pluginName: "AssignLibraryPlugin",
  102. type: options.type
  103. });
  104. this.prefix = options.prefix;
  105. this.declare = options.declare;
  106. this.unnamed = options.unnamed;
  107. this.named = options.named || "assign";
  108. }
  109. /**
  110. * @param {LibraryOptions} library normalized library option
  111. * @returns {T | false} preprocess as needed by overriding
  112. */
  113. parseOptions(library) {
  114. const { name } = library;
  115. if (this.unnamed === "error") {
  116. if (typeof name !== "string" && !Array.isArray(name)) {
  117. throw new Error(
  118. `Library name must be a string or string array. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}`
  119. );
  120. }
  121. } else if (name && typeof name !== "string" && !Array.isArray(name)) {
  122. throw new Error(
  123. `Library name must be a string, string array or unset. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}`
  124. );
  125. }
  126. const _name = /** @type {string | string[]} */ (name);
  127. return {
  128. name: _name,
  129. export: library.export
  130. };
  131. }
  132. /**
  133. * @param {Module} module the exporting entry module
  134. * @param {string} entryName the name of the entrypoint
  135. * @param {LibraryContext<T>} libraryContext context
  136. * @returns {void}
  137. */
  138. finishEntryModule(
  139. module,
  140. entryName,
  141. { options, compilation, compilation: { moduleGraph } }
  142. ) {
  143. const runtime = getEntryRuntime(compilation, entryName);
  144. if (options.export) {
  145. const exportsInfo = moduleGraph.getExportInfo(
  146. module,
  147. Array.isArray(options.export) ? options.export[0] : options.export
  148. );
  149. exportsInfo.setUsed(UsageState.Used, runtime);
  150. exportsInfo.canMangleUse = false;
  151. } else {
  152. const exportsInfo = moduleGraph.getExportsInfo(module);
  153. exportsInfo.setUsedInUnknownWay(runtime);
  154. }
  155. moduleGraph.addExtraReason(module, "used as library export");
  156. }
  157. /**
  158. * @param {Compilation} compilation the compilation
  159. * @returns {string[]} the prefix
  160. */
  161. _getPrefix(compilation) {
  162. return this.prefix === "global"
  163. ? [compilation.runtimeTemplate.globalObject]
  164. : this.prefix;
  165. }
  166. /**
  167. * @param {AssignLibraryPluginParsed} options the library options
  168. * @param {Chunk} chunk the chunk
  169. * @param {Compilation} compilation the compilation
  170. * @returns {Array<string>} the resolved full name
  171. */
  172. _getResolvedFullName(options, chunk, compilation) {
  173. const prefix = this._getPrefix(compilation);
  174. const fullName = options.name ? prefix.concat(options.name) : prefix;
  175. return fullName.map(n =>
  176. compilation.getPath(n, {
  177. chunk
  178. })
  179. );
  180. }
  181. /**
  182. * @param {Source} source source
  183. * @param {RenderContext} renderContext render context
  184. * @param {LibraryContext<T>} libraryContext context
  185. * @returns {Source} source with library export
  186. */
  187. render(source, { chunk }, { options, compilation }) {
  188. const fullNameResolved = this._getResolvedFullName(
  189. options,
  190. chunk,
  191. compilation
  192. );
  193. if (this.declare) {
  194. const base = fullNameResolved[0];
  195. if (!isNameValid(base)) {
  196. throw new Error(
  197. `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(
  198. base
  199. )}) or use a different library type (e. g. 'type: "global"', which assign a property on the global scope instead of declaring a variable). ${
  200. AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE
  201. }`
  202. );
  203. }
  204. source = new ConcatSource(`${this.declare} ${base};\n`, source);
  205. }
  206. return source;
  207. }
  208. /**
  209. * @param {Module} module the exporting entry module
  210. * @param {RenderContext} renderContext render context
  211. * @param {LibraryContext<T>} libraryContext context
  212. * @returns {string | undefined} bailout reason
  213. */
  214. embedInRuntimeBailout(
  215. module,
  216. { chunk, codeGenerationResults },
  217. { options, compilation }
  218. ) {
  219. const { data } = codeGenerationResults.get(module, chunk.runtime);
  220. const topLevelDeclarations =
  221. (data && data.get("topLevelDeclarations")) ||
  222. (module.buildInfo && module.buildInfo.topLevelDeclarations);
  223. if (!topLevelDeclarations)
  224. return "it doesn't tell about top level declarations.";
  225. const fullNameResolved = this._getResolvedFullName(
  226. options,
  227. chunk,
  228. compilation
  229. );
  230. const base = fullNameResolved[0];
  231. if (topLevelDeclarations.has(base))
  232. return `it declares '${base}' on top-level, which conflicts with the current library output.`;
  233. }
  234. /**
  235. * @param {RenderContext} renderContext render context
  236. * @param {LibraryContext<T>} libraryContext context
  237. * @returns {string | undefined} bailout reason
  238. */
  239. strictRuntimeBailout({ chunk }, { options, compilation }) {
  240. if (
  241. this.declare ||
  242. this.prefix === "global" ||
  243. this.prefix.length > 0 ||
  244. !options.name
  245. ) {
  246. return;
  247. }
  248. return "a global variable is assign and maybe created";
  249. }
  250. /**
  251. * @param {Source} source source
  252. * @param {Module} module module
  253. * @param {StartupRenderContext} renderContext render context
  254. * @param {LibraryContext<T>} libraryContext context
  255. * @returns {Source} source with library export
  256. */
  257. renderStartup(
  258. source,
  259. module,
  260. { moduleGraph, chunk },
  261. { options, compilation }
  262. ) {
  263. const fullNameResolved = this._getResolvedFullName(
  264. options,
  265. chunk,
  266. compilation
  267. );
  268. const staticExports = this.unnamed === "static";
  269. const exportAccess = options.export
  270. ? propertyAccess(
  271. Array.isArray(options.export) ? options.export : [options.export]
  272. )
  273. : "";
  274. const result = new ConcatSource(source);
  275. if (staticExports) {
  276. const exportsInfo = moduleGraph.getExportsInfo(module);
  277. const exportTarget = accessWithInit(
  278. fullNameResolved,
  279. this._getPrefix(compilation).length,
  280. true
  281. );
  282. /** @type {string[]} */
  283. const provided = [];
  284. for (const exportInfo of exportsInfo.orderedExports) {
  285. if (!exportInfo.provided) continue;
  286. const nameAccess = propertyAccess([exportInfo.name]);
  287. result.add(
  288. `${exportTarget}${nameAccess} = ${RuntimeGlobals.exports}${exportAccess}${nameAccess};\n`
  289. );
  290. provided.push(exportInfo.name);
  291. }
  292. const webpackExportTarget = accessWithInit(
  293. fullNameResolved,
  294. this._getPrefix(compilation).length,
  295. true
  296. );
  297. /** @type {string} */
  298. let exports = RuntimeGlobals.exports;
  299. if (exportAccess) {
  300. result.add(
  301. `var __webpack_exports_export__ = ${RuntimeGlobals.exports}${exportAccess};\n`
  302. );
  303. exports = "__webpack_exports_export__";
  304. }
  305. result.add(`for(var __webpack_i__ in ${exports}) {\n`);
  306. const hasProvided = provided.length > 0;
  307. if (hasProvided) {
  308. result.add(
  309. ` if (${JSON.stringify(provided)}.indexOf(__webpack_i__) === -1) {\n`
  310. );
  311. }
  312. result.add(
  313. ` ${hasProvided ? " " : ""}${webpackExportTarget}[__webpack_i__] = ${exports}[__webpack_i__];\n`
  314. );
  315. result.add(hasProvided ? " }\n}\n" : "\n");
  316. result.add(
  317. `Object.defineProperty(${exportTarget}, "__esModule", { value: true });\n`
  318. );
  319. } else if (options.name ? this.named === "copy" : this.unnamed === "copy") {
  320. result.add(
  321. `var __webpack_export_target__ = ${accessWithInit(
  322. fullNameResolved,
  323. this._getPrefix(compilation).length,
  324. true
  325. )};\n`
  326. );
  327. /** @type {string} */
  328. let exports = RuntimeGlobals.exports;
  329. if (exportAccess) {
  330. result.add(
  331. `var __webpack_exports_export__ = ${RuntimeGlobals.exports}${exportAccess};\n`
  332. );
  333. exports = "__webpack_exports_export__";
  334. }
  335. result.add(
  336. `for(var __webpack_i__ in ${exports}) __webpack_export_target__[__webpack_i__] = ${exports}[__webpack_i__];\n`
  337. );
  338. result.add(
  339. `if(${exports}.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });\n`
  340. );
  341. } else {
  342. result.add(
  343. `${accessWithInit(
  344. fullNameResolved,
  345. this._getPrefix(compilation).length,
  346. false
  347. )} = ${RuntimeGlobals.exports}${exportAccess};\n`
  348. );
  349. }
  350. return result;
  351. }
  352. /**
  353. * @param {Chunk} chunk the chunk
  354. * @param {Set<string>} set runtime requirements
  355. * @param {LibraryContext<T>} libraryContext context
  356. * @returns {void}
  357. */
  358. runtimeRequirements(chunk, set, libraryContext) {
  359. set.add(RuntimeGlobals.exports);
  360. }
  361. /**
  362. * @param {Chunk} chunk the chunk
  363. * @param {Hash} hash hash
  364. * @param {ChunkHashContext} chunkHashContext chunk hash context
  365. * @param {LibraryContext<T>} libraryContext context
  366. * @returns {void}
  367. */
  368. chunkHash(chunk, hash, chunkHashContext, { options, compilation }) {
  369. hash.update("AssignLibraryPlugin");
  370. const fullNameResolved = this._getResolvedFullName(
  371. options,
  372. chunk,
  373. compilation
  374. );
  375. if (options.name ? this.named === "copy" : this.unnamed === "copy") {
  376. hash.update("copy");
  377. }
  378. if (this.declare) {
  379. hash.update(this.declare);
  380. }
  381. hash.update(fullNameResolved.join("."));
  382. if (options.export) {
  383. hash.update(`${options.export}`);
  384. }
  385. }
  386. }
  387. module.exports = AssignLibraryPlugin;