Skip to content

WIP: Remove unused variables#58

Closed
devongovett wants to merge 1 commit intomasterfrom
unused-vars
Closed

WIP: Remove unused variables#58
devongovett wants to merge 1 commit intomasterfrom
unused-vars

Conversation

@devongovett
Copy link
Member

@devongovett devongovett commented Jan 15, 2022

This is a draft to get feedback. Please let me know what you think in the comments.

I'm not sure if this is a good idea, but I would like a way to remove CSS variables that aren't referenced. For example, in a design system you might have a ton of variables and only use a subset of them in a particular file. For example:

.foo {
  --used: blue;
  --unused: red;
}

.bar {
  color: var(--used);
}

becomes:

.foo{--used:blue}.bar{color:var(--used)}

This is very unsafe, so would need to be opt-in. Variable names are global so could be referenced from another CSS file, or from JavaScript. Also code splitting might break it if the variables were defined in a different bundle from where they are used. So this would basically only work if you are building a library and guarantee that only a single CSS file will be output, on which you can run this optimization pass.

Alternatives

I am hoping there is a better way. One idea I had was to make variables kinda like CSS modules. The names would get hashed, and if you wanted to reference a variable from a different file, you'd need to do so explicitly.

vars.css:

.theme {
  --color: blue;
  --font: Helvetica;
}

component.css:

.button {
  color: var(--color from "vars.css");
}

compiled output:

.theme {
  --color_a8fd: blue;
}

.button {
  color: var(--color_a8fd);
}

Unfortunately, that syntax gets pretty annoying pretty fast if you have a lot of variables. If anyone has any ideas, let me know!

@parcel-bundler parcel-bundler deleted a comment from height bot Jan 15, 2022
@nicksrandall
Copy link
Contributor

FWIW, I think this is a good idea and I have an immediate use case for this. I would love to see this land with opt-in support.

@devongovett
Copy link
Member Author

Main issue is that it breaks any kind of code splitting. If a var is used in a different file, or code splitting occurs, it will see the variable as unused and remove it. Haven't figured out what to do about this yet.

@ghost
Copy link

ghost commented Apr 11, 2023

Would it be possible to have a version of this for transform specifically where an HTML document is provided alongside the CSS essentially implying "if the selector isn't used in this document, then it isn't used at all"? My CSS is generated per-page so this would be really powerful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants