linaria icon indicating copy to clipboard operation
linaria copied to clipboard

feat: add style tag injection

Open mprobber opened this issue 4 years ago • 5 comments

Motivation

When using React in a variety of environments (client-side rendered, server-side rendered, React Native), your build tooling is going to vary from platform to platform. Often times it can be a heavy lift to introduce new rules, plugins, and loaders, as well as keep their options consistent between platforms. Allowing Linaria to inject some logic to add a style tag to the page during the babel transform allows us to check for the existence of the document object, and if it exists, add it to the page. This lets you use libraries that rely on Linaria without setting up any bespoke build tooling, and styles the page if possible.

Summary

I refactored transform.ts to split out any of the preprocessing logic, so it could be shared between it and the babel plugin. (preprocess.ts)

I added an additional option to the linaria configuration, injectStyleTags, that defaults to false.

When injectStyleTags is true, the babel plugin constructs an AST for code to inject the CSS into the head of the DOM, appends that code to the end of the transformed file, so on module initialization, the file adds its' styles to the DOM.

Test plan

All existing unit tests pass (I moved the tests for transformUrl from transform.ts to preprocess.test.ts, that function is now in preprocess.test.ts).

In addition, a new snapshot test was added in babel.test.ts, to make sure that injecting the style works as expected.

mprobber avatar Aug 19 '20 01:08 mprobber

Hey @mprobber, thank you for your pull request 🤗. The coverage report for this branch can be viewed here.

callstack-bot avatar Aug 19 '20 01:08 callstack-bot

Hi @mprobber! It's an interesting proposal. @jayu what do you think?

Anber avatar Sep 03 '20 10:09 Anber

@Anber @jayu any updates on this? It would help reduce a bunch of complexity in a build system I'm working on.

mprobber avatar Sep 10 '20 18:09 mprobber

@Anber @jayu bump? 😄

mprobber avatar Sep 23 '20 17:09 mprobber

Hi @mprobber First of all, sorry for the late reply. If the core team doesn't have any objections, I would like to include it in the next (after 2.0) release.

Anber avatar Oct 26 '20 08:10 Anber