kentcdodds / kentcdodds/tree-shake-css

leverage webpack

Open
#2 16 comments 1 reaction 0 assignees View on GitHub
Dominant language
JavaScript
Stars
36
Forks
0
PR merge metrics
No merged PRs in 30d

Description

> I know why this is happening. I'm not asking for an explanation. I'm just trying to come up with the best way (from the user of the lib module) to only include the css for the exports that are being used.

Just to be sure we agree on the explanation: adding css to the dom is a side-effect and therefore even if you only use code from `a` or `b` it will still include both.

Given that you can't "just" assume that it is ok to tree shake the css. This is only ok if you consider the css to be local to the e.g. components you use. I.e. if you have something like

```css
h1 { /* global changes */ }
```
then shaking this is most likely considered harmful.

Otherwise webpack should already drop the css if this is indeed a library. Try adding `side-effects: false` to this package.json and `import {a} from 'this-lib'`. It should drop `b.css`. See https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free. If this is not a library you could move `a` and `b` to a separate folder with their own package.json and side-effects: false. This is a bit more verbose but less black-magic than writing a babel plugin that strips css and isn't explicit about it.

Contributor guide

No contributing guide indexed for this repository

Research direction

No files, tests, or entry points are named. Start by reviewing the issue discussion and webpack's sideEffects and tree-shaking behavior, then define whether the requested outcome is to exclude unused component CSS while preserving global CSS; completion criteria are not specified.

Written by the indexing model from the issue text.

Assessment

Tech stack
webpack
Domain
build-system
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.