1.3.7 • Published 4 years ago

@decisiv/babel-plugin-styled-components-references v1.3.7

Weekly downloads
8
License
MIT
Repository
-
Last release
4 years ago

babel-plugin-styled-components-references

Overview

The purpose of this Babel plugin is to replace references to styled components inside template strings with a string pattern containing the referenced styled component's name and its path in the filesystem.

Those strings uniquely identify styled components, which is then useful when extracting the components styles into static stylesheets. Since the strings are unique per component, they can be easily replaced by any other string one might want, such as a unique css selector that targets that component.

Extracting styles of a styled component can be done by using the SSR features of styled-components. If we do that for the following code...

import { Icon } from 'some-place';

const MyComponent = styled.div`
  color: green;

  ${Icon} {
    margin-left: 10px;
  }

  ${Icon}::before {
    content: '';
  }
`;

...then we get something like...

.xhh21s2 {
  color: green;
}

.xhh21s2 .kjhkh12 {
  margin-left: 10px;
}

.xhh21s2 .kjhkh12::before {
  content: '';
}

...where the css selector for Icon is unique to that specific reference in the whole codebase. By only reading the generated stylesheet, one cannot know to which component a selector refers to.

By using this babel plugin, the resulting css would be something like:

.xhh21s2 {
  color: green;
}

.xhh21s2 [Icon:path/to/the/component/in/the/filesystem] {
  margin-left: 10px;
}

.xhh21s2 [Icon:path/to/the/component/in/the/filesystem]::before {
  content: '';
}

This then allows us to replace all the references to that component by any selector we want:

.xhh21s2 {
  color: green;
}

.xhh21s2 .icon {
  margin-left: 10px;
}

.xhh21s2 .icon::before {
  content: '';
}

And by SSR rendering each component individually, we can also replace the main selector for that component, which could then result in something like:

.my-component {
  color: green;
}

.my-component .icon {
  margin-left: 10px;
}

.my-component .icon::before {
  content: '';
}