index.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. "use strict";
  2. /* eslint-disable class-methods-use-this */
  3. const path = require("path");
  4. const {
  5. validate
  6. } = require("schema-utils");
  7. const schema = require("./plugin-options.json");
  8. const {
  9. trueFn,
  10. MODULE_TYPE,
  11. AUTO_PUBLIC_PATH,
  12. ABSOLUTE_PUBLIC_PATH,
  13. SINGLE_DOT_PATH_SEGMENT,
  14. compareModulesByIdentifier,
  15. getUndoPath,
  16. BASE_URI
  17. } = require("./utils");
  18. /** @typedef {import("schema-utils/declarations/validate").Schema} Schema */
  19. /** @typedef {import("webpack").Compiler} Compiler */
  20. /** @typedef {import("webpack").Compilation} Compilation */
  21. /** @typedef {import("webpack").ChunkGraph} ChunkGraph */
  22. /** @typedef {import("webpack").Chunk} Chunk */
  23. /** @typedef {Parameters<import("webpack").Chunk["isInGroup"]>[0]} ChunkGroup */
  24. /** @typedef {import("webpack").Module} Module */
  25. /** @typedef {import("webpack").Dependency} Dependency */
  26. /** @typedef {import("webpack").sources.Source} Source */
  27. /** @typedef {import("webpack").Configuration} Configuration */
  28. /** @typedef {import("webpack").WebpackError} WebpackError */
  29. /** @typedef {import("webpack").AssetInfo} AssetInfo */
  30. /** @typedef {import("./loader.js").Dependency} LoaderDependency */
  31. /**
  32. * @typedef {Object} LoaderOptions
  33. * @property {string | ((resourcePath: string, rootContext: string) => string)} [publicPath]
  34. * @property {boolean} [emit]
  35. * @property {boolean} [esModule]
  36. * @property {string} [layer]
  37. */
  38. /**
  39. * @typedef {Object} PluginOptions
  40. * @property {Required<Configuration>['output']['filename']} [filename]
  41. * @property {Required<Configuration>['output']['chunkFilename']} [chunkFilename]
  42. * @property {boolean} [ignoreOrder]
  43. * @property {string | ((linkTag: HTMLLinkElement) => void)} [insert]
  44. * @property {Record<string, string>} [attributes]
  45. * @property {string | false | 'text/css'} [linkType]
  46. * @property {boolean} [runtime]
  47. * @property {boolean} [experimentalUseImportModule]
  48. */
  49. /**
  50. * @typedef {Object} NormalizedPluginOptions
  51. * @property {Required<Configuration>['output']['filename']} filename
  52. * @property {Required<Configuration>['output']['chunkFilename']} [chunkFilename]
  53. * @property {boolean} ignoreOrder
  54. * @property {string | ((linkTag: HTMLLinkElement) => void)} [insert]
  55. * @property {Record<string, string>} [attributes]
  56. * @property {string | false | 'text/css'} [linkType]
  57. * @property {boolean} runtime
  58. * @property {boolean} [experimentalUseImportModule]
  59. */
  60. /**
  61. * @typedef {Object} RuntimeOptions
  62. * @property {string | ((linkTag: HTMLLinkElement) => void) | undefined} insert
  63. * @property {string | false | 'text/css'} linkType
  64. * @property {Record<string, string> | undefined} attributes
  65. */
  66. /** @typedef {any} TODO */
  67. const pluginName = "mini-css-extract-plugin";
  68. const pluginSymbol = Symbol(pluginName);
  69. const DEFAULT_FILENAME = "[name].css";
  70. /**
  71. * @type {Set<string>}
  72. */
  73. const TYPES = new Set([MODULE_TYPE]);
  74. /**
  75. * @type {ReturnType<Module["codeGeneration"]>}
  76. */
  77. const CODE_GENERATION_RESULT = {
  78. sources: new Map(),
  79. runtimeRequirements: new Set()
  80. };
  81. /** @typedef {Module & { content: Buffer, media?: string, sourceMap?: Buffer, supports?: string, layer?: string, assets?: { [key: string]: TODO }, assetsInfo?: Map<string, AssetInfo> }} CssModule */
  82. /** @typedef {{ context: string | null, identifier: string, identifierIndex: number, content: Buffer, sourceMap?: Buffer, media?: string, supports?: string, layer?: TODO, assetsInfo?: Map<string, AssetInfo>, assets?: { [key: string]: TODO }}} CssModuleDependency */
  83. /** @typedef {{ new(dependency: CssModuleDependency): CssModule }} CssModuleConstructor */
  84. /** @typedef {Dependency & CssModuleDependency} CssDependency */
  85. /** @typedef {Omit<LoaderDependency, "context">} CssDependencyOptions */
  86. /** @typedef {{ new(loaderDependency: CssDependencyOptions, context: string | null, identifierIndex: number): CssDependency }} CssDependencyConstructor */
  87. /**
  88. *
  89. * @type {WeakMap<Compiler["webpack"], CssModuleConstructor>}
  90. */
  91. const cssModuleCache = new WeakMap();
  92. /**
  93. * @type {WeakMap<Compiler["webpack"], CssDependencyConstructor>}
  94. */
  95. const cssDependencyCache = new WeakMap();
  96. /**
  97. * @type {WeakSet<Compiler["webpack"]>}
  98. */
  99. const registered = new WeakSet();
  100. class MiniCssExtractPlugin {
  101. /**
  102. * @param {Compiler["webpack"]} webpack
  103. * @returns {CssModuleConstructor}
  104. */
  105. static getCssModule(webpack) {
  106. /**
  107. * Prevent creation of multiple CssModule classes to allow other integrations to get the current CssModule.
  108. */
  109. if (cssModuleCache.has(webpack)) {
  110. return (/** @type {CssModuleConstructor} */cssModuleCache.get(webpack)
  111. );
  112. }
  113. class CssModule extends webpack.Module {
  114. /**
  115. * @param {CssModuleDependency} dependency
  116. */
  117. constructor({
  118. context,
  119. identifier,
  120. identifierIndex,
  121. content,
  122. layer,
  123. supports,
  124. media,
  125. sourceMap,
  126. assets,
  127. assetsInfo
  128. }) {
  129. super(MODULE_TYPE, /** @type {string | undefined} */context);
  130. this.id = "";
  131. this._context = context;
  132. this._identifier = identifier;
  133. this._identifierIndex = identifierIndex;
  134. this.content = content;
  135. this.layer = layer;
  136. this.supports = supports;
  137. this.media = media;
  138. this.sourceMap = sourceMap;
  139. this.assets = assets;
  140. this.assetsInfo = assetsInfo;
  141. this._needBuild = true;
  142. }
  143. // no source() so webpack 4 doesn't do add stuff to the bundle
  144. size() {
  145. return this.content.length;
  146. }
  147. identifier() {
  148. return `css|${this._identifier}|${this._identifierIndex}|${this.layer || ""}|${this.supports || ""}|${this.media}}}`;
  149. }
  150. /**
  151. * @param {Parameters<Module["readableIdentifier"]>[0]} requestShortener
  152. * @returns {ReturnType<Module["readableIdentifier"]>}
  153. */
  154. readableIdentifier(requestShortener) {
  155. return `css ${requestShortener.shorten(this._identifier)}${this._identifierIndex ? ` (${this._identifierIndex})` : ""}${this.layer ? ` (layer ${this.layer})` : ""}${this.supports ? ` (supports ${this.supports})` : ""}${this.media ? ` (media ${this.media})` : ""}`;
  156. }
  157. // eslint-disable-next-line class-methods-use-this
  158. getSourceTypes() {
  159. return TYPES;
  160. }
  161. // eslint-disable-next-line class-methods-use-this
  162. codeGeneration() {
  163. return CODE_GENERATION_RESULT;
  164. }
  165. nameForCondition() {
  166. const resource = /** @type {string} */
  167. this._identifier.split("!").pop();
  168. const idx = resource.indexOf("?");
  169. if (idx >= 0) {
  170. return resource.substring(0, idx);
  171. }
  172. return resource;
  173. }
  174. /**
  175. * @param {Module} module
  176. */
  177. updateCacheModule(module) {
  178. if (!this.content.equals( /** @type {CssModule} */module.content) || this.layer !== /** @type {CssModule} */module.layer || this.supports !== /** @type {CssModule} */module.supports || this.media !== /** @type {CssModule} */module.media || (this.sourceMap ? !this.sourceMap.equals( /** @type {Uint8Array} **/
  179. /** @type {CssModule} */module.sourceMap) : false) || this.assets !== /** @type {CssModule} */module.assets || this.assetsInfo !== /** @type {CssModule} */module.assetsInfo) {
  180. this._needBuild = true;
  181. this.content = /** @type {CssModule} */module.content;
  182. this.layer = /** @type {CssModule} */module.layer;
  183. this.supports = /** @type {CssModule} */module.supports;
  184. this.media = /** @type {CssModule} */module.media;
  185. this.sourceMap = /** @type {CssModule} */module.sourceMap;
  186. this.assets = /** @type {CssModule} */module.assets;
  187. this.assetsInfo = /** @type {CssModule} */module.assetsInfo;
  188. }
  189. }
  190. // eslint-disable-next-line class-methods-use-this
  191. needRebuild() {
  192. return this._needBuild;
  193. }
  194. // eslint-disable-next-line class-methods-use-this
  195. /**
  196. * @param {Parameters<Module["needBuild"]>[0]} context context info
  197. * @param {Parameters<Module["needBuild"]>[1]} callback callback function, returns true, if the module needs a rebuild
  198. */
  199. needBuild(context, callback) {
  200. // eslint-disable-next-line no-undefined
  201. callback(undefined, this._needBuild);
  202. }
  203. /**
  204. * @param {Parameters<Module["build"]>[0]} options
  205. * @param {Parameters<Module["build"]>[1]} compilation
  206. * @param {Parameters<Module["build"]>[2]} resolver
  207. * @param {Parameters<Module["build"]>[3]} fileSystem
  208. * @param {Parameters<Module["build"]>[4]} callback
  209. */
  210. build(options, compilation, resolver, fileSystem, callback) {
  211. this.buildInfo = {
  212. assets: this.assets,
  213. assetsInfo: this.assetsInfo,
  214. cacheable: true,
  215. hash: this._computeHash( /** @type {string} */compilation.outputOptions.hashFunction)
  216. };
  217. this.buildMeta = {};
  218. this._needBuild = false;
  219. callback();
  220. }
  221. /**
  222. * @private
  223. * @param {string} hashFunction
  224. * @returns {string | Buffer}
  225. */
  226. _computeHash(hashFunction) {
  227. const hash = webpack.util.createHash(hashFunction);
  228. hash.update(this.content);
  229. if (this.layer) {
  230. hash.update(this.layer);
  231. }
  232. hash.update(this.supports || "");
  233. hash.update(this.media || "");
  234. hash.update(this.sourceMap || "");
  235. return hash.digest("hex");
  236. }
  237. /**
  238. * @param {Parameters<Module["updateHash"]>[0]} hash
  239. * @param {Parameters<Module["updateHash"]>[1]} context
  240. */
  241. updateHash(hash, context) {
  242. super.updateHash(hash, context);
  243. hash.update(this.buildInfo.hash);
  244. }
  245. /**
  246. * @param {Parameters<Module["serialize"]>[0]} context
  247. */
  248. serialize(context) {
  249. const {
  250. write
  251. } = context;
  252. write(this._context);
  253. write(this._identifier);
  254. write(this._identifierIndex);
  255. write(this.content);
  256. write(this.layer);
  257. write(this.supports);
  258. write(this.media);
  259. write(this.sourceMap);
  260. write(this.assets);
  261. write(this.assetsInfo);
  262. write(this._needBuild);
  263. super.serialize(context);
  264. }
  265. /**
  266. * @param {Parameters<Module["deserialize"]>[0]} context
  267. */
  268. deserialize(context) {
  269. this._needBuild = context.read();
  270. super.deserialize(context);
  271. }
  272. }
  273. cssModuleCache.set(webpack, CssModule);
  274. webpack.util.serialization.register(CssModule, path.resolve(__dirname, "CssModule"),
  275. // @ts-ignore
  276. null, {
  277. serialize(instance, context) {
  278. instance.serialize(context);
  279. },
  280. deserialize(context) {
  281. const {
  282. read
  283. } = context;
  284. const contextModule = read();
  285. const identifier = read();
  286. const identifierIndex = read();
  287. const content = read();
  288. const layer = read();
  289. const supports = read();
  290. const media = read();
  291. const sourceMap = read();
  292. const assets = read();
  293. const assetsInfo = read();
  294. const dep = new CssModule({
  295. context: contextModule,
  296. identifier,
  297. identifierIndex,
  298. content,
  299. layer,
  300. supports,
  301. media,
  302. sourceMap,
  303. assets,
  304. assetsInfo
  305. });
  306. dep.deserialize(context);
  307. return dep;
  308. }
  309. });
  310. return CssModule;
  311. }
  312. /**
  313. * @param {Compiler["webpack"]} webpack
  314. * @returns {CssDependencyConstructor}
  315. */
  316. static getCssDependency(webpack) {
  317. /**
  318. * Prevent creation of multiple CssDependency classes to allow other integrations to get the current CssDependency.
  319. */
  320. if (cssDependencyCache.has(webpack)) {
  321. return (/** @type {CssDependencyConstructor} */
  322. cssDependencyCache.get(webpack)
  323. );
  324. }
  325. class CssDependency extends webpack.Dependency {
  326. /**
  327. * @param {CssDependencyOptions} loaderDependency
  328. * @param {string | null} context
  329. * @param {number} identifierIndex
  330. */
  331. constructor({
  332. identifier,
  333. content,
  334. layer,
  335. supports,
  336. media,
  337. sourceMap
  338. }, context, identifierIndex) {
  339. super();
  340. this.identifier = identifier;
  341. this.identifierIndex = identifierIndex;
  342. this.content = content;
  343. this.layer = layer;
  344. this.supports = supports;
  345. this.media = media;
  346. this.sourceMap = sourceMap;
  347. this.context = context;
  348. /** @type {{ [key: string]: Source } | undefined}} */
  349. // eslint-disable-next-line no-undefined
  350. this.assets = undefined;
  351. /** @type {Map<string, AssetInfo> | undefined} */
  352. // eslint-disable-next-line no-undefined
  353. this.assetsInfo = undefined;
  354. }
  355. /**
  356. * @returns {ReturnType<Dependency["getResourceIdentifier"]>}
  357. */
  358. getResourceIdentifier() {
  359. return `css-module-${this.identifier}-${this.identifierIndex}`;
  360. }
  361. /**
  362. * @returns {ReturnType<Dependency["getModuleEvaluationSideEffectsState"]>}
  363. */
  364. // eslint-disable-next-line class-methods-use-this
  365. getModuleEvaluationSideEffectsState() {
  366. return webpack.ModuleGraphConnection.TRANSITIVE_ONLY;
  367. }
  368. /**
  369. * @param {Parameters<Dependency["serialize"]>[0]} context
  370. */
  371. serialize(context) {
  372. const {
  373. write
  374. } = context;
  375. write(this.identifier);
  376. write(this.content);
  377. write(this.layer);
  378. write(this.supports);
  379. write(this.media);
  380. write(this.sourceMap);
  381. write(this.context);
  382. write(this.identifierIndex);
  383. write(this.assets);
  384. write(this.assetsInfo);
  385. super.serialize(context);
  386. }
  387. /**
  388. * @param {Parameters<Dependency["deserialize"]>[0]} context
  389. */
  390. deserialize(context) {
  391. super.deserialize(context);
  392. }
  393. }
  394. cssDependencyCache.set(webpack, CssDependency);
  395. webpack.util.serialization.register(CssDependency, path.resolve(__dirname, "CssDependency"),
  396. // @ts-ignore
  397. null, {
  398. serialize(instance, context) {
  399. instance.serialize(context);
  400. },
  401. deserialize(context) {
  402. const {
  403. read
  404. } = context;
  405. const dep = new CssDependency({
  406. identifier: read(),
  407. content: read(),
  408. layer: read(),
  409. supports: read(),
  410. media: read(),
  411. sourceMap: read()
  412. }, read(), read());
  413. const assets = read();
  414. const assetsInfo = read();
  415. dep.assets = assets;
  416. dep.assetsInfo = assetsInfo;
  417. dep.deserialize(context);
  418. return dep;
  419. }
  420. });
  421. return CssDependency;
  422. }
  423. /**
  424. * @param {PluginOptions} [options]
  425. */
  426. constructor(options = {}) {
  427. validate( /** @type {Schema} */schema, options, {
  428. baseDataPath: "options"
  429. });
  430. /**
  431. * @private
  432. * @type {WeakMap<Chunk, Set<CssModule>>}
  433. * @private
  434. */
  435. this._sortedModulesCache = new WeakMap();
  436. /**
  437. * @private
  438. * @type {NormalizedPluginOptions}
  439. */
  440. this.options = Object.assign({
  441. filename: DEFAULT_FILENAME,
  442. ignoreOrder: false,
  443. // TODO remove in the next major release
  444. // eslint-disable-next-line no-undefined
  445. experimentalUseImportModule: undefined,
  446. runtime: true
  447. }, options);
  448. /**
  449. * @private
  450. * @type {RuntimeOptions}
  451. */
  452. this.runtimeOptions = {
  453. insert: options.insert,
  454. linkType:
  455. // Todo in next major release set default to "false"
  456. typeof options.linkType === "boolean" && /** @type {boolean} */options.linkType === true || typeof options.linkType === "undefined" ? "text/css" : options.linkType,
  457. attributes: options.attributes
  458. };
  459. if (!this.options.chunkFilename) {
  460. const {
  461. filename
  462. } = this.options;
  463. if (typeof filename !== "function") {
  464. const hasName = /** @type {string} */filename.includes("[name]");
  465. const hasId = /** @type {string} */filename.includes("[id]");
  466. const hasChunkHash = /** @type {string} */
  467. filename.includes("[chunkhash]");
  468. const hasContentHash = /** @type {string} */
  469. filename.includes("[contenthash]");
  470. // Anything changing depending on chunk is fine
  471. if (hasChunkHash || hasContentHash || hasName || hasId) {
  472. this.options.chunkFilename = filename;
  473. } else {
  474. // Otherwise prefix "[id]." in front of the basename to make it changing
  475. this.options.chunkFilename = /** @type {string} */
  476. filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2");
  477. }
  478. } else {
  479. this.options.chunkFilename = "[id].css";
  480. }
  481. }
  482. }
  483. /**
  484. * @param {Compiler} compiler
  485. */
  486. apply(compiler) {
  487. const {
  488. webpack
  489. } = compiler;
  490. if (this.options.experimentalUseImportModule) {
  491. if (typeof /** @type {Compiler["options"]["experiments"] & { executeModule?: boolean }} */
  492. compiler.options.experiments.executeModule === "undefined") {
  493. /** @type {Compiler["options"]["experiments"] & { executeModule?: boolean }} */
  494. // eslint-disable-next-line no-param-reassign
  495. compiler.options.experiments.executeModule = true;
  496. }
  497. }
  498. // TODO bug in webpack, remove it after it will be fixed
  499. // webpack tries to `require` loader firstly when serializer doesn't found
  500. if (!registered.has(webpack)) {
  501. registered.add(webpack);
  502. webpack.util.serialization.registerLoader(/^mini-css-extract-plugin\//, trueFn);
  503. }
  504. const {
  505. splitChunks
  506. } = compiler.options.optimization;
  507. if (splitChunks) {
  508. if ( /** @type {string[]} */splitChunks.defaultSizeTypes.includes("...")) {
  509. /** @type {string[]} */
  510. splitChunks.defaultSizeTypes.push(MODULE_TYPE);
  511. }
  512. }
  513. const CssModule = MiniCssExtractPlugin.getCssModule(webpack);
  514. const CssDependency = MiniCssExtractPlugin.getCssDependency(webpack);
  515. const {
  516. NormalModule
  517. } = compiler.webpack;
  518. compiler.hooks.compilation.tap(pluginName, compilation => {
  519. const {
  520. loader: normalModuleHook
  521. } = NormalModule.getCompilationHooks(compilation);
  522. normalModuleHook.tap(pluginName,
  523. /**
  524. * @param {object} loaderContext
  525. */
  526. loaderContext => {
  527. /** @type {object & { [pluginSymbol]: { experimentalUseImportModule: boolean | undefined } }} */
  528. // eslint-disable-next-line no-param-reassign
  529. loaderContext[pluginSymbol] = {
  530. experimentalUseImportModule: this.options.experimentalUseImportModule
  531. };
  532. });
  533. });
  534. compiler.hooks.thisCompilation.tap(pluginName, compilation => {
  535. class CssModuleFactory {
  536. /**
  537. * @param {{ dependencies: Dependency[] }} dependencies
  538. * @param {(arg0?: Error, arg1?: TODO) => void} callback
  539. */
  540. // eslint-disable-next-line class-methods-use-this
  541. create({
  542. dependencies: [dependency]
  543. }, callback) {
  544. callback(
  545. // eslint-disable-next-line no-undefined
  546. undefined, new CssModule( /** @type {CssDependency} */dependency));
  547. }
  548. }
  549. compilation.dependencyFactories.set(CssDependency, new CssModuleFactory());
  550. class CssDependencyTemplate {
  551. // eslint-disable-next-line class-methods-use-this
  552. apply() {}
  553. }
  554. compilation.dependencyTemplates.set(CssDependency, new CssDependencyTemplate());
  555. compilation.hooks.renderManifest.tap(pluginName,
  556. /**
  557. * @param {ReturnType<Compilation["getRenderManifest"]>} result
  558. * @param {Parameters<Compilation["getRenderManifest"]>[0]} chunk
  559. * @returns {TODO}
  560. */
  561. (result, {
  562. chunk
  563. }) => {
  564. const {
  565. chunkGraph
  566. } = compilation;
  567. const {
  568. HotUpdateChunk
  569. } = webpack;
  570. // We don't need hot update chunks for css
  571. // We will use the real asset instead to update
  572. if (chunk instanceof HotUpdateChunk) {
  573. return;
  574. }
  575. /** @type {CssModule[]} */
  576. const renderedModules = Array.from( /** @type {CssModule[]} */
  577. this.getChunkModules(chunk, chunkGraph)).filter(module => module.type === MODULE_TYPE);
  578. const filenameTemplate = /** @type {string} */
  579. chunk.canBeInitial() ? this.options.filename : this.options.chunkFilename;
  580. if (renderedModules.length > 0) {
  581. result.push({
  582. render: () => this.renderContentAsset(compiler, compilation, chunk, renderedModules, compilation.runtimeTemplate.requestShortener, filenameTemplate, {
  583. contentHashType: MODULE_TYPE,
  584. chunk
  585. }),
  586. filenameTemplate,
  587. pathOptions: {
  588. chunk,
  589. contentHashType: MODULE_TYPE
  590. },
  591. identifier: `${pluginName}.${chunk.id}`,
  592. hash: chunk.contentHash[MODULE_TYPE]
  593. });
  594. }
  595. });
  596. compilation.hooks.contentHash.tap(pluginName, chunk => {
  597. const {
  598. outputOptions,
  599. chunkGraph
  600. } = compilation;
  601. const modules = this.sortModules(compilation, chunk, /** @type {CssModule[]} */
  602. chunkGraph.getChunkModulesIterableBySourceType(chunk, MODULE_TYPE), compilation.runtimeTemplate.requestShortener);
  603. if (modules) {
  604. const {
  605. hashFunction,
  606. hashDigest,
  607. hashDigestLength
  608. } = outputOptions;
  609. const {
  610. createHash
  611. } = compiler.webpack.util;
  612. const hash = createHash( /** @type {string} */hashFunction);
  613. for (const m of modules) {
  614. hash.update(chunkGraph.getModuleHash(m, chunk.runtime));
  615. }
  616. // eslint-disable-next-line no-param-reassign
  617. chunk.contentHash[MODULE_TYPE] = /** @type {string} */
  618. hash.digest(hashDigest).substring(0, hashDigestLength);
  619. }
  620. });
  621. // All the code below is dedicated to the runtime and can be skipped when the `runtime` option is `false`
  622. if (!this.options.runtime) {
  623. return;
  624. }
  625. const {
  626. Template,
  627. RuntimeGlobals,
  628. RuntimeModule,
  629. runtime
  630. } = webpack;
  631. /**
  632. * @param {Chunk} mainChunk
  633. * @param {Compilation} compilation
  634. * @returns {Record<string, number>}
  635. */
  636. // eslint-disable-next-line no-shadow
  637. const getCssChunkObject = (mainChunk, compilation) => {
  638. /** @type {Record<string, number>} */
  639. const obj = {};
  640. const {
  641. chunkGraph
  642. } = compilation;
  643. for (const chunk of mainChunk.getAllAsyncChunks()) {
  644. const modules = chunkGraph.getOrderedChunkModulesIterable(chunk, compareModulesByIdentifier);
  645. for (const module of modules) {
  646. if (module.type === MODULE_TYPE) {
  647. obj[/** @type {string} */chunk.id] = 1;
  648. break;
  649. }
  650. }
  651. }
  652. return obj;
  653. };
  654. class CssLoadingRuntimeModule extends RuntimeModule {
  655. /**
  656. * @param {Set<string>} runtimeRequirements
  657. * @param {RuntimeOptions} runtimeOptions
  658. */
  659. constructor(runtimeRequirements, runtimeOptions) {
  660. super("css loading", 10);
  661. this.runtimeRequirements = runtimeRequirements;
  662. this.runtimeOptions = runtimeOptions;
  663. }
  664. generate() {
  665. const {
  666. chunk,
  667. runtimeRequirements
  668. } = this;
  669. const {
  670. runtimeTemplate,
  671. outputOptions: {
  672. crossOriginLoading
  673. }
  674. } = this.compilation;
  675. const chunkMap = getCssChunkObject(chunk, this.compilation);
  676. const withLoading = runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) && Object.keys(chunkMap).length > 0;
  677. const withHmr = runtimeRequirements.has(RuntimeGlobals.hmrDownloadUpdateHandlers);
  678. if (!withLoading && !withHmr) {
  679. return "";
  680. }
  681. return Template.asString(['if (typeof document === "undefined") return;', `var createStylesheet = ${runtimeTemplate.basicFunction("chunkId, fullhref, oldTag, resolve, reject", ['var linkTag = document.createElement("link");', this.runtimeOptions.attributes ? Template.asString(Object.entries(this.runtimeOptions.attributes).map(entry => {
  682. const [key, value] = entry;
  683. return `linkTag.setAttribute(${JSON.stringify(key)}, ${JSON.stringify(value)});`;
  684. })) : "", 'linkTag.rel = "stylesheet";', this.runtimeOptions.linkType ? `linkTag.type = ${JSON.stringify(this.runtimeOptions.linkType)};` : "", `var onLinkComplete = ${runtimeTemplate.basicFunction("event", ["// avoid mem leaks.", "linkTag.onerror = linkTag.onload = null;", "if (event.type === 'load') {", Template.indent(["resolve();"]), "} else {", Template.indent(["var errorType = event && (event.type === 'load' ? 'missing' : event.type);", "var realHref = event && event.target && event.target.href || fullhref;", 'var err = new Error("Loading CSS chunk " + chunkId + " failed.\\n(" + realHref + ")");', 'err.code = "CSS_CHUNK_LOAD_FAILED";', "err.type = errorType;", "err.request = realHref;", "if (linkTag.parentNode) linkTag.parentNode.removeChild(linkTag)", "reject(err);"]), "}"])}`, "linkTag.onerror = linkTag.onload = onLinkComplete;", "linkTag.href = fullhref;", crossOriginLoading ? Template.asString([`if (linkTag.href.indexOf(window.location.origin + '/') !== 0) {`, Template.indent(`linkTag.crossOrigin = ${JSON.stringify(crossOriginLoading)};`), "}"]) : "", typeof this.runtimeOptions.insert !== "undefined" ? typeof this.runtimeOptions.insert === "function" ? `(${this.runtimeOptions.insert.toString()})(linkTag)` : Template.asString([`var target = document.querySelector("${this.runtimeOptions.insert}");`, `target.parentNode.insertBefore(linkTag, target.nextSibling);`]) : Template.asString(["if (oldTag) {", Template.indent(["oldTag.parentNode.insertBefore(linkTag, oldTag.nextSibling);"]), "} else {", Template.indent(["document.head.appendChild(linkTag);"]), "}"]), "return linkTag;"])};`, `var findStylesheet = ${runtimeTemplate.basicFunction("href, fullhref", ['var existingLinkTags = document.getElementsByTagName("link");', "for(var i = 0; i < existingLinkTags.length; i++) {", Template.indent(["var tag = existingLinkTags[i];", 'var dataHref = tag.getAttribute("data-href") || tag.getAttribute("href");', 'if(tag.rel === "stylesheet" && (dataHref === href || dataHref === fullhref)) return tag;']), "}", 'var existingStyleTags = document.getElementsByTagName("style");', "for(var i = 0; i < existingStyleTags.length; i++) {", Template.indent(["var tag = existingStyleTags[i];", 'var dataHref = tag.getAttribute("data-href");', "if(dataHref === href || dataHref === fullhref) return tag;"]), "}"])};`, `var loadStylesheet = ${runtimeTemplate.basicFunction("chunkId", `return new Promise(${runtimeTemplate.basicFunction("resolve, reject", [`var href = ${RuntimeGlobals.require}.miniCssF(chunkId);`, `var fullhref = ${RuntimeGlobals.publicPath} + href;`, "if(findStylesheet(href, fullhref)) return resolve();", "createStylesheet(chunkId, fullhref, null, resolve, reject);"])});`)}`, withLoading ? Template.asString(["// object to store loaded CSS chunks", "var installedCssChunks = {", Template.indent( /** @type {string[]} */
  685. chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(",\n")), "};", "", `${RuntimeGlobals.ensureChunkHandlers}.miniCss = ${runtimeTemplate.basicFunction("chunkId, promises", [`var cssChunks = ${JSON.stringify(chunkMap)};`, "if(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);", "else if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {", Template.indent([`promises.push(installedCssChunks[chunkId] = loadStylesheet(chunkId).then(${runtimeTemplate.basicFunction("", "installedCssChunks[chunkId] = 0;")}, ${runtimeTemplate.basicFunction("e", ["delete installedCssChunks[chunkId];", "throw e;"])}));`]), "}"])};`]) : "// no chunk loading", "", withHmr ? Template.asString(["var oldTags = [];", "var newTags = [];", `var applyHandler = ${runtimeTemplate.basicFunction("options", [`return { dispose: ${runtimeTemplate.basicFunction("", ["for(var i = 0; i < oldTags.length; i++) {", Template.indent(["var oldTag = oldTags[i];", "if(oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);"]), "}", "oldTags.length = 0;"])}, apply: ${runtimeTemplate.basicFunction("", ['for(var i = 0; i < newTags.length; i++) newTags[i].rel = "stylesheet";', "newTags.length = 0;"])} };`])}`, `${RuntimeGlobals.hmrDownloadUpdateHandlers}.miniCss = ${runtimeTemplate.basicFunction("chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList", ["applyHandlers.push(applyHandler);", `chunkIds.forEach(${runtimeTemplate.basicFunction("chunkId", [`var href = ${RuntimeGlobals.require}.miniCssF(chunkId);`, `var fullhref = ${RuntimeGlobals.publicPath} + href;`, "var oldTag = findStylesheet(href, fullhref);", "if(!oldTag) return;", `promises.push(new Promise(${runtimeTemplate.basicFunction("resolve, reject", [`var tag = createStylesheet(chunkId, fullhref, oldTag, ${runtimeTemplate.basicFunction("", ['tag.as = "style";', 'tag.rel = "preload";', "resolve();"])}, reject);`, "oldTags.push(oldTag);", "newTags.push(tag);"])}));`])});`])}`]) : "// no hmr"]);
  686. }
  687. }
  688. const enabledChunks = new WeakSet();
  689. /**
  690. * @param {Chunk} chunk
  691. * @param {Set<string>} set
  692. */
  693. const handler = (chunk, set) => {
  694. if (enabledChunks.has(chunk)) {
  695. return;
  696. }
  697. enabledChunks.add(chunk);
  698. if (typeof this.options.chunkFilename === "string" && /\[(full)?hash(:\d+)?\]/.test(this.options.chunkFilename)) {
  699. set.add(RuntimeGlobals.getFullHash);
  700. }
  701. set.add(RuntimeGlobals.publicPath);
  702. compilation.addRuntimeModule(chunk, new runtime.GetChunkFilenameRuntimeModule(MODULE_TYPE, "mini-css", `${RuntimeGlobals.require}.miniCssF`,
  703. /**
  704. * @param {Chunk} referencedChunk
  705. * @returns {TODO}
  706. */
  707. referencedChunk => {
  708. if (!referencedChunk.contentHash[MODULE_TYPE]) {
  709. return false;
  710. }
  711. return referencedChunk.canBeInitial() ? this.options.filename : this.options.chunkFilename;
  712. }, false));
  713. compilation.addRuntimeModule(chunk, new CssLoadingRuntimeModule(set, this.runtimeOptions));
  714. };
  715. compilation.hooks.runtimeRequirementInTree.for(RuntimeGlobals.ensureChunkHandlers).tap(pluginName, handler);
  716. compilation.hooks.runtimeRequirementInTree.for(RuntimeGlobals.hmrDownloadUpdateHandlers).tap(pluginName, handler);
  717. });
  718. }
  719. /**
  720. * @private
  721. * @param {Chunk} chunk
  722. * @param {ChunkGraph} chunkGraph
  723. * @returns {Iterable<Module>}
  724. */
  725. getChunkModules(chunk, chunkGraph) {
  726. return typeof chunkGraph !== "undefined" ? chunkGraph.getOrderedChunkModulesIterable(chunk, compareModulesByIdentifier) : chunk.modulesIterable;
  727. }
  728. /**
  729. * @private
  730. * @param {Compilation} compilation
  731. * @param {Chunk} chunk
  732. * @param {CssModule[]} modules
  733. * @param {Compilation["requestShortener"]} requestShortener
  734. * @returns {Set<CssModule>}
  735. */
  736. sortModules(compilation, chunk, modules, requestShortener) {
  737. let usedModules = this._sortedModulesCache.get(chunk);
  738. if (usedModules || !modules) {
  739. return (/** @type {Set<CssModule>} */usedModules
  740. );
  741. }
  742. /** @type {CssModule[]} */
  743. const modulesList = [...modules];
  744. // Store dependencies for modules
  745. /** @type {Map<CssModule, Set<CssModule>>} */
  746. const moduleDependencies = new Map(modulesList.map(m => [m, /** @type {Set<CssModule>} */
  747. new Set()]));
  748. /** @type {Map<CssModule, Map<CssModule, Set<ChunkGroup>>>} */
  749. const moduleDependenciesReasons = new Map(modulesList.map(m => [m, new Map()]));
  750. // Get ordered list of modules per chunk group
  751. // This loop also gathers dependencies from the ordered lists
  752. // Lists are in reverse order to allow to use Array.pop()
  753. /** @type {CssModule[][]} */
  754. const modulesByChunkGroup = Array.from(chunk.groupsIterable, chunkGroup => {
  755. const sortedModules = modulesList.map(module => {
  756. return {
  757. module,
  758. index: chunkGroup.getModulePostOrderIndex(module)
  759. };
  760. })
  761. // eslint-disable-next-line no-undefined
  762. .filter(item => item.index !== undefined).sort((a, b) => b.index - a.index).map(item => item.module);
  763. for (let i = 0; i < sortedModules.length; i++) {
  764. const set = moduleDependencies.get(sortedModules[i]);
  765. const reasons = /** @type {Map<CssModule, Set<ChunkGroup>>} */
  766. moduleDependenciesReasons.get(sortedModules[i]);
  767. for (let j = i + 1; j < sortedModules.length; j++) {
  768. const module = sortedModules[j];
  769. /** @type {Set<CssModule>} */
  770. set.add(module);
  771. const reason = reasons.get(module) || /** @type {Set<ChunkGroup>} */new Set();
  772. reason.add(chunkGroup);
  773. reasons.set(module, reason);
  774. }
  775. }
  776. return sortedModules;
  777. });
  778. // set with already included modules in correct order
  779. usedModules = new Set();
  780. /**
  781. * @param {CssModule} m
  782. * @returns {boolean}
  783. */
  784. const unusedModulesFilter = m => ! /** @type {Set<CssModule>} */usedModules.has(m);
  785. while (usedModules.size < modulesList.length) {
  786. let success = false;
  787. let bestMatch;
  788. let bestMatchDeps;
  789. // get first module where dependencies are fulfilled
  790. for (const list of modulesByChunkGroup) {
  791. // skip and remove already added modules
  792. while (list.length > 0 && usedModules.has(list[list.length - 1])) {
  793. list.pop();
  794. }
  795. // skip empty lists
  796. if (list.length !== 0) {
  797. const module = list[list.length - 1];
  798. const deps = moduleDependencies.get(module);
  799. // determine dependencies that are not yet included
  800. const failedDeps = Array.from( /** @type {Set<CssModule>} */
  801. deps).filter(unusedModulesFilter);
  802. // store best match for fallback behavior
  803. if (!bestMatchDeps || bestMatchDeps.length > failedDeps.length) {
  804. bestMatch = list;
  805. bestMatchDeps = failedDeps;
  806. }
  807. if (failedDeps.length === 0) {
  808. // use this module and remove it from list
  809. usedModules.add( /** @type {CssModule} */list.pop());
  810. success = true;
  811. break;
  812. }
  813. }
  814. }
  815. if (!success) {
  816. // no module found => there is a conflict
  817. // use list with fewest failed deps
  818. // and emit a warning
  819. const fallbackModule = /** @type {CssModule[]} */bestMatch.pop();
  820. if (!this.options.ignoreOrder) {
  821. const reasons = moduleDependenciesReasons.get( /** @type {CssModule} */fallbackModule);
  822. compilation.warnings.push( /** @type {WebpackError} */
  823. new Error([`chunk ${chunk.name || chunk.id} [${pluginName}]`, "Conflicting order. Following module has been added:", ` * ${
  824. /** @type {CssModule} */fallbackModule.readableIdentifier(requestShortener)}`, "despite it was not able to fulfill desired ordering with these modules:", ... /** @type {CssModule[]} */bestMatchDeps.map(m => {
  825. const goodReasonsMap = moduleDependenciesReasons.get(m);
  826. const goodReasons = goodReasonsMap && goodReasonsMap.get( /** @type {CssModule} */fallbackModule);
  827. const failedChunkGroups = Array.from( /** @type {Set<ChunkGroup>} */
  828. /** @type {Map<CssModule, Set<ChunkGroup>>} */
  829. reasons.get(m), cg => cg.name).join(", ");
  830. const goodChunkGroups = goodReasons && Array.from(goodReasons, cg => cg.name).join(", ");
  831. return [` * ${m.readableIdentifier(requestShortener)}`, ` - couldn't fulfill desired order of chunk group(s) ${failedChunkGroups}`, goodChunkGroups && ` - while fulfilling desired order of chunk group(s) ${goodChunkGroups}`].filter(Boolean).join("\n");
  832. })].join("\n")));
  833. }
  834. usedModules.add( /** @type {CssModule} */fallbackModule);
  835. }
  836. }
  837. this._sortedModulesCache.set(chunk, usedModules);
  838. return usedModules;
  839. }
  840. /**
  841. * @private
  842. * @param {Compiler} compiler
  843. * @param {Compilation} compilation
  844. * @param {Chunk} chunk
  845. * @param {CssModule[]} modules
  846. * @param {Compiler["requestShortener"]} requestShortener
  847. * @param {string} filenameTemplate
  848. * @param {Parameters<Exclude<Required<Configuration>['output']['filename'], string | undefined>>[0]} pathData
  849. * @returns {Source}
  850. */
  851. renderContentAsset(compiler, compilation, chunk, modules, requestShortener, filenameTemplate, pathData) {
  852. const usedModules = this.sortModules(compilation, chunk, modules, requestShortener);
  853. const {
  854. ConcatSource,
  855. SourceMapSource,
  856. RawSource
  857. } = compiler.webpack.sources;
  858. const source = new ConcatSource();
  859. const externalsSource = new ConcatSource();
  860. for (const module of usedModules) {
  861. let content = module.content.toString();
  862. const readableIdentifier = module.readableIdentifier(requestShortener);
  863. const startsWithAtRuleImport = /^@import url/.test(content);
  864. let header;
  865. if (compilation.outputOptions.pathinfo) {
  866. // From https://github.com/webpack/webpack/blob/29eff8a74ecc2f87517b627dee451c2af9ed3f3f/lib/ModuleInfoHeaderPlugin.js#L191-L194
  867. const reqStr = readableIdentifier.replace(/\*\//g, "*_/");
  868. const reqStrStar = "*".repeat(reqStr.length);
  869. const headerStr = `/*!****${reqStrStar}****!*\\\n !*** ${reqStr} ***!\n \\****${reqStrStar}****/\n`;
  870. header = new RawSource(headerStr);
  871. }
  872. if (startsWithAtRuleImport) {
  873. if (typeof header !== "undefined") {
  874. externalsSource.add(header);
  875. }
  876. // HACK for IE
  877. // http://stackoverflow.com/a/14676665/1458162
  878. if (module.media) {
  879. // insert media into the @import
  880. // this is rar
  881. // TODO improve this and parse the CSS to support multiple medias
  882. content = content.replace(/;|\s*$/, module.media);
  883. }
  884. externalsSource.add(content);
  885. externalsSource.add("\n");
  886. } else {
  887. if (typeof header !== "undefined") {
  888. source.add(header);
  889. }
  890. if (module.supports) {
  891. source.add(`@supports (${module.supports}) {\n`);
  892. }
  893. if (module.media) {
  894. source.add(`@media ${module.media} {\n`);
  895. }
  896. const needLayer = typeof module.layer !== "undefined";
  897. if (needLayer) {
  898. source.add(`@layer${module.layer.length > 0 ? ` ${module.layer}` : ""} {\n`);
  899. }
  900. const {
  901. path: filename
  902. } = compilation.getPathWithInfo(filenameTemplate, pathData);
  903. const undoPath = getUndoPath(filename, compiler.outputPath, false);
  904. // replacements
  905. content = content.replace(new RegExp(ABSOLUTE_PUBLIC_PATH, "g"), "");
  906. content = content.replace(new RegExp(SINGLE_DOT_PATH_SEGMENT, "g"), ".");
  907. content = content.replace(new RegExp(AUTO_PUBLIC_PATH, "g"), undoPath);
  908. const entryOptions = chunk.getEntryOptions();
  909. const baseUriReplacement = entryOptions && entryOptions.baseUri || undoPath;
  910. content = content.replace(new RegExp(BASE_URI, "g"), baseUriReplacement);
  911. if (module.sourceMap) {
  912. source.add(new SourceMapSource(content, readableIdentifier, module.sourceMap.toString()));
  913. } else {
  914. source.add(new RawSource(content));
  915. }
  916. source.add("\n");
  917. if (needLayer) {
  918. source.add("}\n");
  919. }
  920. if (module.media) {
  921. source.add("}\n");
  922. }
  923. if (module.supports) {
  924. source.add("}\n");
  925. }
  926. }
  927. }
  928. return new ConcatSource(externalsSource, source);
  929. }
  930. }
  931. MiniCssExtractPlugin.pluginName = pluginName;
  932. MiniCssExtractPlugin.pluginSymbol = pluginSymbol;
  933. MiniCssExtractPlugin.loader = require.resolve("./loader");
  934. module.exports = MiniCssExtractPlugin;