-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
Copy pathCssGenerator.js
323 lines (291 loc) · 9.72 KB
/
CssGenerator.js
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Sergey Melyukov @smelukov
*/
"use strict";
const { ReplaceSource, RawSource, ConcatSource } = require("webpack-sources");
const { UsageState } = require("../ExportsInfo");
const Generator = require("../Generator");
const InitFragment = require("../InitFragment");
const {
JS_AND_CSS_EXPORT_TYPES,
JS_AND_CSS_TYPES,
CSS_TYPES,
JS_TYPE,
CSS_TYPE
} = require("../ModuleSourceTypesConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
const Template = require("../Template");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../../declarations/WebpackOptions").CssAutoGeneratorOptions} CssAutoGeneratorOptions */
/** @typedef {import("../../declarations/WebpackOptions").CssGlobalGeneratorOptions} CssGlobalGeneratorOptions */
/** @typedef {import("../../declarations/WebpackOptions").CssModuleGeneratorOptions} CssModuleGeneratorOptions */
/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
/** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../DependencyTemplate").CssData} CssData */
/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../Generator").GenerateContext} GenerateContext */
/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */
/** @typedef {import("../Module").BuildInfo} BuildInfo */
/** @typedef {import("../Module").BuildMeta} BuildMeta */
/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("../Module").SourceTypes} SourceTypes */
/** @typedef {import("../ModuleGraph")} ModuleGraph */
/** @typedef {import("../NormalModule")} NormalModule */
/** @typedef {import("../util/Hash")} Hash */
class CssGenerator extends Generator {
/**
* @param {CssAutoGeneratorOptions | CssGlobalGeneratorOptions | CssModuleGeneratorOptions} options options
* @param {ModuleGraph} moduleGraph the module graph
*/
constructor(options, moduleGraph) {
super();
this.convention = options.exportsConvention;
this.localIdentName = options.localIdentName;
this.exportsOnly = options.exportsOnly;
this.esModule = options.esModule;
this._moduleGraph = moduleGraph;
}
/**
* @param {NormalModule} module module for which the bailout reason should be determined
* @param {ConcatenationBailoutReasonContext} context context
* @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
*/
getConcatenationBailoutReason(module, context) {
if (!this.esModule) {
return "Module is not an ECMAScript module";
}
return undefined;
}
/**
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
* @returns {Source | null} generated code
*/
generate(module, generateContext) {
const source =
generateContext.type === "javascript"
? new ReplaceSource(new RawSource(""))
: new ReplaceSource(/** @type {Source} */ (module.originalSource()));
/** @type {InitFragment<GenerateContext>[]} */
const initFragments = [];
/** @type {CssData} */
const cssData = {
esModule: /** @type {boolean} */ (this.esModule),
exports: new Map()
};
/** @type {InitFragment<GenerateContext>[] | undefined} */
let chunkInitFragments;
/** @type {DependencyTemplateContext} */
const templateContext = {
runtimeTemplate: generateContext.runtimeTemplate,
dependencyTemplates: generateContext.dependencyTemplates,
moduleGraph: generateContext.moduleGraph,
chunkGraph: generateContext.chunkGraph,
module,
runtime: generateContext.runtime,
runtimeRequirements: generateContext.runtimeRequirements,
concatenationScope: generateContext.concatenationScope,
codeGenerationResults:
/** @type {CodeGenerationResults} */
(generateContext.codeGenerationResults),
initFragments,
cssData,
get chunkInitFragments() {
if (!chunkInitFragments) {
const data =
/** @type {NonNullable<GenerateContext["getData"]>} */
(generateContext.getData)();
chunkInitFragments = data.get("chunkInitFragments");
if (!chunkInitFragments) {
chunkInitFragments = [];
data.set("chunkInitFragments", chunkInitFragments);
}
}
return chunkInitFragments;
}
};
/**
* @param {Dependency} dependency dependency
*/
const handleDependency = dependency => {
const constructor =
/** @type {new (...args: EXPECTED_ANY[]) => Dependency} */
(dependency.constructor);
const template = generateContext.dependencyTemplates.get(constructor);
if (!template) {
throw new Error(
`No template for dependency: ${dependency.constructor.name}`
);
}
template.apply(dependency, source, templateContext);
};
for (const dependency of module.dependencies) {
handleDependency(dependency);
}
switch (generateContext.type) {
case "javascript": {
/** @type {BuildInfo} */
(module.buildInfo).cssData = cssData;
generateContext.runtimeRequirements.add(RuntimeGlobals.module);
if (generateContext.concatenationScope) {
const source = new ConcatSource();
const usedIdentifiers = new Set();
for (const [name, v] of cssData.exports) {
const usedName = generateContext.moduleGraph
.getExportInfo(module, name)
.getUsedName(name, generateContext.runtime);
if (!usedName) {
continue;
}
let identifier = Template.toIdentifier(usedName);
const { RESERVED_IDENTIFIER } = require("../util/propertyName");
if (RESERVED_IDENTIFIER.has(identifier)) {
identifier = `_${identifier}`;
}
const i = 0;
while (usedIdentifiers.has(identifier)) {
identifier = Template.toIdentifier(name + i);
}
usedIdentifiers.add(identifier);
generateContext.concatenationScope.registerExport(name, identifier);
source.add(
`${
generateContext.runtimeTemplate.supportsConst()
? "const"
: "var"
} ${identifier} = ${JSON.stringify(v)};\n`
);
}
return source;
}
if (
cssData.exports.size === 0 &&
!(/** @type {BuildMeta} */ (module.buildMeta).isCSSModule)
) {
return new RawSource("");
}
const needNsObj =
this.esModule &&
generateContext.moduleGraph
.getExportsInfo(module)
.otherExportsInfo.getUsed(generateContext.runtime) !==
UsageState.Unused;
if (needNsObj) {
generateContext.runtimeRequirements.add(
RuntimeGlobals.makeNamespaceObject
);
}
const exports = [];
for (const [name, v] of cssData.exports) {
exports.push(`\t${JSON.stringify(name)}: ${JSON.stringify(v)}`);
}
return new RawSource(
`${needNsObj ? `${RuntimeGlobals.makeNamespaceObject}(` : ""}${
module.moduleArgument
}.exports = {\n${exports.join(",\n")}\n}${needNsObj ? ")" : ""};`
);
}
case "css": {
if (module.presentationalDependencies !== undefined) {
for (const dependency of module.presentationalDependencies) {
handleDependency(dependency);
}
}
generateContext.runtimeRequirements.add(RuntimeGlobals.hasCssModules);
return InitFragment.addToSource(source, initFragments, generateContext);
}
default:
return null;
}
}
/**
* @param {Error} error the error
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
* @returns {Source | null} generated code
*/
generateError(error, module, generateContext) {
switch (generateContext.type) {
case "javascript": {
return new RawSource(
`throw new Error(${JSON.stringify(error.message)});`
);
}
case "css": {
return new RawSource(`/**\n ${error.message} \n**/`);
}
default:
return null;
}
}
/**
* @param {NormalModule} module fresh module
* @returns {SourceTypes} available types (do not mutate)
*/
getTypes(module) {
// TODO, find a better way to prevent the original module from being removed after concatenation, maybe it is a bug
if (this.exportsOnly) {
return JS_AND_CSS_EXPORT_TYPES;
}
const sourceTypes = new Set();
const connections = this._moduleGraph.getIncomingConnections(module);
for (const connection of connections) {
if (!connection.originModule) {
continue;
}
if (connection.originModule.type.split("/")[0] !== CSS_TYPE)
sourceTypes.add(JS_TYPE);
}
if (sourceTypes.has(JS_TYPE)) {
return JS_AND_CSS_TYPES;
}
return CSS_TYPES;
}
/**
* @param {NormalModule} module the module
* @param {string=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type) {
switch (type) {
case "javascript": {
const cssData = /** @type {BuildInfo} */ (module.buildInfo).cssData;
if (!cssData) {
return 42;
}
if (cssData.exports.size === 0) {
if (/** @type {BuildMeta} */ (module.buildMeta).isCSSModule) {
return 42;
}
return 0;
}
const exports = cssData.exports;
const stringifiedExports = JSON.stringify(
Array.from(exports).reduce((obj, [key, value]) => {
obj[key] = value;
return obj;
}, /** @type {Record<string, string>} */ ({}))
);
return stringifiedExports.length + 42;
}
case "css": {
const originalSource = module.originalSource();
if (!originalSource) {
return 0;
}
return originalSource.size();
}
default:
return 0;
}
}
/**
* @param {Hash} hash hash that will be modified
* @param {UpdateHashContext} updateHashContext context for updating hash
*/
updateHash(hash, { module }) {
hash.update(/** @type {boolean} */ (this.esModule).toString());
}
}
module.exports = CssGenerator;