Skip to content

Commit 2f91e23

Browse files
committed
feat: improve rem inlining to simplify calc()
1 parent 95e11b9 commit 2f91e23

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

src/__tests__/compiler/compiler.test.tsx

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -381,3 +381,27 @@ test("warnings", () => {
381381
},
382382
});
383383
});
384+
385+
test("simplifies rem", () => {
386+
const compiled = compile(`.test {
387+
border-width: calc(10rem + 2px);
388+
}`);
389+
390+
expect(compiled.stylesheet()).toStrictEqual({
391+
s: [
392+
[
393+
"test",
394+
[
395+
{
396+
d: [
397+
{
398+
borderWidth: 142,
399+
},
400+
],
401+
s: [1, 1],
402+
},
403+
],
404+
],
405+
],
406+
});
407+
});

src/compiler/compiler.ts

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ const defaultLogger = debug("react-native-css:compiler");
3333
*/
3434
export function compile(code: Buffer | string, options: CompilerOptions = {}) {
3535
const { logger = defaultLogger } = options;
36+
3637
const isLoggerEnabled =
3738
"enabled" in logger ? logger.enabled : Boolean(logger);
3839

@@ -103,9 +104,32 @@ export function compile(code: Buffer | string, options: CompilerOptions = {}) {
103104
};
104105
}
105106

106-
// Use the lightningcss library to traverse the CSS AST and extract style declarations and animations
107-
lightningcss({
107+
/**
108+
* Use the lightningcss library to traverse the CSS AST and extract style declarations and animations
109+
*
110+
* We pass the CSS twice, the first time to inline variables and then the second so lightningcss can optimize
111+
* the changes we did
112+
*/
113+
const { code: firstPass } = lightningcss({
108114
code: typeof code === "string" ? new TextEncoder().encode(code) : code,
115+
visitor: {
116+
Length(length) {
117+
if (length.unit !== "rem" || options.inlineRem === false) {
118+
return length;
119+
}
120+
121+
return {
122+
unit: "px",
123+
value: length.value * (options.inlineRem ?? 14),
124+
};
125+
},
126+
},
127+
filename: options.filename ?? "style.css",
128+
projectRoot: options.projectRoot ?? process.cwd(),
129+
});
130+
131+
lightningcss({
132+
code: firstPass,
109133
visitor,
110134
filename: options.filename ?? "style.css",
111135
projectRoot: options.projectRoot ?? process.cwd(),

0 commit comments

Comments
 (0)