WXL
4 天以前 3bd962a6d7f61239c020e2dbbeb7341e5b842dd1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/*
    MIT License http://www.opensource.org/licenses/mit-license.php
    Author Natsu @xiaoxiaojx
*/
 
"use strict";
 
const { SyncWaterfallHook } = require("tapable");
const Compilation = require("../Compilation");
const RuntimeGlobals = require("../RuntimeGlobals");
const RuntimeModule = require("../RuntimeModule");
const Template = require("../Template");
 
/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
 
/**
 * @typedef {object} CssInjectCompilationHooks
 * @property {SyncWaterfallHook<[string, Chunk]>} createStyle
 */
 
/** @type {WeakMap<Compilation, CssInjectCompilationHooks>} */
const compilationHooksMap = new WeakMap();
 
class CssInjectStyleRuntimeModule extends RuntimeModule {
    /**
     * @param {Compilation} compilation the compilation
     * @returns {CssInjectCompilationHooks} hooks
     */
    static getCompilationHooks(compilation) {
        if (!(compilation instanceof Compilation)) {
            throw new TypeError(
                "The 'compilation' argument must be an instance of Compilation"
            );
        }
        let hooks = compilationHooksMap.get(compilation);
        if (hooks === undefined) {
            hooks = {
                createStyle: new SyncWaterfallHook(["source", "chunk"])
            };
            compilationHooksMap.set(compilation, hooks);
        }
        return hooks;
    }
 
    /**
     * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements
     */
    constructor(runtimeRequirements) {
        super("css inject style", RuntimeModule.STAGE_ATTACH);
        /** @type {ReadOnlyRuntimeRequirements} */
        this._runtimeRequirements = runtimeRequirements;
    }
 
    /**
     * Generates runtime code for this runtime module.
     * @returns {string | null} runtime code
     */
    generate() {
        const compilation = /** @type {Compilation} */ (this.compilation);
        const { runtimeTemplate, outputOptions } = compilation;
        const { uniqueName } = outputOptions;
        const { _runtimeRequirements } = this;
 
        /** @type {boolean} */
        const withHmr =
            _runtimeRequirements &&
            _runtimeRequirements.has(RuntimeGlobals.hmrDownloadUpdateHandlers);
 
        const { createStyle } =
            CssInjectStyleRuntimeModule.getCompilationHooks(compilation);
 
        const createStyleElementCode = Template.asString([
            "var style = document.createElement('style');",
            "",
            `if (${RuntimeGlobals.scriptNonce}) {`,
            Template.indent(
                `style.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
            ),
            "}",
            'style.setAttribute("data-webpack", getDataWebpackId(key));'
        ]);
 
        return Template.asString([
            `var dataWebpackPrefix = ${uniqueName ? JSON.stringify(`${uniqueName}:`) : '"webpack:"'};`,
            "",
            "function getDataWebpackId(identifier) {",
            Template.indent("return dataWebpackPrefix + identifier;"),
            "}",
            "",
            "function applyStyle(styleElement, css) {",
            Template.indent("styleElement.textContent = css;"),
            "}",
            "",
            "function removeStyleElement(styleElement) {",
            Template.indent([
                "if (styleElement.parentNode) {",
                Template.indent("styleElement.parentNode.removeChild(styleElement);"),
                "}"
            ]),
            "}",
            "",
            "function findStyleElement(identifier) {",
            Template.indent([
                "var elements = document.getElementsByTagName('style');",
                "for (var i = 0; i < elements.length; i++) {",
                Template.indent([
                    "var el = elements[i];",
                    "if (el.getAttribute('data-webpack') === getDataWebpackId(identifier)) {",
                    Template.indent("return el;"),
                    "}"
                ]),
                "}",
                "return null;"
            ]),
            "}",
            "",
            "function insertStyleElement(key) {",
            Template.indent([
                createStyle.call(
                    createStyleElementCode,
                    /** @type {Chunk} */ (this.chunk)
                ),
                "",
                "document.head.appendChild(style);",
                "",
                "return style;"
            ]),
            "}",
            "",
            `${RuntimeGlobals.cssInjectStyle} = ${runtimeTemplate.basicFunction(
                "identifier, css",
                [
                    "var element = findStyleElement(identifier);",
                    "if (element) {",
                    Template.indent("applyStyle(element, css);"),
                    "} else {",
                    Template.indent([
                        "var element = insertStyleElement(identifier);",
                        "applyStyle(element, css);"
                    ]),
                    "}"
                ]
            )};`,
            "",
            `${RuntimeGlobals.cssInjectStyle}.removeModules = ${runtimeTemplate.basicFunction(
                "removedModules",
                [
                    "if (!removedModules) return;",
                    "var identifiers = Array.isArray(removedModules) ? removedModules : [removedModules];",
                    "for (var i = 0; i < identifiers.length; i++) {",
                    Template.indent([
                        "var identifier = identifiers[i];",
                        "var element = findStyleElement(identifier);",
                        "if (element) {",
                        Template.indent("removeStyleElement(element);"),
                        "}"
                    ]),
                    "}"
                ]
            )};`,
            withHmr
                ? Template.asString([
                        `${RuntimeGlobals.hmrDownloadUpdateHandlers}.cssInjectStyle = ${runtimeTemplate.basicFunction(
                            "chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList, css",
                            [
                                "if (removedModules) {",
                                Template.indent(
                                    `${RuntimeGlobals.cssInjectStyle}.removeModules(removedModules);`
                                ),
                                "}"
                            ]
                        )};`
                    ])
                : "// no css inject style HMR download handler"
        ]);
    }
}
 
module.exports = CssInjectStyleRuntimeModule;