webpack/lib/css/CssGenerator.js

326 lines
9.8 KiB
JavaScript
Raw Normal View History

2021-11-30 19:55:51 +08:00
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Sergey Melyukov @smelukov
*/
"use strict";
2025-07-03 17:06:45 +08:00
const { ConcatSource, RawSource, ReplaceSource } = require("webpack-sources");
2024-11-15 00:14:15 +08:00
const { UsageState } = require("../ExportsInfo");
2021-11-30 19:55:51 +08:00
const Generator = require("../Generator");
2021-11-30 20:46:42 +08:00
const InitFragment = require("../InitFragment");
2024-11-20 09:31:41 +08:00
const {
2025-07-03 17:06:45 +08:00
CSS_TYPE,
CSS_TYPES,
2024-11-20 09:31:41 +08:00
JS_AND_CSS_EXPORT_TYPES,
JS_AND_CSS_TYPES,
2025-07-03 17:06:45 +08:00
JS_TYPE
2024-11-20 09:31:41 +08:00
} = require("../ModuleSourceTypesConstants");
const RuntimeGlobals = require("../RuntimeGlobals");
2024-11-15 00:14:15 +08:00
const Template = require("../Template");
const memoize = require("../util/memoize");
2021-11-30 19:55:51 +08:00
/** @typedef {import("webpack-sources").Source} Source */
2024-11-15 00:14:15 +08:00
/** @typedef {import("../../declarations/WebpackOptions").CssAutoGeneratorOptions} CssAutoGeneratorOptions */
/** @typedef {import("../../declarations/WebpackOptions").CssGlobalGeneratorOptions} CssGlobalGeneratorOptions */
/** @typedef {import("../../declarations/WebpackOptions").CssModuleGeneratorOptions} CssModuleGeneratorOptions */
2025-09-02 22:12:40 +08:00
/** @typedef {import("../Compilation").DependencyConstructor} DependencyConstructor */
2024-10-01 03:05:27 +08:00
/** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
2021-11-30 20:46:42 +08:00
/** @typedef {import("../Dependency")} Dependency */
2024-11-29 04:35:59 +08:00
/** @typedef {import("../DependencyTemplate").CssData} CssData */
/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */
2021-11-30 19:55:51 +08:00
/** @typedef {import("../Generator").GenerateContext} GenerateContext */
/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */
2025-03-07 21:12:22 +08:00
/** @typedef {import("../Module").BuildInfo} BuildInfo */
/** @typedef {import("../Module").BuildMeta} BuildMeta */
2024-11-15 00:14:15 +08:00
/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
2024-11-01 04:19:07 +08:00
/** @typedef {import("../Module").SourceTypes} SourceTypes */
/** @typedef {import("../ModuleGraph")} ModuleGraph */
2021-11-30 19:55:51 +08:00
/** @typedef {import("../NormalModule")} NormalModule */
/** @typedef {import("../util/Hash")} Hash */
const getPropertyName = memoize(() => require("../util/propertyName"));
2021-11-30 19:55:51 +08:00
class CssGenerator extends Generator {
2024-02-21 16:00:24 +08:00
/**
2024-11-15 00:14:15 +08:00
* @param {CssAutoGeneratorOptions | CssGlobalGeneratorOptions | CssModuleGeneratorOptions} options options
* @param {ModuleGraph} moduleGraph the module graph
2024-02-21 16:00:24 +08:00
*/
constructor(options, moduleGraph) {
2021-11-30 19:55:51 +08:00
super();
2024-11-15 00:14:15 +08:00
this.convention = options.exportsConvention;
this.localIdentName = options.localIdentName;
this.exportsOnly = options.exportsOnly;
this.esModule = options.esModule;
this._moduleGraph = moduleGraph;
2024-11-15 00:14:15 +08:00
}
/**
* @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";
}
2024-11-15 23:59:14 +08:00
2024-11-15 00:14:15 +08:00
return undefined;
2021-11-30 19:55:51 +08:00
}
/**
* @param {NormalModule} module module for which the code should be generated
* @param {GenerateContext} generateContext context for generate
2024-10-24 04:30:31 +08:00
* @returns {Source | null} generated code
2021-11-30 19:55:51 +08:00
*/
2021-11-30 20:46:42 +08:00
generate(module, generateContext) {
2024-11-15 00:14:15 +08:00
const source =
generateContext.type === "javascript"
? new ReplaceSource(new RawSource(""))
: new ReplaceSource(/** @type {Source} */ (module.originalSource()));
2024-10-01 03:05:27 +08:00
/** @type {InitFragment<GenerateContext>[]} */
2021-11-30 20:46:42 +08:00
const initFragments = [];
2024-11-29 04:35:59 +08:00
/** @type {CssData} */
const cssData = {
2025-03-08 00:02:26 +08:00
esModule: /** @type {boolean} */ (this.esModule),
exports: new Map()
};
2021-11-30 20:46:42 +08:00
2024-10-01 03:05:27 +08:00
/** @type {InitFragment<GenerateContext>[] | undefined} */
let chunkInitFragments;
/** @type {DependencyTemplateContext} */
2021-12-14 23:02:26 +08:00
const templateContext = {
runtimeTemplate: generateContext.runtimeTemplate,
dependencyTemplates: generateContext.dependencyTemplates,
moduleGraph: generateContext.moduleGraph,
chunkGraph: generateContext.chunkGraph,
module,
runtime: generateContext.runtime,
runtimeRequirements: generateContext.runtimeRequirements,
concatenationScope: generateContext.concatenationScope,
2024-10-01 03:05:27 +08:00
codeGenerationResults:
/** @type {CodeGenerationResults} */
(generateContext.codeGenerationResults),
2021-12-14 23:02:26 +08:00
initFragments,
2024-11-29 04:35:59 +08:00
cssData,
get chunkInitFragments() {
if (!chunkInitFragments) {
2024-10-01 03:05:27 +08:00
const data =
/** @type {NonNullable<GenerateContext["getData"]>} */
(generateContext.getData)();
chunkInitFragments = data.get("chunkInitFragments");
if (!chunkInitFragments) {
chunkInitFragments = [];
data.set("chunkInitFragments", chunkInitFragments);
}
}
return chunkInitFragments;
}
2021-12-14 23:02:26 +08:00
};
2023-04-29 02:50:41 +08:00
/**
* @param {Dependency} dependency dependency
*/
const handleDependency = (dependency) => {
2024-10-25 02:13:59 +08:00
const constructor =
2025-09-02 22:12:40 +08:00
/** @type {DependencyConstructor} */
2024-10-25 02:13:59 +08:00
(dependency.constructor);
2021-11-30 20:46:42 +08:00
const template = generateContext.dependencyTemplates.get(constructor);
if (!template) {
throw new Error(
2024-07-31 10:39:30 +08:00
`No template for dependency: ${dependency.constructor.name}`
2021-11-30 20:46:42 +08:00
);
}
template.apply(dependency, source, templateContext);
2021-12-14 23:02:26 +08:00
};
2024-11-15 00:14:15 +08:00
2024-08-02 02:36:27 +08:00
for (const dependency of module.dependencies) {
handleDependency(dependency);
}
2024-11-15 00:14:15 +08:00
switch (generateContext.type) {
case "javascript": {
2025-03-07 21:12:22 +08:00
/** @type {BuildInfo} */
(module.buildInfo).cssData = cssData;
2024-11-29 04:35:59 +08:00
2024-11-15 00:14:15 +08:00
generateContext.runtimeRequirements.add(RuntimeGlobals.module);
if (generateContext.concatenationScope) {
const source = new ConcatSource();
const usedIdentifiers = new Set();
const { RESERVED_IDENTIFIER } = getPropertyName();
2024-11-29 04:35:59 +08:00
for (const [name, v] of cssData.exports) {
2024-11-20 09:31:41 +08:00
const usedName = generateContext.moduleGraph
.getExportInfo(module, name)
.getUsedName(name, generateContext.runtime);
if (!usedName) {
continue;
}
let identifier = Template.toIdentifier(usedName);
2024-11-15 23:59:14 +08:00
if (RESERVED_IDENTIFIER.has(identifier)) {
identifier = `_${identifier}`;
}
2024-11-15 00:14:15 +08:00
const i = 0;
while (usedIdentifiers.has(identifier)) {
identifier = Template.toIdentifier(name + i);
}
usedIdentifiers.add(identifier);
generateContext.concatenationScope.registerExport(name, identifier);
source.add(
`${generateContext.runtimeTemplate.renderConst()} ${identifier} = ${JSON.stringify(v)};\n`
2024-11-15 00:14:15 +08:00
);
}
return source;
}
if (
cssData.exports.size === 0 &&
!(/** @type {BuildMeta} */ (module.buildMeta).isCSSModule)
) {
return new RawSource("");
}
2024-11-15 00:14:15 +08:00
const needNsObj =
this.esModule &&
generateContext.moduleGraph
.getExportsInfo(module)
.otherExportsInfo.getUsed(generateContext.runtime) !==
UsageState.Unused;
if (needNsObj) {
generateContext.runtimeRequirements.add(
RuntimeGlobals.makeNamespaceObject
);
}
const exports = [];
2024-11-29 04:35:59 +08:00
for (const [name, v] of cssData.exports) {
2024-11-15 00:14:15 +08:00
exports.push(`\t${JSON.stringify(name)}: ${JSON.stringify(v)}`);
}
return new RawSource(
`${needNsObj ? `${RuntimeGlobals.makeNamespaceObject}(` : ""}${
module.moduleArgument
}.exports = {\n${exports.join(",\n")}\n}${needNsObj ? ")" : ""};`
);
2024-08-02 02:36:27 +08:00
}
2024-11-15 00:14:15 +08:00
case "css": {
if (module.presentationalDependencies !== undefined) {
for (const dependency of module.presentationalDependencies) {
handleDependency(dependency);
}
}
generateContext.runtimeRequirements.add(RuntimeGlobals.hasCssModules);
2021-12-14 23:02:26 +08:00
2024-11-15 00:14:15 +08:00
return InitFragment.addToSource(source, initFragments, generateContext);
}
2025-03-07 21:12:22 +08:00
default:
return null;
2024-11-15 00:14:15 +08:00
}
2021-11-30 19:55:51 +08:00
}
/**
* @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;
}
}
2021-11-30 19:55:51 +08:00
/**
* @param {NormalModule} module fresh module
2024-11-01 04:19:07 +08:00
* @returns {SourceTypes} available types (do not mutate)
2021-11-30 19:55:51 +08:00
*/
getTypes(module) {
2024-11-20 09:31:41 +08:00
// 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;
2021-11-30 19:55:51 +08:00
}
/**
* @param {NormalModule} module the module
* @param {string=} type source type
* @returns {number} estimate size of the module
*/
getSize(module, type) {
2024-11-15 00:14:15 +08:00
switch (type) {
case "javascript": {
const cssData = /** @type {BuildInfo} */ (module.buildInfo).cssData;
if (!cssData) {
2024-11-29 04:45:02 +08:00
return 42;
}
if (cssData.exports.size === 0) {
if (/** @type {BuildMeta} */ (module.buildMeta).isCSSModule) {
return 42;
}
return 0;
}
const exports = cssData.exports;
2024-11-29 04:35:59 +08:00
const stringifiedExports = JSON.stringify(
2025-07-03 17:06:45 +08:00
[...exports].reduce((obj, [key, value]) => {
2024-11-29 04:35:59 +08:00
obj[key] = value;
return obj;
2025-04-23 10:06:20 +08:00
}, /** @type {Record<string, string>} */ ({}))
2024-11-29 04:35:59 +08:00
);
return stringifiedExports.length + 42;
2024-11-15 00:14:15 +08:00
}
case "css": {
const originalSource = module.originalSource();
2021-11-30 19:55:51 +08:00
2024-11-15 00:14:15 +08:00
if (!originalSource) {
return 0;
}
2021-11-30 19:55:51 +08:00
2024-11-15 00:14:15 +08:00
return originalSource.size();
}
2025-03-07 21:12:22 +08:00
default:
return 0;
2024-11-15 00:14:15 +08:00
}
2021-11-30 19:55:51 +08:00
}
/**
* @param {Hash} hash hash that will be modified
* @param {UpdateHashContext} updateHashContext context for updating hash
*/
updateHash(hash, { module }) {
2025-03-08 00:02:26 +08:00
hash.update(/** @type {boolean} */ (this.esModule).toString());
}
2021-11-30 19:55:51 +08:00
}
module.exports = CssGenerator;