Using CSS-in-JS with Preact

Emma Goto 🍙 - Aug 16 '20 - - Dev Community

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',
        },
    },
};
Enter fullscreen mode Exit fullscreen mode

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;
      },
};
Enter fullscreen mode Exit fullscreen mode

After this you can install your preferred package:

npm i @emotion/styled
# OR
npm i styled-components
Enter fullscreen mode Exit fullscreen mode

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;
`;
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player