Using CSS-in-JS with Preact

16 August 2020
·
preact

The two most popular CSS-in-JS libraries, styled-components and Emotion, don’t support Preact out of the box. However there is an easy workaround.

Add these aliases to your webpack.config.js file:

module.exports = {
    resolve: {
        alias: {
            react: 'preact/compat',
            'react-dom/test-utils': 'preact/test-utils',
            'react-dom': 'preact/compat',
        },
    },
};

Adding these aliases allows you to use other libraries intended for React too!

And if you’re using Storybook, you’ll need to add the same alias to your .storybook/main.js file:

module.exports = {
	stories: ['../app/javascript/**/story.tsx'],
	webpackFinal: async config => {
		config.resolve.alias = Object.assign({}, config.resolve.alias, {
			react: "preact/compat",
			'react-dom': 'preact/compat'
		})
	    return config;
	  },
};

After this you can install your preferred package:

npm i @emotion/styled
# OR
npm i styled-components

And use either styled-components or Emotion without any problems:

import styled from '@emotion/styled'; 
// OR
import styled from 'styled-components';
 
export const Container = styled.div`
  background-color: pink;
`;

Recent posts

Comments