MCPcopy Create free account
hub / github.com/FredKSchott/snowpack / transformCSSProxy

Function transformCSSProxy

plugins/plugin-optimize/lib/css.js:27–79  ·  view source on GitHub ↗

* Scans JS for CSS imports, and embeds only what’s needed * * import 'global.css' -> (removed; loaded in HTML) * import url from 'global.css' -> const url = 'global.css' * import {foo, bar} from 'local.module.css' -> const {foo, bar} = 'local.module.css'

(file, originalCode)

Source from the content-addressed store, hash-verified

25 * import {foo, bar} from 'local.module.css' -> const {foo, bar} = 'local.module.css'
26 */
27function transformCSSProxy(file, originalCode) {
28 const filePath = path.dirname(file);
29 let code = originalCode;
30
31 const getProxyImports = (code) =>
32 parse(code)[0]
33 .filter(({d}) => d === -1) // discard dynamic imports (> -1) and import.meta (-2)
34 .filter(({s, e}) => code.substring(s, e).endsWith('.css.proxy.js')); // only accept .css.proxy.js files
35
36 // iterate through proxy imports
37 let proxyImports = getProxyImports(code);
38 while (proxyImports.length) {
39 const {s, e, ss, se} = proxyImports[0]; // only transform one at a time, because every transformation requires re-parsing (unless you created an ellaborate mechanism to keep track of character counts but IMO parsing is simpler/cheaper)
40
41 const originalImport = code.substring(s, e);
42 const importedFile = originalImport.replace(/\.proxy\.js$/, '');
43 const importNamed = code
44 .substring(ss, se)
45 .replace(code.substring(s - 1, e + 1), '') // remove import
46 .replace(/^import\s+/, '') // remove keyword
47 .replace(/\s*from.*$/, '') // remove other keyword
48 .replace(/\*\s+as\s+/, '') // sanitize star imports
49 .trim();
50
51 // transform JS
52 if (!importNamed) {
53 // option 1: no transforms needed
54 code = code.replace(new RegExp(`${code.substring(ss, se)};?\n?`), '');
55 } else {
56 if (importedFile.endsWith('.module.css')) {
57 // option 2: transform css modules
58 const proxyCode = fs.readFileSync(path.resolve(filePath, originalImport), 'utf-8');
59 const matches = proxyCode.match(/^let json\s*=\s*(\{[^\}]+\})/m);
60 if (matches) {
61 code = code.replace(
62 new RegExp(`${code.substring(ss, se).replace(/\*/g, '\\*')};?`),
63 `const ${importNamed.replace(/\*\s+as\s+/, '')} = ${matches[1]};`,
64 );
65 }
66 } else {
67 // option 3: transfrom normal css
68 code = code.replace(
69 new RegExp(`${code.substring(ss, se)};?`),
70 `const ${importNamed} = '${importedFile}';`,
71 );
72 }
73 }
74
75 proxyImports = getProxyImports(code); // re-parse code, continuing until all are transformed
76 }
77
78 return code;
79}
80exports.transformCSSProxy = transformCSSProxy;
81
82/** Build CSS File */

Callers 1

optimizeFileFunction · 0.85

Calls 1

getProxyImportsFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…