Unlocking the Power of Zero-Runtime CSS-in-JS with Linaria
What is Linaria?
<p)linaria is=”” a=”” build-time=”” css-in-js=”” library=”” that=”” allows=”” us=”” to=”” write=”” css=”” inside=”” javascript=”” like=”” runtime=”” libraries.=”” however,=”” instead=”” of=”” bundling=”” the=”” with=”” js,=”” which=”” increases=”” bundle=”” size,=”” linaria=”” extracts=”” styles=”” into=”” static=”” file=”” at=”” build=”” time,=”” eliminating=”” extra=”” workload=”” in=”” runtime.<=”” p=””>
Setting Up Linaria Without Create React App
To set up Linaria in a fresh React project, we need to customize a bundler like Webpack. We can then include a Webpack loader to extract CSS from JS at build time.
- Install the Linaria library and its dependencies:
npm install @linaria/core @linaria/react
- Configure Webpack to use the Linaria loader. Create a
webpack.config.js
file in the project root and add the following code:module.exports = { // ... other configurations ... module: { rules: [ { test: /\.js$/, use: ['babel-loader', '@linaria/webpack-loader'], exclude: /node_modules/, }, ], }, };
Using Linaria in a Fresh React Project
Now that we have set up Linaria, let’s create a simple React component and use Linaria to style it:
import React from 'react';
import { css } from '@linaria/core';
const Button = () => {
return (
);
};
export default Button;
Setting Up Linaria with Create React App
If you’re using Create React App, you need to modify the Webpack configuration. Since the default setup doesn’t expose the Webpack configuration, we need to use external libraries like customize-cra
and react-app-rewired
.
- Install the required libraries:
npm install customize-cra react-app-rewired
- Create a
config-overrides.js
file in the project root and add the following code:const { override, useBabelRc } = require('customize-cra'); module.exports = override( useBabelRc(), (config) => { config.module.rules.push({ test: /\.js$/, use: ['babel-loader', '@linaria/webpack-loader'], exclude: /node_modules/, }); return config; } );
</p)linaria>