AssignLibraryPlugin.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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("../Compiler")} Compiler */
  20. /** @typedef {import("../Module")} Module */
  21. /** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
  22. /** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */
  23. /** @typedef {import("../util/Hash")} Hash */
  24. /** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext<T>} LibraryContext<T> */
  25. const KEYWORD_REGEX =
  26. /^(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)$/;
  27. const IDENTIFIER_REGEX =
  28. /^[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$/iu;
  29. /**
  30. * Validates the library name by checking for keywords and valid characters
  31. * @param {string} name name to be validated
  32. * @returns {boolean} true, when valid
  33. */
  34. const isNameValid = name =>
  35. !KEYWORD_REGEX.test(name) && IDENTIFIER_REGEX.test(name);
  36. /**
  37. * @param {string[]} accessor variable plus properties
  38. * @param {number} existingLength items of accessor that are existing already
  39. * @param {boolean=} initLast if the last property should also be initialized to an object
  40. * @returns {string} code to access the accessor while initializing
  41. */
  42. const accessWithInit = (accessor, existingLength, initLast = false) => {
  43. // This generates for [a, b, c, d]:
  44. // (((a = typeof a === "undefined" ? {} : a).b = a.b || {}).c = a.b.c || {}).d
  45. const base = accessor[0];
  46. if (accessor.length === 1 && !initLast) return base;
  47. let current =
  48. existingLength > 0
  49. ? base
  50. : `(${base} = typeof ${base} === "undefined" ? {} : ${base})`;
  51. // i is the current position in accessor that has been printed
  52. let i = 1;
  53. // all properties printed so far (excluding base)
  54. /** @type {string[] | undefined} */
  55. let propsSoFar;
  56. // if there is existingLength, print all properties until this position as property access
  57. if (existingLength > i) {
  58. propsSoFar = accessor.slice(1, existingLength);
  59. i = existingLength;
  60. current += propertyAccess(propsSoFar);
  61. } else {
  62. propsSoFar = [];
  63. }
  64. // all remaining properties (except the last one when initLast is not set)
  65. // should be printed as initializer
  66. const initUntil = initLast ? accessor.length : accessor.length - 1;
  67. for (; i < initUntil; i++) {
  68. const prop = accessor[i];
  69. propsSoFar.push(prop);
  70. current = `(${current}${propertyAccess([prop])} = ${base}${propertyAccess(
  71. propsSoFar
  72. )} || {})`;
  73. }
  74. // print the last property as property access if not yet printed
  75. if (i < accessor.length)
  76. current = `${current}${propertyAccess([accessor[accessor.length - 1]])}`;
  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 ? prefix.concat(options.name) : prefix;
  176. return fullName.map(n =>
  177. compilation.getPath(n, {
  178. chunk
  179. })
  180. );
  181. }
  182. /**
  183. * @param {Source} source source
  184. * @param {RenderContext} renderContext render context
  185. * @param {LibraryContext<T>} libraryContext context
  186. * @returns {Source} source with library export
  187. */
  188. render(source, { chunk }, { options, compilation }) {
  189. const fullNameResolved = this._getResolvedFullName(
  190. options,
  191. chunk,
  192. compilation
  193. );
  194. if (this.declare) {
  195. const base = fullNameResolved[0];
  196. if (!isNameValid(base)) {
  197. throw new Error(
  198. `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(
  199. base
  200. )}) or use a different library type (e. g. 'type: "global"', which assign a property on the global scope instead of declaring a variable). ${
  201. AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE
  202. }`
  203. );
  204. }
  205. source = new ConcatSource(`${this.declare} ${base};\n`, source);
  206. }
  207. return source;
  208. }
  209. /**
  210. * @param {Module} module the exporting entry module
  211. * @param {RenderContext} renderContext render context
  212. * @param {LibraryContext<T>} libraryContext context
  213. * @returns {string | undefined} bailout reason
  214. */
  215. embedInRuntimeBailout(
  216. module,
  217. { chunk, codeGenerationResults },
  218. { options, compilation }
  219. ) {
  220. const { data } = codeGenerationResults.get(module, chunk.runtime);
  221. const topLevelDeclarations =
  222. (data && data.get("topLevelDeclarations")) ||
  223. (module.buildInfo && module.buildInfo.topLevelDeclarations);
  224. if (!topLevelDeclarations)
  225. return "it doesn't tell about top level declarations.";
  226. const fullNameResolved = this._getResolvedFullName(
  227. options,
  228. chunk,
  229. compilation
  230. );
  231. const base = fullNameResolved[0];
  232. if (topLevelDeclarations.has(base))
  233. return `it declares '${base}' on top-level, which conflicts with the current library output.`;
  234. }
  235. /**
  236. * @param {RenderContext} renderContext render context
  237. * @param {LibraryContext<T>} libraryContext context
  238. * @returns {string | undefined} bailout reason
  239. */
  240. strictRuntimeBailout({ chunk }, { options, compilation }) {
  241. if (
  242. this.declare ||
  243. this.prefix === "global" ||
  244. this.prefix.length > 0 ||
  245. !options.name
  246. ) {
  247. return;
  248. }
  249. return "a global variable is assign and maybe created";
  250. }
  251. /**
  252. * @param {Source} source source
  253. * @param {Module} module module
  254. * @param {StartupRenderContext} renderContext render context
  255. * @param {LibraryContext<T>} libraryContext context
  256. * @returns {Source} source with library export
  257. */
  258. renderStartup(
  259. source,
  260. module,
  261. { moduleGraph, chunk },
  262. { options, compilation }
  263. ) {
  264. const fullNameResolved = this._getResolvedFullName(
  265. options,
  266. chunk,
  267. compilation
  268. );
  269. const staticExports = this.unnamed === "static";
  270. const exportAccess = options.export
  271. ? propertyAccess(
  272. Array.isArray(options.export) ? options.export : [options.export]
  273. )
  274. : "";
  275. const result = new ConcatSource(source);
  276. if (staticExports) {
  277. const exportsInfo = moduleGraph.getExportsInfo(module);
  278. const exportTarget = accessWithInit(
  279. fullNameResolved,
  280. this._getPrefix(compilation).length,
  281. true
  282. );
  283. for (const exportInfo of exportsInfo.orderedExports) {
  284. if (!exportInfo.provided) continue;
  285. const nameAccess = propertyAccess([exportInfo.name]);
  286. result.add(
  287. `${exportTarget}${nameAccess} = ${RuntimeGlobals.exports}${exportAccess}${nameAccess};\n`
  288. );
  289. }
  290. result.add(
  291. `Object.defineProperty(${exportTarget}, "__esModule", { value: true });\n`
  292. );
  293. } else if (options.name ? this.named === "copy" : this.unnamed === "copy") {
  294. result.add(
  295. `var __webpack_export_target__ = ${accessWithInit(
  296. fullNameResolved,
  297. this._getPrefix(compilation).length,
  298. true
  299. )};\n`
  300. );
  301. /** @type {string} */
  302. let exports = RuntimeGlobals.exports;
  303. if (exportAccess) {
  304. result.add(
  305. `var __webpack_exports_export__ = ${RuntimeGlobals.exports}${exportAccess};\n`
  306. );
  307. exports = "__webpack_exports_export__";
  308. }
  309. result.add(
  310. `for(var __webpack_i__ in ${exports}) __webpack_export_target__[__webpack_i__] = ${exports}[__webpack_i__];\n`
  311. );
  312. result.add(
  313. `if(${exports}.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });\n`
  314. );
  315. } else {
  316. result.add(
  317. `${accessWithInit(
  318. fullNameResolved,
  319. this._getPrefix(compilation).length,
  320. false
  321. )} = ${RuntimeGlobals.exports}${exportAccess};\n`
  322. );
  323. }
  324. return result;
  325. }
  326. /**
  327. * @param {Chunk} chunk the chunk
  328. * @param {Set<string>} set runtime requirements
  329. * @param {LibraryContext<T>} libraryContext context
  330. * @returns {void}
  331. */
  332. runtimeRequirements(chunk, set, libraryContext) {
  333. set.add(RuntimeGlobals.exports);
  334. }
  335. /**
  336. * @param {Chunk} chunk the chunk
  337. * @param {Hash} hash hash
  338. * @param {ChunkHashContext} chunkHashContext chunk hash context
  339. * @param {LibraryContext<T>} libraryContext context
  340. * @returns {void}
  341. */
  342. chunkHash(chunk, hash, chunkHashContext, { options, compilation }) {
  343. hash.update("AssignLibraryPlugin");
  344. const fullNameResolved = this._getResolvedFullName(
  345. options,
  346. chunk,
  347. compilation
  348. );
  349. if (options.name ? this.named === "copy" : this.unnamed === "copy") {
  350. hash.update("copy");
  351. }
  352. if (this.declare) {
  353. hash.update(this.declare);
  354. }
  355. hash.update(fullNameResolved.join("."));
  356. if (options.export) {
  357. hash.update(`${options.export}`);
  358. }
  359. }
  360. }
  361. module.exports = AssignLibraryPlugin;