1 | "use strict";
|
2 |
|
3 |
|
4 | const path = require("path");
|
5 |
|
6 | const {
|
7 | validate
|
8 | } = require("schema-utils");
|
9 |
|
10 | const schema = require("./plugin-options.json");
|
11 |
|
12 | const {
|
13 | trueFn,
|
14 | MODULE_TYPE,
|
15 | AUTO_PUBLIC_PATH,
|
16 | ABSOLUTE_PUBLIC_PATH,
|
17 | SINGLE_DOT_PATH_SEGMENT,
|
18 | compareModulesByIdentifier,
|
19 | getUndoPath
|
20 | } = require("./utils");
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 |
|
88 |
|
89 | const pluginName = "mini-css-extract-plugin";
|
90 | const pluginSymbol = Symbol(pluginName);
|
91 | const DEFAULT_FILENAME = "[name].css";
|
92 |
|
93 |
|
94 |
|
95 |
|
96 | const TYPES = new Set([MODULE_TYPE]);
|
97 |
|
98 |
|
99 |
|
100 |
|
101 | const CODE_GENERATION_RESULT = {
|
102 | sources: new Map(),
|
103 | runtimeRequirements: new Set()
|
104 | };
|
105 |
|
106 |
|
107 |
|
108 |
|
109 |
|
110 |
|
111 |
|
112 |
|
113 |
|
114 |
|
115 |
|
116 |
|
117 |
|
118 |
|
119 |
|
120 |
|
121 |
|
122 | const cssModuleCache = new WeakMap();
|
123 |
|
124 |
|
125 |
|
126 |
|
127 | const cssDependencyCache = new WeakMap();
|
128 |
|
129 |
|
130 |
|
131 |
|
132 | const registered = new WeakSet();
|
133 |
|
134 | class MiniCssExtractPlugin {
|
135 | |
136 |
|
137 |
|
138 |
|
139 | static getCssModule(webpack) {
|
140 | |
141 |
|
142 |
|
143 | if (cssModuleCache.has(webpack)) {
|
144 | return (
|
145 |
|
146 | cssModuleCache.get(webpack)
|
147 | );
|
148 | }
|
149 |
|
150 | class CssModule extends webpack.Module {
|
151 | |
152 |
|
153 |
|
154 | constructor({
|
155 | context,
|
156 | identifier,
|
157 | identifierIndex,
|
158 | content,
|
159 | layer,
|
160 | supports,
|
161 | media,
|
162 | sourceMap,
|
163 | assets,
|
164 | assetsInfo
|
165 | }) {
|
166 | super(MODULE_TYPE,
|
167 |
|
168 | context);
|
169 | this.id = "";
|
170 | this._context = context;
|
171 | this._identifier = identifier;
|
172 | this._identifierIndex = identifierIndex;
|
173 | this.content = content;
|
174 | this.layer = layer;
|
175 | this.supports = supports;
|
176 | this.media = media;
|
177 | this.sourceMap = sourceMap;
|
178 | this.assets = assets;
|
179 | this.assetsInfo = assetsInfo;
|
180 | this._needBuild = true;
|
181 | }
|
182 |
|
183 |
|
184 | size() {
|
185 | return this.content.length;
|
186 | }
|
187 |
|
188 | identifier() {
|
189 | return `css|${this._identifier}|${this._identifierIndex}`;
|
190 | }
|
191 | |
192 |
|
193 |
|
194 |
|
195 |
|
196 |
|
197 | readableIdentifier(requestShortener) {
|
198 | return `css ${requestShortener.shorten(this._identifier)}${this._identifierIndex ? ` (${this._identifierIndex})` : ""}`;
|
199 | }
|
200 |
|
201 |
|
202 | getSourceTypes() {
|
203 | return TYPES;
|
204 | }
|
205 |
|
206 |
|
207 | codeGeneration() {
|
208 | return CODE_GENERATION_RESULT;
|
209 | }
|
210 |
|
211 | nameForCondition() {
|
212 | const resource =
|
213 |
|
214 | this._identifier.split("!").pop();
|
215 |
|
216 | const idx = resource.indexOf("?");
|
217 |
|
218 | if (idx >= 0) {
|
219 | return resource.substring(0, idx);
|
220 | }
|
221 |
|
222 | return resource;
|
223 | }
|
224 | |
225 |
|
226 |
|
227 |
|
228 |
|
229 | updateCacheModule(module) {
|
230 | if (this.content !==
|
231 |
|
232 | module.content || this.layer !==
|
233 |
|
234 | module.layer || this.supports !==
|
235 |
|
236 | module.supports || this.media !==
|
237 |
|
238 | module.media || this.sourceMap !==
|
239 |
|
240 | module.sourceMap || this.assets !==
|
241 |
|
242 | module.assets || this.assetsInfo !==
|
243 |
|
244 | module.assetsInfo) {
|
245 | this._needBuild = true;
|
246 | this.content =
|
247 |
|
248 | module.content;
|
249 | this.layer =
|
250 |
|
251 | module.layer;
|
252 | this.supports =
|
253 |
|
254 | module.supports;
|
255 | this.media =
|
256 |
|
257 | module.media;
|
258 | this.sourceMap =
|
259 |
|
260 | module.sourceMap;
|
261 | this.assets =
|
262 |
|
263 | module.assets;
|
264 | this.assetsInfo =
|
265 |
|
266 | module.assetsInfo;
|
267 | }
|
268 | }
|
269 |
|
270 |
|
271 | needRebuild() {
|
272 | return this._needBuild;
|
273 | }
|
274 |
|
275 | |
276 |
|
277 |
|
278 |
|
279 |
|
280 |
|
281 | needBuild(context, callback) {
|
282 |
|
283 | callback(undefined, this._needBuild);
|
284 | }
|
285 | |
286 |
|
287 |
|
288 |
|
289 |
|
290 |
|
291 |
|
292 |
|
293 |
|
294 | build(options, compilation, resolver, fileSystem, callback) {
|
295 | this.buildInfo = {
|
296 | assets: this.assets,
|
297 | assetsInfo: this.assetsInfo,
|
298 | cacheable: true,
|
299 | hash: this._computeHash(
|
300 |
|
301 | compilation.outputOptions.hashFunction)
|
302 | };
|
303 | this.buildMeta = {};
|
304 | this._needBuild = false;
|
305 | callback();
|
306 | }
|
307 | |
308 |
|
309 |
|
310 |
|
311 |
|
312 |
|
313 |
|
314 | _computeHash(hashFunction) {
|
315 | const hash = webpack.util.createHash(hashFunction);
|
316 | hash.update(this.content);
|
317 |
|
318 | if (this.layer) {
|
319 | hash.update(this.layer);
|
320 | }
|
321 |
|
322 | hash.update(this.supports || "");
|
323 | hash.update(this.media || "");
|
324 | hash.update(this.sourceMap || "");
|
325 | return hash.digest("hex");
|
326 | }
|
327 | |
328 |
|
329 |
|
330 |
|
331 |
|
332 |
|
333 | updateHash(hash, context) {
|
334 | super.updateHash(hash, context);
|
335 | hash.update(this.buildInfo.hash);
|
336 | }
|
337 | |
338 |
|
339 |
|
340 |
|
341 |
|
342 | serialize(context) {
|
343 | const {
|
344 | write
|
345 | } = context;
|
346 | write(this._context);
|
347 | write(this._identifier);
|
348 | write(this._identifierIndex);
|
349 | write(this.content);
|
350 | write(this.layer);
|
351 | write(this.supports);
|
352 | write(this.media);
|
353 | write(this.sourceMap);
|
354 | write(this.assets);
|
355 | write(this.assetsInfo);
|
356 | write(this._needBuild);
|
357 | super.serialize(context);
|
358 | }
|
359 | |
360 |
|
361 |
|
362 |
|
363 |
|
364 | deserialize(context) {
|
365 | this._needBuild = context.read();
|
366 | super.deserialize(context);
|
367 | }
|
368 |
|
369 | }
|
370 |
|
371 | cssModuleCache.set(webpack, CssModule);
|
372 | webpack.util.serialization.register(CssModule, path.resolve(__dirname, "CssModule"),
|
373 | null, {
|
374 | serialize(instance, context) {
|
375 | instance.serialize(context);
|
376 | },
|
377 |
|
378 | deserialize(context) {
|
379 | const {
|
380 | read
|
381 | } = context;
|
382 | const contextModule = read();
|
383 | const identifier = read();
|
384 | const identifierIndex = read();
|
385 | const content = read();
|
386 | const layer = read();
|
387 | const supports = read();
|
388 | const media = read();
|
389 | const sourceMap = read();
|
390 | const assets = read();
|
391 | const assetsInfo = read();
|
392 | const dep = new CssModule({
|
393 | context: contextModule,
|
394 | identifier,
|
395 | identifierIndex,
|
396 | content,
|
397 | layer,
|
398 | supports,
|
399 | media,
|
400 | sourceMap,
|
401 | assets,
|
402 | assetsInfo
|
403 | });
|
404 | dep.deserialize(context);
|
405 | return dep;
|
406 | }
|
407 |
|
408 | });
|
409 | return CssModule;
|
410 | }
|
411 | |
412 |
|
413 |
|
414 |
|
415 |
|
416 |
|
417 | static getCssDependency(webpack) {
|
418 | |
419 |
|
420 |
|
421 | if (cssDependencyCache.has(webpack)) {
|
422 | return (
|
423 |
|
424 | cssDependencyCache.get(webpack)
|
425 | );
|
426 | }
|
427 |
|
428 | class CssDependency extends webpack.Dependency {
|
429 | |
430 |
|
431 |
|
432 |
|
433 |
|
434 | constructor({
|
435 | identifier,
|
436 | content,
|
437 | layer,
|
438 | supports,
|
439 | media,
|
440 | sourceMap
|
441 | }, context, identifierIndex) {
|
442 | super();
|
443 | this.identifier = identifier;
|
444 | this.identifierIndex = identifierIndex;
|
445 | this.content = content;
|
446 | this.layer = layer;
|
447 | this.supports = supports;
|
448 | this.media = media;
|
449 | this.sourceMap = sourceMap;
|
450 | this.context = context;
|
451 |
|
452 |
|
453 |
|
454 | this.assets = undefined;
|
455 |
|
456 |
|
457 |
|
458 | this.assetsInfo = undefined;
|
459 | }
|
460 | |
461 |
|
462 |
|
463 |
|
464 |
|
465 | getResourceIdentifier() {
|
466 | return `css-module-${this.identifier}-${this.identifierIndex}`;
|
467 | }
|
468 | |
469 |
|
470 |
|
471 |
|
472 |
|
473 |
|
474 | getModuleEvaluationSideEffectsState() {
|
475 | return webpack.ModuleGraphConnection.TRANSITIVE_ONLY;
|
476 | }
|
477 | |
478 |
|
479 |
|
480 |
|
481 |
|
482 | serialize(context) {
|
483 | const {
|
484 | write
|
485 | } = context;
|
486 | write(this.identifier);
|
487 | write(this.content);
|
488 | write(this.layer);
|
489 | write(this.supports);
|
490 | write(this.media);
|
491 | write(this.sourceMap);
|
492 | write(this.context);
|
493 | write(this.identifierIndex);
|
494 | write(this.assets);
|
495 | write(this.assetsInfo);
|
496 | super.serialize(context);
|
497 | }
|
498 | |
499 |
|
500 |
|
501 |
|
502 |
|
503 | deserialize(context) {
|
504 | super.deserialize(context);
|
505 | }
|
506 |
|
507 | }
|
508 |
|
509 | cssDependencyCache.set(webpack, CssDependency);
|
510 | webpack.util.serialization.register(CssDependency, path.resolve(__dirname, "CssDependency"),
|
511 | null, {
|
512 | serialize(instance, context) {
|
513 | instance.serialize(context);
|
514 | },
|
515 |
|
516 | deserialize(context) {
|
517 | const {
|
518 | read
|
519 | } = context;
|
520 | const dep = new CssDependency({
|
521 | identifier: read(),
|
522 | content: read(),
|
523 | layer: read(),
|
524 | supports: read(),
|
525 | media: read(),
|
526 | sourceMap: read()
|
527 | }, read(), read());
|
528 | const assets = read();
|
529 | const assetsInfo = read();
|
530 | dep.assets = assets;
|
531 | dep.assetsInfo = assetsInfo;
|
532 | dep.deserialize(context);
|
533 | return dep;
|
534 | }
|
535 |
|
536 | });
|
537 | return CssDependency;
|
538 | }
|
539 | |
540 |
|
541 |
|
542 |
|
543 |
|
544 | constructor(options = {}) {
|
545 | validate(
|
546 |
|
547 | schema, options, {
|
548 | baseDataPath: "options"
|
549 | });
|
550 | |
551 |
|
552 |
|
553 |
|
554 |
|
555 |
|
556 | this._sortedModulesCache = new WeakMap();
|
557 | |
558 |
|
559 |
|
560 |
|
561 |
|
562 | this.options = Object.assign({
|
563 | filename: DEFAULT_FILENAME,
|
564 | ignoreOrder: false,
|
565 |
|
566 |
|
567 | experimentalUseImportModule: undefined,
|
568 | runtime: true
|
569 | }, options);
|
570 | |
571 |
|
572 |
|
573 |
|
574 |
|
575 | this.runtimeOptions = {
|
576 | insert: options.insert,
|
577 | linkType:
|
578 | typeof options.linkType === "boolean" &&
|
579 |
|
580 | options.linkType === true || typeof options.linkType === "undefined" ? "text/css" : options.linkType,
|
581 | attributes: options.attributes
|
582 | };
|
583 |
|
584 | if (!this.options.chunkFilename) {
|
585 | const {
|
586 | filename
|
587 | } = this.options;
|
588 |
|
589 | if (typeof filename !== "function") {
|
590 | const hasName =
|
591 |
|
592 | filename.includes("[name]");
|
593 | const hasId =
|
594 |
|
595 | filename.includes("[id]");
|
596 | const hasChunkHash =
|
597 |
|
598 | filename.includes("[chunkhash]");
|
599 | const hasContentHash =
|
600 |
|
601 | filename.includes("[contenthash]");
|
602 |
|
603 | if (hasChunkHash || hasContentHash || hasName || hasId) {
|
604 | this.options.chunkFilename = filename;
|
605 | } else {
|
606 |
|
607 | this.options.chunkFilename =
|
608 |
|
609 | filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2");
|
610 | }
|
611 | } else {
|
612 | this.options.chunkFilename = "[id].css";
|
613 | }
|
614 | }
|
615 | }
|
616 | |
617 |
|
618 |
|
619 |
|
620 |
|
621 | apply(compiler) {
|
622 | const {
|
623 | webpack
|
624 | } = compiler;
|
625 |
|
626 | if (this.options.experimentalUseImportModule) {
|
627 | if (typeof
|
628 |
|
629 | compiler.options.experiments.executeModule === "undefined") {
|
630 |
|
631 |
|
632 | compiler.options.experiments.executeModule = true;
|
633 | }
|
634 | }
|
635 |
|
636 |
|
637 |
|
638 | if (!registered.has(webpack)) {
|
639 | registered.add(webpack);
|
640 | webpack.util.serialization.registerLoader(/^mini-css-extract-plugin\//, trueFn);
|
641 | }
|
642 |
|
643 | const {
|
644 | splitChunks
|
645 | } = compiler.options.optimization;
|
646 |
|
647 | if (splitChunks) {
|
648 | if (
|
649 |
|
650 | splitChunks.defaultSizeTypes.includes("...")) {
|
651 |
|
652 | splitChunks.defaultSizeTypes.push(MODULE_TYPE);
|
653 | }
|
654 | }
|
655 |
|
656 | const CssModule = MiniCssExtractPlugin.getCssModule(webpack);
|
657 | const CssDependency = MiniCssExtractPlugin.getCssDependency(webpack);
|
658 | const {
|
659 | NormalModule
|
660 | } = compiler.webpack;
|
661 | compiler.hooks.compilation.tap(pluginName, compilation => {
|
662 | const {
|
663 | loader: normalModuleHook
|
664 | } = NormalModule.getCompilationHooks(compilation);
|
665 | normalModuleHook.tap(pluginName,
|
666 | |
667 |
|
668 |
|
669 | loaderContext => {
|
670 |
|
671 |
|
672 | loaderContext[pluginSymbol] = {
|
673 | experimentalUseImportModule: this.options.experimentalUseImportModule
|
674 | };
|
675 | });
|
676 | });
|
677 | compiler.hooks.thisCompilation.tap(pluginName, compilation => {
|
678 | class CssModuleFactory {
|
679 | |
680 |
|
681 |
|
682 |
|
683 |
|
684 | create({
|
685 | dependencies: [dependency]
|
686 | }, callback) {
|
687 |
|
688 | callback(undefined, new CssModule(
|
689 |
|
690 | dependency));
|
691 | }
|
692 |
|
693 | }
|
694 |
|
695 | compilation.dependencyFactories.set(CssDependency, new CssModuleFactory());
|
696 |
|
697 | class CssDependencyTemplate {
|
698 |
|
699 | apply() {}
|
700 |
|
701 | }
|
702 |
|
703 | compilation.dependencyTemplates.set(CssDependency, new CssDependencyTemplate());
|
704 | compilation.hooks.renderManifest.tap(pluginName,
|
705 | |
706 |
|
707 |
|
708 |
|
709 |
|
710 | (result, {
|
711 | chunk
|
712 | }) => {
|
713 | const {
|
714 | chunkGraph
|
715 | } = compilation;
|
716 | const {
|
717 | HotUpdateChunk
|
718 | } = webpack;
|
719 |
|
720 |
|
721 | if (chunk instanceof HotUpdateChunk) {
|
722 | return;
|
723 | }
|
724 |
|
725 |
|
726 |
|
727 | const renderedModules = Array.from(
|
728 |
|
729 | this.getChunkModules(chunk, chunkGraph)).filter(module => module.type === MODULE_TYPE);
|
730 | const filenameTemplate =
|
731 |
|
732 | chunk.canBeInitial() ? this.options.filename : this.options.chunkFilename;
|
733 |
|
734 | if (renderedModules.length > 0) {
|
735 | result.push({
|
736 | render: () => this.renderContentAsset(compiler, compilation, chunk, renderedModules, compilation.runtimeTemplate.requestShortener, filenameTemplate, {
|
737 | contentHashType: MODULE_TYPE,
|
738 | chunk
|
739 | }),
|
740 | filenameTemplate,
|
741 | pathOptions: {
|
742 | chunk,
|
743 | contentHashType: MODULE_TYPE
|
744 | },
|
745 | identifier: `${pluginName}.${chunk.id}`,
|
746 | hash: chunk.contentHash[MODULE_TYPE]
|
747 | });
|
748 | }
|
749 | });
|
750 | compilation.hooks.contentHash.tap(pluginName, chunk => {
|
751 | const {
|
752 | outputOptions,
|
753 | chunkGraph
|
754 | } = compilation;
|
755 | const modules = this.sortModules(compilation, chunk,
|
756 |
|
757 | chunkGraph.getChunkModulesIterableBySourceType(chunk, MODULE_TYPE), compilation.runtimeTemplate.requestShortener);
|
758 |
|
759 | if (modules) {
|
760 | const {
|
761 | hashFunction,
|
762 | hashDigest,
|
763 | hashDigestLength
|
764 | } = outputOptions;
|
765 | const {
|
766 | createHash
|
767 | } = compiler.webpack.util;
|
768 | const hash = createHash(
|
769 |
|
770 | hashFunction);
|
771 |
|
772 | for (const m of modules) {
|
773 | hash.update(chunkGraph.getModuleHash(m, chunk.runtime));
|
774 | }
|
775 |
|
776 |
|
777 | chunk.contentHash[MODULE_TYPE] =
|
778 |
|
779 | hash.digest(hashDigest).substring(0, hashDigestLength);
|
780 | }
|
781 | });
|
782 |
|
783 | if (!this.options.runtime) {
|
784 | return;
|
785 | }
|
786 |
|
787 | const {
|
788 | Template,
|
789 | RuntimeGlobals,
|
790 | RuntimeModule,
|
791 | runtime
|
792 | } = webpack;
|
793 | |
794 |
|
795 |
|
796 |
|
797 |
|
798 |
|
799 |
|
800 | const getCssChunkObject = (mainChunk, compilation) => {
|
801 |
|
802 | const obj = {};
|
803 | const {
|
804 | chunkGraph
|
805 | } = compilation;
|
806 |
|
807 | for (const chunk of mainChunk.getAllAsyncChunks()) {
|
808 | const modules = chunkGraph.getOrderedChunkModulesIterable(chunk, compareModulesByIdentifier);
|
809 |
|
810 | for (const module of modules) {
|
811 | if (module.type === MODULE_TYPE) {
|
812 | obj[
|
813 |
|
814 | chunk.id] = 1;
|
815 | break;
|
816 | }
|
817 | }
|
818 | }
|
819 |
|
820 | return obj;
|
821 | };
|
822 |
|
823 | class CssLoadingRuntimeModule extends RuntimeModule {
|
824 | |
825 |
|
826 |
|
827 |
|
828 | constructor(runtimeRequirements, runtimeOptions) {
|
829 | super("css loading", 10);
|
830 | this.runtimeRequirements = runtimeRequirements;
|
831 | this.runtimeOptions = runtimeOptions;
|
832 | }
|
833 |
|
834 | generate() {
|
835 | const {
|
836 | chunk,
|
837 | runtimeRequirements
|
838 | } = this;
|
839 | const {
|
840 | runtimeTemplate,
|
841 | outputOptions: {
|
842 | crossOriginLoading
|
843 | }
|
844 | } = this.compilation;
|
845 | const chunkMap = getCssChunkObject(chunk, this.compilation);
|
846 | const withLoading = runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) && Object.keys(chunkMap).length > 0;
|
847 | const withHmr = runtimeRequirements.has(RuntimeGlobals.hmrDownloadUpdateHandlers);
|
848 |
|
849 | if (!withLoading && !withHmr) {
|
850 | return "";
|
851 | }
|
852 |
|
853 | return Template.asString([`var createStylesheet = ${runtimeTemplate.basicFunction("chunkId, fullhref, resolve, reject", ['var linkTag = document.createElement("link");', this.runtimeOptions.attributes ? Template.asString(Object.entries(this.runtimeOptions.attributes).map(entry => {
|
854 | const [key, value] = entry;
|
855 | return `linkTag.setAttribute(${JSON.stringify(key)}, ${JSON.stringify(value)});`;
|
856 | })) : "", '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;", "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(["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, resolve, reject);"])});`)}`, withLoading ? Template.asString(["// object to store loaded CSS chunks", "var installedCssChunks = {", Template.indent(
|
857 |
|
858 | 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, ${runtimeTemplate.basicFunction("", ['tag.as = "style";', 'tag.rel = "preload";', "resolve();"])}, reject);`, "oldTags.push(oldTag);", "newTags.push(tag);"])}));`])});`])}`]) : "// no hmr"]);
|
859 | }
|
860 |
|
861 | }
|
862 |
|
863 | const enabledChunks = new WeakSet();
|
864 | |
865 |
|
866 |
|
867 |
|
868 |
|
869 | const handler = (chunk, set) => {
|
870 | if (enabledChunks.has(chunk)) {
|
871 | return;
|
872 | }
|
873 |
|
874 | enabledChunks.add(chunk);
|
875 |
|
876 | if (typeof this.options.chunkFilename === "string" && /\[(full)?hash(:\d+)?\]/.test(this.options.chunkFilename)) {
|
877 | set.add(RuntimeGlobals.getFullHash);
|
878 | }
|
879 |
|
880 | set.add(RuntimeGlobals.publicPath);
|
881 | compilation.addRuntimeModule(chunk, new runtime.GetChunkFilenameRuntimeModule(MODULE_TYPE, "mini-css", `${RuntimeGlobals.require}.miniCssF`,
|
882 | /**
|
883 | * @param {Chunk} referencedChunk
|
884 | * @returns {TODO}
|
885 | */
|
886 | referencedChunk => {
|
887 | if (!referencedChunk.contentHash[MODULE_TYPE]) {
|
888 | return false;
|
889 | }
|
890 |
|
891 | return referencedChunk.canBeInitial() ? this.options.filename : this.options.chunkFilename;
|
892 | }, false));
|
893 | compilation.addRuntimeModule(chunk, new CssLoadingRuntimeModule(set, this.runtimeOptions));
|
894 | };
|
895 |
|
896 | compilation.hooks.runtimeRequirementInTree.for(RuntimeGlobals.ensureChunkHandlers).tap(pluginName, handler);
|
897 | compilation.hooks.runtimeRequirementInTree.for(RuntimeGlobals.hmrDownloadUpdateHandlers).tap(pluginName, handler);
|
898 | });
|
899 | }
|
900 | /**
|
901 | * @private
|
902 | * @param {Chunk} chunk
|
903 | * @param {ChunkGraph} chunkGraph
|
904 | * @returns {Iterable<Module>}
|
905 | */
|
906 |
|
907 |
|
908 | getChunkModules(chunk, chunkGraph) {
|
909 | return typeof chunkGraph !== "undefined" ? chunkGraph.getOrderedChunkModulesIterable(chunk, compareModulesByIdentifier) : chunk.modulesIterable;
|
910 | }
|
911 | /**
|
912 | * @private
|
913 | * @param {Compilation} compilation
|
914 | * @param {Chunk} chunk
|
915 | * @param {CssModule[]} modules
|
916 | * @param {Compilation["requestShortener"]} requestShortener
|
917 | * @returns {Set<CssModule>}
|
918 | */
|
919 |
|
920 |
|
921 | sortModules(compilation, chunk, modules, requestShortener) {
|
922 | let usedModules = this._sortedModulesCache.get(chunk);
|
923 |
|
924 | if (usedModules || !modules) {
|
925 | return (
|
926 | /** @type {Set<CssModule>} */
|
927 | usedModules
|
928 | );
|
929 | }
|
930 | /** @type {CssModule[]} */
|
931 |
|
932 |
|
933 | const modulesList = [...modules]; // Store dependencies for modules
|
934 |
|
935 | /** @type {Map<CssModule, Set<CssModule>>} */
|
936 |
|
937 | const moduleDependencies = new Map(modulesList.map(m => [m,
|
938 | /** @type {Set<CssModule>} */
|
939 | new Set()]));
|
940 | /** @type {Map<CssModule, Map<CssModule, Set<ChunkGroup>>>} */
|
941 |
|
942 | const moduleDependenciesReasons = new Map(modulesList.map(m => [m, new Map()])); // Get ordered list of modules per chunk group
|
943 | // This loop also gathers dependencies from the ordered lists
|
944 | // Lists are in reverse order to allow to use Array.pop()
|
945 |
|
946 | /** @type {CssModule[][]} */
|
947 |
|
948 | const modulesByChunkGroup = Array.from(chunk.groupsIterable, chunkGroup => {
|
949 | const sortedModules = modulesList.map(module => {
|
950 | return {
|
951 | module,
|
952 | index: chunkGroup.getModulePostOrderIndex(module)
|
953 | };
|
954 | }) // eslint-disable-next-line no-undefined
|
955 | .filter(item => item.index !== undefined).sort((a, b) => b.index - a.index).map(item => item.module);
|
956 |
|
957 | for (let i = 0; i < sortedModules.length; i++) {
|
958 | const set = moduleDependencies.get(sortedModules[i]);
|
959 | const reasons =
|
960 | /** @type {Map<CssModule, Set<ChunkGroup>>} */
|
961 | moduleDependenciesReasons.get(sortedModules[i]);
|
962 |
|
963 | for (let j = i + 1; j < sortedModules.length; j++) {
|
964 | const module = sortedModules[j];
|
965 | /** @type {Set<CssModule>} */
|
966 |
|
967 | set.add(module);
|
968 | const reason = reasons.get(module) ||
|
969 | /** @type {Set<ChunkGroup>} */
|
970 | new Set();
|
971 | reason.add(chunkGroup);
|
972 | reasons.set(module, reason);
|
973 | }
|
974 | }
|
975 |
|
976 | return sortedModules;
|
977 | }); // set with already included modules in correct order
|
978 |
|
979 | usedModules = new Set();
|
980 | /**
|
981 | * @param {CssModule} m
|
982 | * @returns {boolean}
|
983 | */
|
984 |
|
985 | const unusedModulesFilter = m => !
|
986 | /** @type {Set<CssModule>} */
|
987 | usedModules.has(m);
|
988 |
|
989 | while (usedModules.size < modulesList.length) {
|
990 | let success = false;
|
991 | let bestMatch;
|
992 | let bestMatchDeps; // get first module where dependencies are fulfilled
|
993 |
|
994 | for (const list of modulesByChunkGroup) {
|
995 | // skip and remove already added modules
|
996 | while (list.length > 0 && usedModules.has(list[list.length - 1])) {
|
997 | list.pop();
|
998 | } // skip empty lists
|
999 |
|
1000 |
|
1001 | if (list.length !== 0) {
|
1002 | const module = list[list.length - 1];
|
1003 | const deps = moduleDependencies.get(module); // determine dependencies that are not yet included
|
1004 |
|
1005 | const failedDeps = Array.from(
|
1006 | /** @type {Set<CssModule>} */
|
1007 | deps).filter(unusedModulesFilter); // store best match for fallback behavior
|
1008 |
|
1009 | if (!bestMatchDeps || bestMatchDeps.length > failedDeps.length) {
|
1010 | bestMatch = list;
|
1011 | bestMatchDeps = failedDeps;
|
1012 | }
|
1013 |
|
1014 | if (failedDeps.length === 0) {
|
1015 | // use this module and remove it from list
|
1016 | usedModules.add(
|
1017 | /** @type {CssModule} */
|
1018 | list.pop());
|
1019 | success = true;
|
1020 | break;
|
1021 | }
|
1022 | }
|
1023 | }
|
1024 |
|
1025 | if (!success) {
|
1026 | // no module found => there is a conflict
|
1027 | // use list with fewest failed deps
|
1028 | // and emit a warning
|
1029 | const fallbackModule =
|
1030 | /** @type {CssModule[]} */
|
1031 | bestMatch.pop();
|
1032 |
|
1033 | if (!this.options.ignoreOrder) {
|
1034 | const reasons = moduleDependenciesReasons.get(
|
1035 | /** @type {CssModule} */
|
1036 | fallbackModule);
|
1037 | compilation.warnings.push(
|
1038 | /** @type {WebpackError} */
|
1039 | new Error([`chunk ${chunk.name || chunk.id} [${pluginName}]`, "Conflicting order. Following module has been added:", ` * ${
|
1040 |
|
1041 | fallbackModule.readableIdentifier(requestShortener)}`, "despite it was not able to fulfill desired ordering with these modules:", ...
|
1042 | /** @type {CssModule[]} */
|
1043 | bestMatchDeps.map(m => {
|
1044 | const goodReasonsMap = moduleDependenciesReasons.get(m);
|
1045 | const goodReasons = goodReasonsMap && goodReasonsMap.get(
|
1046 | /** @type {CssModule} */
|
1047 | fallbackModule);
|
1048 | const failedChunkGroups = Array.from(
|
1049 | /** @type {Set<ChunkGroup>} */
|
1050 |
|
1051 | /** @type {Map<CssModule, Set<ChunkGroup>>} */
|
1052 | reasons.get(m), cg => cg.name).join(", ");
|
1053 | const goodChunkGroups = goodReasons && Array.from(goodReasons, cg => cg.name).join(", ");
|
1054 | 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");
|
1055 | })].join("\n")));
|
1056 | }
|
1057 |
|
1058 | usedModules.add(
|
1059 |
|
1060 | fallbackModule);
|
1061 | }
|
1062 | }
|
1063 |
|
1064 | this._sortedModulesCache.set(chunk, usedModules);
|
1065 |
|
1066 | return usedModules;
|
1067 | }
|
1068 | |
1069 |
|
1070 |
|
1071 |
|
1072 |
|
1073 |
|
1074 |
|
1075 |
|
1076 |
|
1077 |
|
1078 |
|
1079 |
|
1080 |
|
1081 | renderContentAsset(compiler, compilation, chunk, modules, requestShortener, filenameTemplate, pathData) {
|
1082 | const usedModules = this.sortModules(compilation, chunk, modules, requestShortener);
|
1083 | const {
|
1084 | ConcatSource,
|
1085 | SourceMapSource,
|
1086 | RawSource
|
1087 | } = compiler.webpack.sources;
|
1088 | const source = new ConcatSource();
|
1089 | const externalsSource = new ConcatSource();
|
1090 |
|
1091 | for (const module of usedModules) {
|
1092 | let content = module.content.toString();
|
1093 | const readableIdentifier = module.readableIdentifier(requestShortener);
|
1094 | const startsWithAtRuleImport = /^@import url/.test(content);
|
1095 | let header;
|
1096 |
|
1097 | if (compilation.outputOptions.pathinfo) {
|
1098 |
|
1099 | const reqStr = readableIdentifier.replace(/\*\//g, "*_/");
|
1100 | const reqStrStar = "*".repeat(reqStr.length);
|
1101 | const headerStr = `/*!****${reqStrStar}****!*\\\n !*** ${reqStr} ***!\n \\****${reqStrStar}****/\n`;
|
1102 | header = new RawSource(headerStr);
|
1103 | }
|
1104 |
|
1105 | if (startsWithAtRuleImport) {
|
1106 | if (typeof header !== "undefined") {
|
1107 | externalsSource.add(header);
|
1108 | }
|
1109 |
|
1110 |
|
1111 |
|
1112 | if (module.media) {
|
1113 |
|
1114 |
|
1115 |
|
1116 | content = content.replace(/;|\s*$/, module.media);
|
1117 | }
|
1118 |
|
1119 | externalsSource.add(content);
|
1120 | externalsSource.add("\n");
|
1121 | } else {
|
1122 | if (typeof header !== "undefined") {
|
1123 | source.add(header);
|
1124 | }
|
1125 |
|
1126 | if (module.supports) {
|
1127 | source.add(`@supports (${module.supports}) {\n`);
|
1128 | }
|
1129 |
|
1130 | if (module.media) {
|
1131 | source.add(`@media ${module.media} {\n`);
|
1132 | }
|
1133 |
|
1134 | const needLayer = typeof module.layer !== "undefined";
|
1135 |
|
1136 | if (needLayer) {
|
1137 | source.add(`@layer${module.layer.length > 0 ? ` ${module.layer}` : ""} {\n`);
|
1138 | }
|
1139 |
|
1140 | const {
|
1141 | path: filename
|
1142 | } = compilation.getPathWithInfo(filenameTemplate, pathData);
|
1143 | const undoPath = getUndoPath(filename, compiler.outputPath, false);
|
1144 | content = content.replace(new RegExp(ABSOLUTE_PUBLIC_PATH, "g"), "");
|
1145 | content = content.replace(new RegExp(SINGLE_DOT_PATH_SEGMENT, "g"), ".");
|
1146 | content = content.replace(new RegExp(AUTO_PUBLIC_PATH, "g"), undoPath);
|
1147 |
|
1148 | if (module.sourceMap) {
|
1149 | source.add(new SourceMapSource(content, readableIdentifier, module.sourceMap.toString()));
|
1150 | } else {
|
1151 | source.add(new RawSource(content));
|
1152 | }
|
1153 |
|
1154 | source.add("\n");
|
1155 |
|
1156 | if (needLayer) {
|
1157 | source.add("}\n");
|
1158 | }
|
1159 |
|
1160 | if (module.media) {
|
1161 | source.add("}\n");
|
1162 | }
|
1163 |
|
1164 | if (module.supports) {
|
1165 | source.add("}\n");
|
1166 | }
|
1167 | }
|
1168 | }
|
1169 |
|
1170 | return new ConcatSource(externalsSource, source);
|
1171 | }
|
1172 |
|
1173 | }
|
1174 |
|
1175 | MiniCssExtractPlugin.pluginName = pluginName;
|
1176 | MiniCssExtractPlugin.pluginSymbol = pluginSymbol;
|
1177 | MiniCssExtractPlugin.loader = require.resolve("./loader");
|
1178 | module.exports = MiniCssExtractPlugin; |
\ | No newline at end of file |