A recommended babel preprocessing plugin for emotion, The Next Generation of CSS-in-JS.
npx @tessl/cli install tessl/npm-emotion--babel-plugin@11.13.0@emotion/babel-plugin is a Babel preprocessing plugin that provides minification, optimization, and enhanced features for emotion CSS-in-JS applications. It transforms emotion template literals and styled component calls into optimized runtime code while supporting advanced development features like source maps, component-as-selector support, and contextual class names.
npm install --save-dev @emotion/babel-pluginImport the plugin directly:
const emotionBabelPlugin = require("@emotion/babel-plugin");For ES modules:
import emotionBabelPlugin from "@emotion/babel-plugin";Access pre-configured macros (for advanced plugin development):
import emotionBabelPlugin, { macros } from "@emotion/babel-plugin";Without options:
{
"plugins": ["@emotion"]
}With options (defaults shown):
{
"plugins": [
[
"@emotion",
{
"sourceMap": true,
"autoLabel": "dev-only",
"labelFormat": "[local]",
"cssPropOptimization": true
}
]
]
}babel --plugins @emotion/babel-plugin script.jsrequire('@babel/core').transform('code', {
plugins: ['@emotion/babel-plugin']
})The plugin operates through Babel's visitor pattern with several key components:
The default export provides the main Babel plugin function that processes emotion code.
/**
* Main Babel plugin function for @emotion/babel-plugin
* @param {Object} babel - Babel instance with types and utilities
* @param {PluginOptions} options - Plugin configuration options
* @returns {PluginConfig} Babel plugin configuration object
*/
function emotionBabelPlugin(babel, options = {});Collection of pre-configured transformer macros for different emotion packages.
/**
* Pre-configured macros for different emotion packages
*/
const macros: {
/** Core emotion/react macro for css and jsx transformations */
core: TransformerMacro;
/** React Native styled component macro */
nativeStyled: TransformerMacro;
/** Primitives styled component macro */
primitivesStyled: TransformerMacro;
/** Web styled component macro */
webStyled: TransformerMacro;
/** Vanilla emotion/css macro */
vanillaEmotion: TransformerMacro;
};Transforms CSS template literals with minification and optimization.
// Input transformation
const myStyles = css`
font-size: 20px;
background: green;
`;
// Output after transformation (optimized and minified)
const myStyles = /*#__PURE__*/ css('font-size:20px;background:green;');Transforms styled component definitions with labeling and optimization.
// Input transformation
const Button = styled.button`
padding: 10px;
`;
// Output after transformation
const Button = /*#__PURE__*/ styled('button', { label: 'Button' })({
padding: '10px'
});Development-focused features including labeling, source maps, and debugging aids.
// Automatic labeling based on variable names
const navigationStyles = css`
display: flex;
`;
// Result class: css-hash-navigationStyles
// Label format customization
// labelFormat: "[filename]--[local]"
// Result class: css-hash-MyComponent--navigationStylesCustom import mapping for packages that re-export emotion functionality.
interface ImportMap {
[packageName: string]: {
[exportName: string]: {
canonicalImport: [string, string];
styledBaseImport?: [string, string];
};
};
}Internal transformation utilities for string processing, import management, CSS minification, and object simplification.
// Core transformation engine
function transformExpressionWithStyles({ babel, state, path, shouldLabel, sourceMap });
// String manipulation utilities
function appendStringReturningExpressionToArguments(t, path, expression);
function joinStringLiterals(expressions, t);
// Import management
function addImport(state, importSource, importedSpecifier, nameHint);The plugin provides transformations for the following emotion packages:
@emotion/css - Vanilla CSS-in-JS functionality@emotion/react - React-specific emotion features@emotion/styled - Styled components@emotion/native - React Native support@emotion/primitives - Primitives supportThe plugin handles various error conditions:
path.buildCodeFrameError() to provide clear error contextThe plugin is compatible with babel-plugin-macros for Create React App and similar environments:
import { css, keyframes } from '@emotion/css/macro'
import { jsx, css, Global, keyframes } from '@emotion/react/macro'
import styled from '@emotion/styled/macro'interface PluginOptions {
/** Enable source map generation (default: true) */
sourceMap?: boolean;
/** Automatic label generation mode (default: 'dev-only') */
autoLabel?: 'dev-only' | 'always' | 'never';
/** Label format string with placeholders (default: '[local]') */
labelFormat?: string;
/** Enable CSS prop optimization (default: true) */
cssPropOptimization?: boolean;
/** Custom import mapping for re-exported emotion functions */
importMap?: ImportMap;
}
interface TransformerMacro {
(options: MacroOptions): void;
}
interface MacroOptions {
path: any;
references: { [importName: string]: any[] };
state: any;
babel: any;
isEmotionCall?: boolean;
isBabelMacrosCall?: boolean;
}
interface EmotionBabelPluginPass {
pluginMacros: { [importSource: string]: TransformerMacro };
jsxReactImport: {
importSource: string;
export: string;
cssExport: string;
};
transformCssProp: boolean;
emotionSourceMap: boolean;
opts: PluginOptions;
file: any;
emotionStringifiedCssId?: any;
}
/** Valid values for autoLabel configuration option */
const AUTO_LABEL_VALUES: ['dev-only', 'never', 'always'];
/** Error message for incorrectly stringified CSS objects */
const CSS_OBJECT_STRINGIFIED_ERROR: string;