AssignLibraryPlugin.js 12 KB

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