-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathpostcss-css-to-esm.mjs
More file actions
65 lines (53 loc) · 2.05 KB
/
Copy pathpostcss-css-to-esm.mjs
File metadata and controls
65 lines (53 loc) · 2.05 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
import fs from 'node:fs';
import path from 'node:path';
const getTSContent = (targetFile, packageName, css, exportTokens) => {
// tabs are intentionally mixed to have proper identation in the produced file
return `export const styleData = \`${css}\`;
export const classNames = ${JSON.stringify(exportTokens)} as const;
export { styleData as content };
`;
};
// strips the unnecessary theming data coming from @sap-theming/theming-base-content and leaves only the css parameters
// & scope variables
const proccessCSS = (css) => {
css = css.replace(/\.sapThemeMeta[\s\S]*?:root/, ':root');
css = css.replace(/\.background-image.*{.*}/, '');
css = css.replace(/\.sapContrast[ ]*:root[\s\S]*?}/, '');
css = css.replace(/--sapFontUrl.*\);?/, '');
return css;
};
function cssToEsmPostcssPlugin(opts) {
opts = opts || {};
const packageName = opts.packageName;
const toReplace = opts.toReplace;
return {
postcssPlugin: 'postcss-css-to-esm',
OnceExit(root, { result }) {
const css = proccessCSS(root.toString());
const { exportTokens } = result.messages.find(
(message) => message.type === 'export' && message.plugin === 'postcss-modules',
);
const targetFile = root.source.input.from
.replace(`/${toReplace}/`, '/src/')
.replace(`\\${toReplace}\\`, '\\src\\');
fs.mkdirSync(path.dirname(targetFile), { recursive: true });
const filePath = `${targetFile}.ts`;
// it seems slower to read the old content, but writing the same content with no real changes
// (as in initial build and then watch mode) will cause an unnecessary dev server refresh
let oldContent = '';
try {
oldContent = fs.readFileSync(filePath, 'utf8');
} catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
}
const content = getTSContent(targetFile, packageName, css, exportTokens);
if (content !== oldContent) {
fs.writeFileSync(filePath, content);
}
},
};
}
cssToEsmPostcssPlugin.postcss = true;
export default cssToEsmPostcssPlugin;