### Full webpack configuration example with Linaria
Source: https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md
A comprehensive webpack configuration file demonstrating Linaria integration, including CSS extraction, development server setup, and Babel integration.
```javascript
const webpack = require('webpack');
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const dev = process.env.NODE_ENV !== 'production';
module.exports = {
mode: dev ? 'development' : 'production',
devtool: 'source-map',
entry: {
app: './src/index',
},
output: {
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist/',
filename: '[name].bundle.js',
},
optimization: {
noEmitOnErrors: true,
},
plugins: [
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV) },
}),
new MiniCssExtractPlugin({ filename: 'styles.css' }),
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{ loader: 'babel-loader' },
{
loader: '@wyw-in-js/webpack-loader',
options: { sourceMap: dev },
},
],
},
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
options: { sourceMap: dev },
},
],
},
{
test: /\.(jpg|png|gif|woff|woff2|eot|ttf|svg)$/,
use: [{ loader: 'file-loader' }],
},
],
},
devServer: {
contentBase: [path.join(__dirname, 'public')],
historyApiFallback: true,
},
};
```
--------------------------------
### Install Stylelint v13 and Linaria
Source: https://github.com/callstack/linaria/blob/master/docs/LINTING.md
Install stylelint and the necessary Linaria package for stylelint v13.
```bash
yarn add --dev stylelint stylelint-config-recommended @linaria/stylelint
```
--------------------------------
### Install Stylelint v14 and Linaria
Source: https://github.com/callstack/linaria/blob/master/docs/LINTING.md
Install stylelint and the Linaria standard config for stylelint v14.
```bash
yarn add --dev stylelint @linaria/stylelint-config-standard-linaria
```
--------------------------------
### Install Linaria and Babel Preset
Source: https://context7.com/callstack/linaria/llms.txt
Install the necessary Linaria core and React packages along with the Babel preset for build-time processing.
```sh
npm install @linaria/core @linaria/react @wyw-in-js/babel-preset
```
--------------------------------
### Install @linaria/babel-plugin-interop
Source: https://github.com/callstack/linaria/blob/master/packages/interop/README.md
Install the plugin as a development dependency using npm.
```bash
npm install --save-dev @linaria/babel-plugin-interop
```
--------------------------------
### Install Rollup Plugins for Linaria
Source: https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md
Install the necessary Linaria and CSS handling plugins for Rollup.
```sh
yarn add --dev rollup-plugin-css-only @wyw-in-js/rollup
```
--------------------------------
### Install Linaria Core Packages (yarn)
Source: https://github.com/callstack/linaria/blob/master/packages/core/README.md
Use this command to install the necessary Linaria packages using yarn.
```sh
yarn add @linaria/core @linaria/react @linaria/babel-preset
```
--------------------------------
### Stylelint setup for Linaria CSS-in-JS
Source: https://context7.com/callstack/linaria/llms.txt
Install the Linaria stylelint config for Stylelint 14+ to lint your CSS-in-JS files. Ensure your .stylelintrc file extends the standard Linaria configuration.
```bash
yarn add --dev stylelint @linaria/stylelint-config-standard-linaria
```
```json
// .stylelintrc
{
"extends": ["@linaria/stylelint-config-standard-linaria"]
}
```
--------------------------------
### Install Linaria Core and React Bindings
Source: https://github.com/callstack/linaria/blob/master/README.md
Install the necessary Linaria packages using npm or yarn. Includes core functionality and React helpers, along with the Babel preset for integration.
```sh
npm install @linaria/core @linaria/react @wyw-in-js/babel-preset
```
```sh
yarn add @linaria/core @linaria/react @wyw-in-js/babel-preset
```
--------------------------------
### Install Linaria Core Packages (npm)
Source: https://github.com/callstack/linaria/blob/master/packages/core/README.md
Use this command to install the necessary Linaria packages using npm.
```sh
npm install @linaria/core @linaria/react @linaria/babel-preset
```
--------------------------------
### Install Vite Plugin for Linaria
Source: https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md
Install the Linaria Vite plugin to integrate Linaria with Vite projects.
```sh
yarn add --dev @wyw-in-js/vite
```
--------------------------------
### Basic Configuration with JS File
Source: https://github.com/callstack/linaria/blob/master/docs/CONFIGURATION.md
Use a JS file to export configuration options for Linaria. This example sets `evaluate` to true and `displayName` to false.
```javascript
module.exports = {
evaluate: true,
displayName: false,
};
```
--------------------------------
### Install Linaria Core, React, and Babel Preset
Source: https://github.com/callstack/linaria/blob/master/packages/react/README.md
Install the necessary Linaria packages for your React project using npm or yarn.
```bash
npm install @linaria/core @linaria/react @linaria/babel-preset
```
```bash
yarn add @linaria/core @linaria/react @linaria/babel-preset
```
--------------------------------
### Install CSS extraction dependencies
Source: https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md
Install `css-loader` and `mini-css-extract-plugin` for extracting CSS. These are essential for handling styles separately.
```sh
yarn add --dev css-loader mini-css-extract-plugin
```
--------------------------------
### Install webpack development dependencies
Source: https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md
Install all necessary webpack and Linaria related packages as development dependencies. This command includes bundlers, loaders, and plugins.
```sh
yarn add --dev webpack webpack-cli webpack-dev-server mini-css-extract-plugin css-loader file-loader babel-loader @wyw-in-js/webpack-loader
```
--------------------------------
### Run Development Watch Mode
Source: https://github.com/callstack/linaria/blob/master/CONTRIBUTING.md
Use this command to automatically compile changed files during development. Ensure Pnpm is installed and the project is bootstrapped.
```sh
pnpm watch
```
--------------------------------
### Run Website Development Server
Source: https://github.com/callstack/linaria/blob/master/CONTRIBUTING.md
Start the development server for the Linaria website with live reloading to preview changes. This is useful when working on documentation or website features.
```sh
pnpm website start
```
--------------------------------
### Update package.json for Preact CLI
Source: https://github.com/callstack/linaria/blob/master/docs/CONFIGURATION.md
Install necessary Linaria and Babel packages and update your `package.json` when using Preact CLI. Ensure `@babel/preset-react` is installed as Linaria works with JSX.
```diff
"devDependencies": {
"@babel/preset-react": "^7.8.3",
"enzyme": "^3.10.0",
"enzyme-adapter-preact-pure": "^2.0.0",
"eslint": "^6.0.1",
"eslint-config-preact": "^1.1.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^24.9.0",
"jest-preset-preact": "^1.0.0",
"per-env": "^1.0.2",
"preact-cli": "^3.0.0-rc.6",
"preact-render-spy": "^1.2.1",
"sirv-cli": "^0.4.5"
},
"dependencies": {
"@linaria/babel-preset": "^3.0.0",
"@linaria/core": "^3.0.0",
"@linaria/react": "^3.0.0",
"@linaria/webpack-loader": "^3.0.0",
"preact": "^10.3.2",
"preact-render-to-string": "^5.1.4",
"preact-router": "^3.2.1"
}
```
--------------------------------
### Re-exporting Linaria APIs from a Local File
Source: https://github.com/callstack/linaria/blob/master/docs/CONFIGURATION.md
Example of re-exporting Linaria's core APIs from a local file, enabling them to be imported from a custom path as configured by `tagResolver`.
```javascript
// my-file.js
import { css, styled } from './my-local-folder/linaria';
export const MyComponent = styled.div`
color: red;
`;
export default css`
border: 1px solid black;
`;
```
--------------------------------
### Equivalent CSS for Object Interpolation
Source: https://github.com/callstack/linaria/blob/master/docs/BASICS.md
This shows the CSS generated from the object interpolation example. It demonstrates how nested styles and media queries are flattened.
```css
const Title = styled.h1`
font-size: 24px;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
opacity: 1;
min-height: 360px;
@media (min-width: 200px): {
min-height: 480px;
}
`;
```
--------------------------------
### Webpack Integration with Linaria
Source: https://context7.com/callstack/linaria/llms.txt
Configuration for integrating Linaria with webpack. Includes setup for babel-loader, @wyw-in-js/webpack-loader, and MiniCssExtractPlugin.
```javascript
// webpack.config.js
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const dev = process.env.NODE_ENV !== 'production';
module.exports = {
mode: dev ? 'development' : 'production',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].bundle.js',
},
plugins: [
new MiniCssExtractPlugin({
filename: dev ? 'styles.css' : 'styles-[contenthash].css',
}),
],
module: {
rules: [
{
test: /\.(js|ts|tsx)$/,
exclude: /node_modules/,
use: [
{ loader: 'babel-loader' },
{
loader: '@wyw-in-js/webpack-loader',
options: {
sourceMap: dev,
// cacheProvider: './path/to/cache' // needed with thread-loader
},
},
],
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { sourceMap: dev } }],
},
],
},
};
```
--------------------------------
### Fix Lint and Formatting Errors
Source: https://github.com/callstack/linaria/blob/master/CONTRIBUTING.md
Run this command to automatically fix any linting or formatting issues in the codebase. Ensure you have pnpm installed.
```sh
pnpm lint -- --fix
```
--------------------------------
### Custom Tag Resolver for Linaria APIs
Source: https://github.com/callstack/linaria/blob/master/docs/CONFIGURATION.md
Implement `tagResolver` to allow Linaria's `css` and `styled` APIs to be imported from custom locations. This example maps imports from a local file to specific Linaria processors.
```javascript
{
tagResolver: (source, tag) => {
const pathToLocalFile = join(__dirname, './my-local-folder/linaria.js');
if (source === pathToLocalFile) {
if (tag === 'css') {
return require.resolve('@linaria/core/processors/css');
}
if (tag === 'styled') {
return require.resolve('@linaria/react/processors/styled');
}
}
return null;
};
}
```
--------------------------------
### Express App Example for Critical CSS
Source: https://github.com/callstack/linaria/blob/master/docs/CRITICAL_CSS.md
Demonstrates critical CSS extraction in an Express.js app using React. It renders the app, collects critical CSS, and serves non-critical CSS lazily.
```javascript
import fs from 'fs';
import express from 'express';
import crypto from 'crypto';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { collect } from '@linaria/server';
import App from './App';
const cache = {};
const css = fs.readFileSync('./dist/styles.css', 'utf8');
const app = express();
app.get('/', (req, res) => {
const html = ReactDOMServer.renderToString();
const { critical, other } = collect(html, css);
const slug = crypto.createHash('md5').update(other).digest('hex');
cache[slug] = other;
res.end(`
App
${html}
`);
});
app.get('/styles/:slug', (req, res) => {
res.type('text/css');
res.end(cache[req.params.slug])
});
app.listen(3242);
```
--------------------------------
### Create Gatsby Project
Source: https://github.com/callstack/linaria/blob/master/docs/CONFIGURATION.md
Initialize a new Gatsby project using the `gatsby-cli`. This command sets up the basic structure for a Gatsby application.
```bash
npx gatsby new my-project
```
--------------------------------
### Linaria CLI with Multiple Globs
Source: https://github.com/callstack/linaria/blob/master/docs/CLI.md
Shows how to use multiple glob patterns to specify input files for the Linaria CLI. The `-o` option remains required.
```bash
yarn linaria -o styles src/component/**/*.js src/screens/**/*.js
```
--------------------------------
### Importing CSS with Linaria
Source: https://github.com/callstack/linaria/blob/master/README.md
Demonstrates how to import CSS using the `css` tag from Linaria. Ensure that imported files do not have side-effects.
```javascript
import { css } from '@linaria/core';
import colors from './colors';
const title = css`
color: ${colors.text};
`;
```
--------------------------------
### Linaria CLI with Output Directory
Source: https://github.com/callstack/linaria/blob/master/docs/CLI.md
Demonstrates how to specify the output directory using the `-o` option. This is a mandatory option for the CLI.
```bash
yarn linaria -o styles src/component/**/*.js
```
--------------------------------
### Theming with CSS Custom Properties and Class Selectors
Source: https://context7.com/callstack/linaria/llms.txt
Illustrates two theming approaches: CSS custom properties for dynamic theming and parent class selectors for IE-compatible theming. Also shows React Context integration with `withTheme`.
```javascript
import { css } from '@linaria/core';
import { styled } from '@linaria/react';
// --- Approach 1: CSS variable themes ---
const lightTheme = css`
--color-primary: #6200ee;
--color-accent: #03dac4;
--color-bg: #ffffff;
--color-text: #000000;
`;
const darkTheme = css`
--color-primary: #bb86fc;
--color-accent: #03dac4;
--color-bg: #121212;
--color-text: #ffffff;
`;
const ThemedButton = styled.button`
background-color: var(--color-primary);
color: var(--color-text);
`;
function App({ isDark }) {
return (
Click me
);
}
// --- Approach 2: Parent class selector theming (IE-compatible) ---
const colors = {
light: { text: 'black', bg: 'white' },
dark: { text: 'white', bg: '#121212' },
};
const theming = (cb) =>
Object.keys(colors).reduce(
(acc, name) => Object.assign(acc, { [`.theme-${name} &`]: cb(colors[name]) }),
{}
);
const Header = styled.h1`
text-transform: uppercase;
${theming((c) => ({
color: c.text,
backgroundColor: c.bg,
}))};
`;
// --- Approach 3: React Context + withTheme ---
const ThemedCard = withTheme(styled.div`
background-color: ${(props) => props.theme.surface};
border: 1px solid ${(props) => props.theme.border};
`);
```
--------------------------------
### Babel Preset configuration for Gatsby
Source: https://context7.com/callstack/linaria/llms.txt
Configure the '@wyw-in-js/babel-preset' within your babel.config.js for Gatsby projects. This example dynamically sets the 'displayName' based on the NODE_ENV.
```js
// babel.config.js — Gatsby example
module.exports = {
presets: [
'babel-preset-gatsby',
['@wyw-in-js/babel-preset', {
evaluate: true,
displayName: process.env.NODE_ENV !== 'production',
}],
],
};
```
--------------------------------
### Basic Linaria CLI Usage
Source: https://github.com/callstack/linaria/blob/master/docs/CLI.md
This is the basic command to run the Linaria CLI. The `-o` or `--out-dir` option is always required to specify the output directory for extracted CSS files.
```bash
yarn linaria [options] [...]
```
--------------------------------
### Using Atomic CSS with Linaria
Source: https://github.com/callstack/linaria/blob/master/docs/ATOMIC_CSS.md
Demonstrates how to import and use the `css` template literal from `@linaria/atomic` to create atomic styles in a React component.
```tsx
import { cx } from '@linaria/core';
import { css } from '@linaria/atomic';
const atomicCss = css`
background: red;
width: 100%;
height: 100%;
border: 1px solid black;
`;
const blueBackground = css`
background: blue;
border: 1px solid black;
`;
// In React:
;
// In vanilla JS:
const div = document.createElement('div');
div.setAttribute('class', cx(atomicCss, blueBackground));
document.body.appendChild(div);
```
--------------------------------
### Configure dangerousCodeRemover Feature
Source: https://github.com/callstack/linaria/blob/master/docs/FEATURE_FLAGS.md
Use the `features` option to selectively disable the `dangerousCodeRemover` for specific files. This example excludes `specialComponent.js` from the removal process.
```javascript
{
features: {
dangerousCodeRemover: ["**/*", "!**/specialComponent.js"],
},
}
```
--------------------------------
### Nesting Media Queries
Source: https://github.com/callstack/linaria/blob/master/docs/BASICS.md
Shows how to nest media queries within a `styled` component. Styles defined within the media query will apply when the condition is met.
```javascript
const Thing = styled.div`
color: black;
@media (min-width: 200px) {
color: blue;
}
`;
```
--------------------------------
### Customize Class Name Slug with String
Source: https://github.com/callstack/linaria/blob/master/docs/CONFIGURATION.md
Customize the output of CSS class names by providing a string pattern. For example, `classNameSlug: '[title]'` generates a class name like `.header` instead of the default `.header_absdjfsdf`.
--------------------------------
### esbuild Plugin Configuration
Source: https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md
Integrate Linaria with esbuild using its plugin. Enable source maps for production builds.
```javascript
import linaria from '@wyw-in-js/esbuild';
import esbuild from 'esbuild';
const prod = process.env.NODE_ENV === 'production';
esbuild
.build({
entryPoints: ['src/index.ts'],
outdir: 'dist',
bundle: true,
minify: prod,
plugins: [
linaria({
sourceMap: prod,
}),
],
})
.catch(() => process.exit(1));
```
--------------------------------
### Configure Linaria Build-Time Evaluation
Source: https://context7.com/callstack/linaria/llms.txt
Configuration for Linaria's build-time evaluation engine. Customize dynamic expressions, class names, variable formats, and module rules.
```javascript
// wyw-in-js.config.js
const sha1 = require('sha1');
module.exports = {
// Evaluate dynamic expressions and imported variables at build time
evaluate: true,
// Add component display names to generated class names (useful in dev)
displayName: process.env.NODE_ENV !== 'production',
// 'var' (default) | 'dashes' | 'raw' — controls CSS variable format
variableNameConfig: 'var',
// Custom class name format
classNameSlug: (hash, title, args) => sha1(`${args.name}-${title}`),
// Custom CSS variable name format
variableNameSlug: '[componentName]-[valueSlug]-[index]',
// Control which modules are evaluated vs. treated as opaque
rules: [
{
action: require.resolve('@linaria/shaker'),
},
{
test: /[\/]node_modules[\/]/,
action: 'ignore',
},
],
// Re-export linaria APIs from your own module
tagResolver: (source, tag) => {
if (source === require.resolve('./src/styles/linaria')) {
if (tag === 'css') return require.resolve('@linaria/core/processors/css');
if (tag === 'styled') return require.resolve('@linaria/react/processors/styled');
}
return null;
},
// Add globals to the evaluation context
overrideContext: (context, filename) => ({
...context,
__DEV__: process.env.NODE_ENV !== 'production',
}),
// Pass custom Babel options for module parsing
babelOptions: {
presets: ['@babel/preset-typescript'],
},
};
```
--------------------------------
### Use Theming Helper in Styles
Source: https://github.com/callstack/linaria/blob/master/docs/THEMING.md
Apply dynamic styling to elements using the `theming` helper function, which generates theme-specific CSS rules.
```javascript
const Header = styled.h1`
text-transform: uppercase;
${theming(c => ({
color: c.text,
}))};
`;
```
--------------------------------
### Create Styled React Components
Source: https://github.com/callstack/linaria/blob/master/README.md
Utilize the `styled` helper from '@linaria/react' for a styled-component-like syntax with React. Enables dynamic styles using CSS custom properties without runtime overhead.
```js
import { styled } from '@linaria/react';
import { families, sizes } from './fonts';
// Write your styles in `styled` tag
const Title = styled.h1`
font-family: ${families.serif};
`;
const Container = styled.div`
font-size: ${sizes.medium}px;
color: ${props => props.color};
border: 1px solid red;
&:hover {
border-color: blue;
}
${Title} {
margin-bottom: 24px;
}
`;
// Then use the resulting component
Hello world;
```
--------------------------------
### Configure Babel for @linaria/interop
Source: https://github.com/callstack/linaria/blob/master/packages/interop/README.md
Add the @linaria/interop plugin to your Babel configuration before the styled-components plugin. Specify the library being used.
```json
{
"plugins": [
["@linaria/interop", { "library": "styled-components" }],
"styled-components"
]
}
```
--------------------------------
### Importing the collect helper
Source: https://github.com/callstack/linaria/blob/master/docs/CRITICAL_CSS.md
Import the `collect` function from `@linaria/server` to enable critical CSS extraction.
```javascript
import { collect } from '@linaria/server';
const { critical, other } = collect(html, css);
```
--------------------------------
### Configure MiniCssExtractPlugin with content hash
Source: https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md
For production builds, use a content hash in the filename for better cache control. This ensures that updated files are fetched by the browser.
```javascript
new MiniCssExtractPlugin({
filename: 'styles-[contenthash].css',
});
```
--------------------------------
### Publish a Release
Source: https://github.com/callstack/linaria/blob/master/CONTRIBUTING.md
Command to publish a new release using release-it. Ensure you have NPM publish access and a GITHUB_TOKEN environment variable set with 'repo' access.
```sh
yarn release
```
--------------------------------
### Configure Stylelint v13 with Linaria
Source: https://github.com/callstack/linaria/blob/master/docs/LINTING.md
Extend your stylelint configuration to include the Linaria stylelint plugin for v13.
```json
{
"extends": [
"stylelint-config-recommended",
"@linaria/stylelint"
]
}
```
--------------------------------
### Configure Svelte with Rollup, Linaria, and CSS Plugin
Source: https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md
Set up Rollup for Svelte projects with Linaria and a CSS plugin. Ensure `emitCss` is enabled in `svelte-loader` for CSS bundling.
```javascript
import svelte from 'rollup-plugin-svelte';
import css from 'rollup-plugin-css-only'; // for CSS bundling
import linaria from '@wyw-in-js/rollup';
const dev = process.env.NODE_ENV !== 'production';
export default {
...
plugins: [
svelte({
dev,
// allow `plugin-css-only` to bundle with CSS generated by linaria
emitCss: true,
}),
linaria({
sourceMap: dev,
}),
css({
output: '/bundle.css',
}),
],
};
```
--------------------------------
### Configure Stylelint v14 with Linaria Custom Syntax
Source: https://github.com/callstack/linaria/blob/master/docs/LINTING.md
Configure stylelint v14 to use Linaria's custom syntax without extending a full config.
```json
{
"customSyntax": "@linaria/postcss-linaria"
}
```
--------------------------------
### Custom PostCSS syntax for Stylelint
Source: https://context7.com/callstack/linaria/llms.txt
If you only need to use Linaria's PostCSS syntax with Stylelint without a full configuration, specify '@linaria/postcss-linaria' as the customSyntax in your .stylelintrc file.
```json
// .stylelintrc
{
"customSyntax": "@linaria/postcss-linaria"
}
```
--------------------------------
### esbuild Integration with Linaria
Source: https://context7.com/callstack/linaria/llms.txt
Configuration for integrating Linaria with esbuild. Uses the @wyw-in-js/esbuild plugin.
```javascript
// build.js
import linaria from '@wyw-in-js/esbuild';
import esbuild from 'esbuild';
esbuild.build({
entryPoints: ['src/index.ts'],
outdir: 'dist',
bundle: true,
minify: process.env.NODE_ENV === 'production',
plugins: [
linaria({ sourceMap: true }),
],
}).catch(() => process.exit(1));
```
--------------------------------
### Atomic CSS with At-Rules and Pseudo Classes
Source: https://github.com/callstack/linaria/blob/master/docs/ATOMIC_CSS.md
Demonstrates how Linaria's atomic CSS supports nested at-rules, pseudo classes, and keyframes. Note that keyframe animations are not atomized.
```ts
import { css } from '@linaria/atomic';
// Note: animation name namespacing does not happen automatically with @linaria/atomic. Keyframe animations are pulled out to the top level and not atomized.
export const animation = css`
@keyframes my-animation {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
animation: my-animation 1s infinite;
`;
export const pseudoClass = css`
&:hover {
color: pink;
}
`;
export const mediaQuery = css`
@media (max-width: 400px) {
background: orange;
}
`;
```
--------------------------------
### Linaria CLI: Extract CSS
Source: https://context7.com/callstack/linaria/llms.txt
Command-line interface for Linaria to extract CSS from source files without a bundler. Supports multiple globs, source maps, and custom config files.
```bash
# Install
yarn add --dev @linaria/cli
# Extract CSS from all component files into ./styles directory
yarn linaria -o styles src/components/**/*.js
# Multiple globs
yarn linaria -o styles src/components/**/*.js src/screens/**/*.tsx
# With source maps
yarn linaria -o styles --source-maps src/**/*.js
# Automatically insert `require('./component.css')` into transpiled JS
yarn linaria \
-o dist/styles \
--source-root src \
--insert-css-requires dist \
src/**/*.js
# Use a custom config file
yarn linaria -o styles --config-file ./my-linaria.config.js src/**/*.js
```
--------------------------------
### Create Theming Helper Function
Source: https://github.com/callstack/linaria/blob/master/docs/THEMING.md
A helper function to generate CSS rule sets for multiple themes by iterating over a color configuration object.
```javascript
const colors = {
light: {
text: 'black',
},
dark: {
text: 'white',
},
};
const theming = cb =>
Object.keys(colors).reduce((acc, name) => Object.assign(acc, {
[`.theme-${name} &`]: cb(colors[name]),
}), {});
```
--------------------------------
### Configure Stylelint v14 with Linaria Standard Config
Source: https://github.com/callstack/linaria/blob/master/docs/LINTING.md
Extend your stylelint configuration with the standard Linaria config for v14.
```json
{
"extends": [
"@linaria/stylelint-config-standard-linaria"
]
}
```
--------------------------------
### Configure Vite with Linaria for TypeScript Support
Source: https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md
Configure the Linaria Vite plugin to support TypeScript syntax by specifying include paths and Babel options.
```javascript
import { defineConfig } from 'vite';
import linaria from '@wyw-in-js/vite';
// example to support typescript syntax:
export default defineConfig(() => ({
// ...
plugins: [
linaria({
include: ['**/*.{ts,tsx}'],
babelOptions: {
presets: ['@babel/preset-typescript', '@babel/preset-react'],
},
}),
],
}));
```
--------------------------------
### Template Literal Syntax
Source: https://github.com/callstack/linaria/blob/master/docs/BASICS.md
Demonstrates the basic syntax of JavaScript template literals, including multi-line strings and interpolation.
```javascript
const message = `
This is a template literal.
This is an interpolation: ${answer}.
`;
```
--------------------------------
### Create React styled components with `styled`
Source: https://context7.com/callstack/linaria/llms.txt
Use the `styled` tag from `@linaria/react` to create React components with scoped CSS. Dynamic prop-based styles compile to CSS custom properties for runtime updates.
```javascript
import { styled } from '@linaria/react';
import { darken } from 'polished';
const colors = { primary: '#6200ee', accent: '#03dac4' };
// Basic styled component
const Button = styled.button`
padding: 8px 24px;
border: none;
border-radius: 4px;
background-color: ${colors.primary};
/* evaluated at build time */
color: white;
cursor: pointer;
&:hover {
background-color: ${darken(0.1, colors.primary)}; /* build-time fn call */
}
`;
// Prop-based dynamic styles (CSS custom properties at runtime)
const Title = styled.h1`
font-size: ${props => props.size ?? 24}px;
color: ${props => props.color ?? 'black'};
font-weight: ${props => (props.bold ? 'bold' : 'normal')};
`;
// Extend / override another styled component
const LargeButton = styled(Button)`
padding: 16px 32px;
font-size: 18px;
`;
// Use `as` prop to swap the rendered HTML tag
const LinkButton = () => (
);
// Reference a component in another component's selector
const Card = styled.article`
padding: 24px;
${Title} {
margin-bottom: 16px;
}
`;
// Style a custom component (must accept className + style props)
function CustomInput({ className, style, ...rest }) {
return ;
}
const StyledInput = styled(CustomInput)`
border: 2px solid ${props => (props.error ? 'red' : '#ccc')};
padding: 8px;
`;
```
--------------------------------
### Configure VS Code Stylelint Extension
Source: https://github.com/callstack/linaria/blob/master/docs/LINTING.md
Configure the vscode-stylelint extension to validate Linaria files by specifying language identifiers.
```json
{
"stylelint.validate": ["typescriptreact"]
}
```
--------------------------------
### Define CSS with css Tag
Source: https://github.com/callstack/linaria/blob/master/README.md
Use the `css` tag from '@linaria/core' to write styles. Supports imported variables and functions for dynamic styling evaluated at build time. Styles are applied as class names.
```js
import { css } from '@linaria/core';
import { modularScale, hiDPI } from 'polished';
import fonts from './fonts';
// Write your styles in `css` tag
const header = css`
text-transform: uppercase;
font-family: ${fonts.heading};
font-size: ${modularScale(2)};
${hiDPI(1.5)} {
font-size: ${modularScale(2.5)};
}
`;
// Then use it as a class name
Hello world
;
```
--------------------------------
### Webpack Loader Configuration
Source: https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md
Configure the Linaria webpack loader with options like sourceMap.
```javascript
{
loader: '@wyw-in-js/webpack-loader',
options: {
sourceMap: false,
},
}
```
--------------------------------
### Create React Components with styled Helper
Source: https://github.com/callstack/linaria/blob/master/docs/API.md
Use the `styled` helper from `@linaria/react` to create styled React components. It supports CSS template literals and function interpolations that receive component props.
```javascript
import { styled } from '@linaria/react';
import colors from './colors.json';
const Container = styled.div`
background-color: ${colors.background};
color: ${(props) => props.color};
width: ${100 / 3}%;
border: 1px solid red;
&:hover {
border-color: blue;
}
`;
```
--------------------------------
### Configure Linaria Evaluation Strategy
Source: https://github.com/callstack/linaria/blob/master/docs/MIGRATION_GUIDE.md
If you need to use the old evaluation strategy from Linaria 1.x, add this 'rules' section to your Linaria config.
```javascript
[
{
action: require('linaria/evaluators').extractor,
},
{
test: /\/node_modules\//,
action: 'ignore',
},
]
```
--------------------------------
### Add Linaria Babel Preset
Source: https://github.com/callstack/linaria/blob/master/docs/CONFIGURATION.md
Append `@linaria` to your Babel presets list to enable Linaria's CSS pre-processing. This is useful when components are imported outside of bundler-handled files.
```json
{
"presets": [
"@babel/preset-env",
"@babel/preset-react",
"@linaria"
]
}
```
--------------------------------
### Babel Preset configuration for non-bundler contexts
Source: https://context7.com/callstack/linaria/llms.txt
Configure the '@wyw-in-js/babel-preset' in your .babelrc file for environments like SSR or tests where a bundler is not used. Set 'evaluate' to true and 'displayName' to false for production builds.
```json
// .babelrc
{
"presets": [
"@babel/preset-env",
"@babel/preset-react",
"@babel/preset-typescript",
["@wyw-in-js/babel-preset", {
"evaluate": true,
"displayName": false
}]
]
}
```
--------------------------------
### Linaria CLI with CSS Require Insertion
Source: https://github.com/callstack/linaria/blob/master/docs/CLI.md
This command configures the Linaria CLI to automatically insert require statements for generated CSS files. It requires both `--source-root` and `--insert-css-requires` options to be set.
```bash
yarn linaria -o out-dir --source-root src --insert-css-requires dist src/**/*.js
```
--------------------------------
### Dynamic Styles with `css` Tag
Source: https://context7.com/callstack/linaria/llms.txt
Demonstrates using the `css` tag for dynamic styling with CSS custom properties, data attributes, and `currentColor`. Runtime values should use CSS mechanisms, not JS interpolations.
```javascript
import React from 'react';
import { css } from '@linaria/core';
// Pattern 1: CSS custom properties
const sizedBox = css`
height: var(--size);
width: var(--size);
background: var(--color, tomato);
`;
function Box({ size, color }) {
return (
);
}
// Pattern 2: data-* attributes for known discrete values
const statusBadge = css`
&[data-status='success'] { background: green; color: white; }
&[data-status='error'] { background: red; color: white; }
&[data-status='pending'] { background: gray; color: white; }
`;
function Badge({ status, label }) {
return (
{label}
);
}
// Pattern 3: currentColor for color-driven styling
const coloredIcon = css`
background-color: currentColor;
`;
function Icon({ color }) {
return (
{/* text inside gets a different color */}
);
}
```
--------------------------------
### Configure MiniCssExtractPlugin for CSS
Source: https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md
Set up `MiniCssExtractPlugin` to extract CSS from your project. This configuration should be added to your webpack rules for `.css` files.
```javascript
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
```
```javascript
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
options: {
sourceMap: process.env.NODE_ENV !== 'production',
},
},
],
}
```
--------------------------------
### Transformed Atomic CSS Output
Source: https://github.com/callstack/linaria/blob/master/docs/ATOMIC_CSS.md
Shows the build-time transformation of Linaria's atomic CSS into optimized class names, highlighting deduplication of styles.
```ts
import { cx } from '@linaria/core';
import { css } from '@linaria/atomic';
const atomicCss =
'atm_background_abcd atm_width_efgh atm_height_ijkl atm_border_mnop';
const blueBackground = 'atm_background_qrst atm_border_mnop';
// In React:
; //
// In vanilla JS:
const div = document.createElement('div');
div.setAttribute('class', cx(atomicCss, blueBackground)); // same as React example
document.body.appendChild(div);
```
--------------------------------
### cx - Class Name Concatenation
Source: https://github.com/callstack/linaria/blob/master/docs/API.md
The `cx` function from `@linaria/core` takes a list of class names and returns a concatenated string. Falsy values in the list are ignored. It is similar to the `classnames` library but does not handle objects.
```APIDOC
## cx(...classNames: Array) => string
### Description
Takes a list of class names and returns a concatenated string with the class names. Falsy values are ignored.
### Usage
```js
import { css, cx } from '@linaria/core';
const cat = css`
font-weight: bold;
`;
const yarn = css`
color: violet;
`;
const fun = css`
display: flex;
`;
function App({ isPlaying }) {
return ;
}
```
Unlike the [`classnames`](https://www.npmjs.com/package/classnames) library, this doesn't handle objects.
```
--------------------------------
### Linaria 1.x/2.x to 3.x+ migration: Package split
Source: https://context7.com/callstack/linaria/llms.txt
When migrating from Linaria versions 1.x or 2.x to 3.x+, update your import statements. The 'css' and 'styled' functions are now imported from '@linaria/core' and '@linaria/react' respectively, instead of the top-level 'linaria' package.
```diff
- import { css } from 'linaria';
- import { styled } from 'linaria/react';
+ import { css } from '@linaria/core';
+ import { styled } from '@linaria/react';
```
--------------------------------
### Configure MiniCssExtractPlugin instance
Source: https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md
Instantiate `MiniCssExtractPlugin` in your webpack config's `plugins` section. This specifies the output filename for the extracted CSS.
```javascript
new MiniCssExtractPlugin({
filename: 'styles.css',
});
```
--------------------------------
### cx
Source: https://context7.com/callstack/linaria/llms.txt
The `cx` utility is used for conditionally combining class names. It takes any number of class name strings (or falsy values) and returns a space-separated string. Falsy values such as `false`, `null`, `undefined`, or `0` are ignored.
```APIDOC
## cx
### Description
`cx(...classNames)` takes any number of class name strings (or falsy values) and returns a space-separated string. Falsy values (`false`, `null`, `undefined`, `0`) are ignored.
### Usage
```js
import { css, cx } from '@linaria/core';
const base = css`
padding: 8px 16px;
border-radius: 4px;
font-size: 14px;
`;
const primary = css`
background-color: rebeccapurple;
color: white;
`;
const disabled = css`
opacity: 0.5;
cursor: not-allowed;
`;
function Button({ variant, isDisabled, className, children }) {
return (
);
}
// Usage:
//
// className → 'base_x1 primary_y2'
//
//
// className → 'base_x1 disabled_z3'
```
```
--------------------------------
### Link Local Linaria Build
Source: https://github.com/callstack/linaria/blob/master/CONTRIBUTING.md
Commands to link a local development build of Linaria into a test project for local testing. This involves using yarn link in both the Linaria clone and the test project.
```sh
cd /path/to/your/linaria_clone/
yarn
yarn link
cd /path/to/test_project/
yarn link linaria
```
```sh
yarn unlink linaria
```
--------------------------------
### Vite Integration with Linaria
Source: https://context7.com/callstack/linaria/llms.txt
Configuration for integrating Linaria with Vite. Uses the @wyw-in-js/vite plugin and @vitejs/plugin-react.
```javascript
// vite.config.js
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import linaria from '@wyw-in-js/vite';
export default defineConfig({
plugins: [
linaria({
include: ['**/*.{ts,tsx,js,jsx}'],
babelOptions: {
presets: ['@babel/preset-typescript', '@babel/preset-react'],
},
}),
react(),
],
});
```
--------------------------------
### Configure Vite with Linaria Plugin
Source: https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md
Add the Linaria plugin to your Vite configuration file. Vite handles CSS internally, so no separate CSS plugin is needed.
```javascript
import { defineConfig } from 'vite';
import linaria from '@wyw-in-js/vite';
export default defineConfig(() => ({
// ...
plugins: [linaria()],
}));
```
--------------------------------
### Local Linaria Core Re-export
Source: https://github.com/callstack/linaria/blob/master/docs/CONFIGURATION.md
A simple re-export of Linaria's core module, intended to be used with a custom `tagResolver` configuration.
```javascript
// ./my-local-folder/core.js
export * from '@linaria/core';
```
--------------------------------
### Configure Rollup with Linaria, CSS, and Babel Plugins
Source: https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md
Integrate Linaria, a CSS plugin, and Babel into your Rollup configuration. The order of plugins is important, with Linaria typically preceding Babel.
```javascript
import linaria from '@wyw-in-js/rollup';
import css from 'rollup-plugin-css-only';
import babel from '@rollup/plugin-babel';
export default {
plugins: [
linaria({
sourceMap: process.env.NODE_ENV !== 'production',
}),
css({
output: 'styles.css',
}),
babel({}),
/* rest of your plugins */
],
};
```
--------------------------------
### Configure Webpack for Preact CLI
Source: https://github.com/callstack/linaria/blob/master/docs/CONFIGURATION.md
Modify your `preact.config.js` to integrate `@linaria/webpack-loader` and necessary Babel presets. This ensures Linaria processes your styles correctly within the Preact build.
```javascript
export default (config) => {
const { options, ...babelLoaderRule } = config.module.rules[0]; // Get the babel rule and options
options.presets.push('@babel/preset-react', '@linaria'); // Push the necessary presets
config.module.rules[0] = {
...babelLoaderRule,
loader: undefined, // Disable the predefined babel-loader on the rule
use: [
{
loader: 'babel-loader',
options,
},
{
loader: '@linaria/webpack-loader',
options: {
babelOptions: options, // Pass the current babel options to linaria's babel instance
},
},
],
};
};
```
--------------------------------
### Configure CSS Variable Formatting (raw)
Source: https://github.com/callstack/linaria/blob/master/docs/CONFIGURATION.md
Uses only the variable name without dashes and `var()` wrapper. This is not a valid CSS value on its own and requires manual wrapping with `var()`.
```javascript
import { styled } from "@linaria/react";
export const MyComponent = styled.div`
color: ${(props) => props.color};
`;
```
```css
.MyComponent_mc195ga {
color: mc195ga-0;
}
```
```javascript
export const MyComponent = styled.div`
color: var(--${(props) => props.color});
`;
```
--------------------------------
### Property Priority in Atomic CSS
Source: https://github.com/callstack/linaria/blob/master/docs/ATOMIC_CSS.md
Illustrates how longhand properties (e.g., `padding-top`) have higher priority than shorthand properties (e.g., `padding`) in Atomic CSS.
```ts
import { css } from '@linaria/atomic';
const noPadding = css`
padding: 0;
`;
const paddingTop = css`
padding-top: 5px:
`;
// In react:
...
;
```
--------------------------------
### Configure webpack-loader for Linaria
Source: https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md
Add `@wyw-in-js/webpack-loader` to your webpack configuration. Ensure it's placed after `babel-loader` to process JavaScript files correctly.
```javascript
{
test: /\.js$/,
use: [
{ loader: 'babel-loader' },
{
loader: '@wyw-in-js/webpack-loader',
options: {
sourceMap: process.env.NODE_ENV !== 'production',
},
}
],
}
```