index.js 46 KB

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