AssignLibraryPlugin.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 Template = require("../Template");
  9. const propertyAccess = require("../util/propertyAccess");
  10. const { getEntryRuntime } = require("../util/runtime");
  11. const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
  12. /** @typedef {import("webpack-sources").Source} Source */
  13. /** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
  14. /** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */
  15. /** @typedef {import("../Chunk")} Chunk */
  16. /** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */
  17. /** @typedef {import("../Compiler")} Compiler */
  18. /** @typedef {import("../Module")} Module */
  19. /** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
  20. /** @typedef {import("../javascript/JavascriptModulesPlugin").StartupRenderContext} StartupRenderContext */
  21. /** @typedef {import("../util/Hash")} Hash */
  22. /** @template T @typedef {import("./AbstractLibraryPlugin").LibraryContext<T>} LibraryContext<T> */
  23. const KEYWORD_REGEX =
  24. /^(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)$/;
  25. const IDENTIFIER_REGEX =
  26. /^[\p{L}\p{Nl}$_][\p{L}\p{Nl}$\p{Mn}\p{Mc}\p{Nd}\p{Pc}]*$/iu;
  27. /**
  28. * Validates the library name by checking for keywords and valid characters
  29. * @param {string} name name to be validated
  30. * @returns {boolean} true, when valid
  31. */
  32. const isNameValid = name => {
  33. return !KEYWORD_REGEX.test(name) && IDENTIFIER_REGEX.test(name);
  34. };
  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. let propsSoFar;
  54. // if there is existingLength, print all properties until this position as property access
  55. if (existingLength > i) {
  56. propsSoFar = accessor.slice(1, existingLength);
  57. i = existingLength;
  58. current += propertyAccess(propsSoFar);
  59. } else {
  60. propsSoFar = [];
  61. }
  62. // all remaining properties (except the last one when initLast is not set)
  63. // should be printed as initializer
  64. const initUntil = initLast ? accessor.length : accessor.length - 1;
  65. for (; i < initUntil; i++) {
  66. const prop = accessor[i];
  67. propsSoFar.push(prop);
  68. current = `(${current}${propertyAccess([prop])} = ${base}${propertyAccess(
  69. propsSoFar
  70. )} || {})`;
  71. }
  72. // print the last property as property access if not yet printed
  73. if (i < accessor.length)
  74. current = `${current}${propertyAccess([accessor[accessor.length - 1]])}`;
  75. return current;
  76. };
  77. /**
  78. * @typedef {Object} AssignLibraryPluginOptions
  79. * @property {LibraryType} type
  80. * @property {string[] | "global"} prefix name prefix
  81. * @property {string | false} declare declare name as variable
  82. * @property {"error"|"static"|"copy"|"assign"} unnamed behavior for unnamed library name
  83. * @property {"copy"|"assign"=} named behavior for named library name
  84. */
  85. /**
  86. * @typedef {Object} AssignLibraryPluginParsed
  87. * @property {string | string[]} name
  88. * @property {string | string[] | undefined} export
  89. */
  90. /**
  91. * @typedef {AssignLibraryPluginParsed} T
  92. * @extends {AbstractLibraryPlugin<AssignLibraryPluginParsed>}
  93. */
  94. class AssignLibraryPlugin extends AbstractLibraryPlugin {
  95. /**
  96. * @param {AssignLibraryPluginOptions} options the plugin options
  97. */
  98. constructor(options) {
  99. super({
  100. pluginName: "AssignLibraryPlugin",
  101. type: options.type
  102. });
  103. this.prefix = options.prefix;
  104. this.declare = options.declare;
  105. this.unnamed = options.unnamed;
  106. this.named = options.named || "assign";
  107. }
  108. /**
  109. * @param {LibraryOptions} library normalized library option
  110. * @returns {T | false} preprocess as needed by overriding
  111. */
  112. parseOptions(library) {
  113. const { name } = library;
  114. if (this.unnamed === "error") {
  115. if (typeof name !== "string" && !Array.isArray(name)) {
  116. throw new Error(
  117. `Library name must be a string or string array. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}`
  118. );
  119. }
  120. } else {
  121. 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. }
  127. return {
  128. name: /** @type {string|string[]=} */ (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. _getPrefix(compilation) {
  158. return this.prefix === "global"
  159. ? [compilation.runtimeTemplate.globalObject]
  160. : this.prefix;
  161. }
  162. _getResolvedFullName(options, chunk, compilation) {
  163. const prefix = this._getPrefix(compilation);
  164. const fullName = options.name ? prefix.concat(options.name) : prefix;
  165. return fullName.map(n =>
  166. compilation.getPath(n, {
  167. chunk
  168. })
  169. );
  170. }
  171. /**
  172. * @param {Source} source source
  173. * @param {RenderContext} renderContext render context
  174. * @param {LibraryContext<T>} libraryContext context
  175. * @returns {Source} source with library export
  176. */
  177. render(source, { chunk }, { options, compilation }) {
  178. const fullNameResolved = this._getResolvedFullName(
  179. options,
  180. chunk,
  181. compilation
  182. );
  183. if (this.declare) {
  184. const base = fullNameResolved[0];
  185. if (!isNameValid(base)) {
  186. throw new Error(
  187. `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(
  188. base
  189. )}) or use a different library type (e. g. 'type: "global"', which assign a property on the global scope instead of declaring a variable). ${
  190. AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE
  191. }`
  192. );
  193. }
  194. source = new ConcatSource(`${this.declare} ${base};\n`, source);
  195. }
  196. return source;
  197. }
  198. /**
  199. * @param {Module} module the exporting entry module
  200. * @param {RenderContext} renderContext render context
  201. * @param {LibraryContext<T>} libraryContext context
  202. * @returns {string | undefined} bailout reason
  203. */
  204. embedInRuntimeBailout(
  205. module,
  206. { chunk, codeGenerationResults },
  207. { options, compilation }
  208. ) {
  209. const { data } = codeGenerationResults.get(module, chunk.runtime);
  210. const topLevelDeclarations =
  211. (data && data.get("topLevelDeclarations")) ||
  212. (module.buildInfo && module.buildInfo.topLevelDeclarations);
  213. if (!topLevelDeclarations)
  214. return "it doesn't tell about top level declarations.";
  215. const fullNameResolved = this._getResolvedFullName(
  216. options,
  217. chunk,
  218. compilation
  219. );
  220. const base = fullNameResolved[0];
  221. if (topLevelDeclarations.has(base))
  222. return `it declares '${base}' on top-level, which conflicts with the current library output.`;
  223. }
  224. /**
  225. * @param {RenderContext} renderContext render context
  226. * @param {LibraryContext<T>} libraryContext context
  227. * @returns {string | undefined} bailout reason
  228. */
  229. strictRuntimeBailout({ chunk }, { options, compilation }) {
  230. if (
  231. this.declare ||
  232. this.prefix === "global" ||
  233. this.prefix.length > 0 ||
  234. !options.name
  235. ) {
  236. return;
  237. }
  238. return "a global variable is assign and maybe created";
  239. }
  240. /**
  241. * @param {Source} source source
  242. * @param {Module} module module
  243. * @param {StartupRenderContext} renderContext render context
  244. * @param {LibraryContext<T>} libraryContext context
  245. * @returns {Source} source with library export
  246. */
  247. renderStartup(
  248. source,
  249. module,
  250. { moduleGraph, chunk },
  251. { options, compilation }
  252. ) {
  253. const fullNameResolved = this._getResolvedFullName(
  254. options,
  255. chunk,
  256. compilation
  257. );
  258. const staticExports = this.unnamed === "static";
  259. const exportAccess = options.export
  260. ? propertyAccess(
  261. Array.isArray(options.export) ? options.export : [options.export]
  262. )
  263. : "";
  264. const result = new ConcatSource(source);
  265. if (staticExports) {
  266. const exportsInfo = moduleGraph.getExportsInfo(module);
  267. const exportTarget = accessWithInit(
  268. fullNameResolved,
  269. this._getPrefix(compilation).length,
  270. true
  271. );
  272. for (const exportInfo of exportsInfo.orderedExports) {
  273. if (!exportInfo.provided) continue;
  274. const nameAccess = propertyAccess([exportInfo.name]);
  275. result.add(
  276. `${exportTarget}${nameAccess} = __webpack_exports__${exportAccess}${nameAccess};\n`
  277. );
  278. }
  279. result.add(
  280. `Object.defineProperty(${exportTarget}, "__esModule", { value: true });\n`
  281. );
  282. } else if (options.name ? this.named === "copy" : this.unnamed === "copy") {
  283. result.add(
  284. `var __webpack_export_target__ = ${accessWithInit(
  285. fullNameResolved,
  286. this._getPrefix(compilation).length,
  287. true
  288. )};\n`
  289. );
  290. let exports = "__webpack_exports__";
  291. if (exportAccess) {
  292. result.add(
  293. `var __webpack_exports_export__ = __webpack_exports__${exportAccess};\n`
  294. );
  295. exports = "__webpack_exports_export__";
  296. }
  297. result.add(
  298. `for(var i in ${exports}) __webpack_export_target__[i] = ${exports}[i];\n`
  299. );
  300. result.add(
  301. `if(${exports}.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });\n`
  302. );
  303. } else {
  304. result.add(
  305. `${accessWithInit(
  306. fullNameResolved,
  307. this._getPrefix(compilation).length,
  308. false
  309. )} = __webpack_exports__${exportAccess};\n`
  310. );
  311. }
  312. return result;
  313. }
  314. /**
  315. * @param {Chunk} chunk the chunk
  316. * @param {Set<string>} set runtime requirements
  317. * @param {LibraryContext<T>} libraryContext context
  318. * @returns {void}
  319. */
  320. runtimeRequirements(chunk, set, libraryContext) {
  321. // we don't need to return exports from runtime
  322. }
  323. /**
  324. * @param {Chunk} chunk the chunk
  325. * @param {Hash} hash hash
  326. * @param {ChunkHashContext} chunkHashContext chunk hash context
  327. * @param {LibraryContext<T>} libraryContext context
  328. * @returns {void}
  329. */
  330. chunkHash(chunk, hash, chunkHashContext, { options, compilation }) {
  331. hash.update("AssignLibraryPlugin");
  332. const fullNameResolved = this._getResolvedFullName(
  333. options,
  334. chunk,
  335. compilation
  336. );
  337. if (options.name ? this.named === "copy" : this.unnamed === "copy") {
  338. hash.update("copy");
  339. }
  340. if (this.declare) {
  341. hash.update(this.declare);
  342. }
  343. hash.update(fullNameResolved.join("."));
  344. if (options.export) {
  345. hash.update(`${options.export}`);
  346. }
  347. }
  348. }
  349. module.exports = AssignLibraryPlugin;