If you are using styled components, then you may also consider using babel-plugin-styled-components.
This is a plugin for babel, which provides a few useful configurations, such as:
ssr
: for server side rendering supportdisplayName
: show component name for in class namestranspileTemplateLiterals
: transpile tagged template literals
The usage is pretty simple, we just add it into babel config file:
{
"plugins": ["babel-plugin-styled-components"]
}
But what if we are using vite instead of webpack? How we config it then? The answer is that it depends.
In Vite, we have 2 options for react: @vitejs/plugin-react
or @vitejs/plugin-react-swc
.
@vitejs/plugin-react
is using esbuild and babel under the hood, so we can use babel-plugin-styled-components
directly as well:
// vite.config.js
export default defineConfig({
plugins: [
react({
babel: {
plugins: [
[
'babel-plugin-styled-components',
{
displayName: true,
fileName: false
}
]
]
}
})
]
})
But @vitejs/plugin-react-swc
replaces babel with swc, so we cannot use babel-plugin-styled-components
any more. Luckily, swc provides its own plugin for styled components. So in this case, we can set config as:
react({ plugins: [["@swc/plugin-styled-components", {}]] });
Last thing needs to be noted is that this swc plugin seems not complete yet. Some options may not working, the doc seems vague. I tried locally, at least displayName
is working correctly.