Repository navigation
Expand file tree
/
Copy pathcss-minify-loader.cjs
More file actions
125 lines (115 loc) · 5.33 KB
/
Copy pathcss-minify-loader.cjs
File metadata and controls
125 lines (115 loc) · 5.33 KB
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
/**
* ============================================================================
* Litefin - Inline CSS Minification Loader
* ============================================================================
* Minifies raw stylesheet text BEFORE css-loader packages it into a
* style-loader singleton string. This is required for TV build tiers that
* inline all CSS into the JS bundle (legacy / ultra-legacy via style-loader):
* Terser cannot shrink an injected CSS string, so without this loader the raw
* stylesheet text (comments, whitespace, and the full variant stacks in
* modern/*.css) ships verbatim inside js/main.js.
*
* Also flattens @import chain: css-loader does not re-run the user rule for
* @imported stylesheets (it resolves them with its own bare request), so a
* loader that only processes the entry module would miss the imported files.
* Instead this loader recursively inlines every relative @import into one
* flat stylesheet, then minifies. After this step no @import remains, so
* css-loader sees a single stylesheet and no child modules are emitted.
*
* Runs the same cssnano 'default' pipeline as CssMinimizerPlugin so inline
* and extracted outputs remain consistent. Custom properties (:root vars)
* and var() fallbacks are preserved - the runtime CSS variable transformer
* (_extractThemeVariables) relies on them.
* ============================================================================
*/
const fs = require('fs');
const path = require('path');
const postcss = require('postcss');
const cssnano = require('cssnano');
/**
* Safe cssnano preset configuration for legacy Smart TV rendering engines.
* Discards all comments and collapses extraneous whitespace while explicitly
* disabling destructive transformations that corrupt backward compatibility
* on Chromium 26-38, legacy WebKit, and TV WebViews (Tizen 2.3-3.0, webOS 1.0-3.5).
*/
const safeCssnanoPreset = [
'default',
{
// Strip comments completely to optimize bundle weight
discardComments: { removeAll: true },
// Normalize whitespace for high-density delivery
normalizeWhitespace: true,
// Disable selector merging: if any selector fails parsing, older engines drop the entire block
mergeRules: false,
// Preserve duplicate property declarations used as progressive enhancements or vendor fallbacks
discardOverridden: false,
// Preserve intentional fallback duplicate declarations
discardDuplicates: false,
// Disable calc optimization: prevents operator whitespace stripping that breaks older WebKit layout
calc: false,
// Prevent color rewriting: preserves rgba channels in gradients and regex compatibility
colormin: false,
// Keep quotes intact on attribute selectors for older CSS parsers
minifySelectors: false,
// Do not combine individual directional properties into shorthands
mergeLonghand: false,
// Do not replace initial keyword with default browser values
reduceInitial: false,
// Preserve explicit z-index values to avoid layering collisions in modals and overlays
zindex: false
}
];
/** @type {import('postcss').Plugin} */
function cssnanoPlugin() {
const cssnanoFactory = cssnano.default || cssnano;
return cssnanoFactory({ preset: safeCssnanoPreset });
}
const IMPORT_RE = /@import\s+(?:url\(\s*)?['"]([^'"]+)['"]\s*(?:\)\s*)?[^;]*;/g;
/**
* Recursively inline relative @import statements into the source text.
* Sub-imports are resolved relative to the file that declares them.
* Cycle-safe via a visited set; absolute/url imports are left untouched
* (css-loader still handles those, and bundles.css only uses relative ones).
*
* @param {string} cssText - CSS source text
* @param {string} currentDir - Directory of the file declaring the imports
* @param {Set<string>} visited - Already inlined files (cycle protection)
* @returns {string}
*/
function inlineImports(cssText, currentDir, visited) {
return cssText.replace(IMPORT_RE, (statement, request) => {
// Leave the statement intact for css-loader if not a relative import
if (!request.startsWith('.')) {
return statement;
}
const resolved = path.resolve(currentDir, request);
if (visited.has(resolved)) {
return ''; // cycle guard: skip second occurrence
}
visited.add(resolved);
const nested = fs.readFileSync(resolved, 'utf8');
return inlineImports(nested, path.dirname(resolved), visited);
});
}
module.exports = function cssMinifyLoader(source) {
const callback = this.async();
try {
const flattened = inlineImports(source, path.dirname(this.resourcePath), new Set([this.resourcePath]));
postcss([cssnanoPlugin()])
.process(flattened, {
from: this.resourcePath,
map: false
})
.then((result) => {
if (result.warnings && result.warnings.length) {
for (const w of result.warnings) {
this.emitWarning(new Error('css-minify-loader: ' + w.text));
}
}
callback(null, result.css);
})
.catch((err) => callback(new Error('css-minify-loader: ' + err.message)));
} catch (err) {
callback(err);
}
};