Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
babel-plugin-emotion
Advanced tools
A recommended babel preprocessing plugin for emotion, The Next Generation of CSS-in-JS.
The babel-plugin-emotion npm package is designed to enhance the development experience when using Emotion, a popular CSS-in-JS library. It provides optimizations and custom transformations for styles defined in JavaScript, enabling more efficient and powerful styling solutions in React applications. This plugin facilitates the use of Emotion by offering features such as source maps for easier debugging, auto-labeling for better readability of class names, and the optimization of styles for production.
Source Maps
Generates source maps for styles, improving the debugging process by allowing developers to trace back to the original location of a style definition within their code.
"use strict";
var _emotion = require("@emotion/core");
function App() {
return /*#__PURE__*/_emotion.jsx("div", {
css: {
color: 'hotpink'
}
}, "Hello World");
}
Auto-labeling
Automatically adds labels to the generated class names based on the name of the variable or component. This enhances readability in the DOM and helps in identifying components during debugging.
"use strict";
var _emotion = require("@emotion/core");
var _styled = /*#__PURE__*/(0, _emotion.default)("div")
/*#__PURE__*/
.emotionLabel('MyComponent_styled_h1nx9f');
Optimization for Production
In production, the plugin optimizes the styles by compacting and efficient handling, reducing the size of the generated CSS and improving load times.
process.env.NODE_ENV === 'production' ? /*#__PURE__*/require('@emotion/css').css('label:MyComponent;', 'color:hotpink;') : /*#__PURE__*/require('@emotion/css').css('color:hotpink;');
Styled-components is another CSS-in-JS library that allows for styling applications using tagged template literals. While it offers similar functionality in terms of defining styles within JavaScript, it differs in syntax and the way styles are applied. Styled-components focuses on creating styled components without the need for a separate CSS file, whereas babel-plugin-emotion enhances the Emotion library's capabilities with additional compile-time optimizations and features.
This plugin is specifically designed for styled-components, offering similar compile-time enhancements as babel-plugin-emotion but for styled-components. It includes features like server-side rendering optimizations, better debugging with readable class names, and minification of styles for production. The comparison lies in the focus of each plugin on its respective CSS-in-JS library, providing tailored optimizations and developer experience improvements.
Babel plugin for the minification and optimization of emotion styles.
babel-plugin-emotion
is highly recommended, but not required in version 8 and
above of emotion
.
Feature/Syntax | Native | Babel Plugin Required | Notes |
---|---|---|---|
css`` | ✅ | ||
css(...) | ✅ | Generally used for object styles. | |
styled('div')`` syntax | ✅ | Both string and object styles work without this plugin. | |
styled.div`` syntax | ✅ | Supporting the shortcut syntax without the Babel plugin requires a large list of valid elements to be included in the bundle. | |
components as selectors | ✅ | Allows an emotion component to be used as a CSS selector. | |
Minification | ✅ | Any leading/trailing space between properties in your css and styled blocks is removed. This can reduce the size of your final bundle. | |
Dead Code Elimination | ✅ | Uglifyjs will use the injected /*#__PURE__*/ flag comments to mark your css and styled blocks as candidates for dead code elimination. | |
Static Extraction | ✅ | Generated CSS that is eligible for extraction can be moved to an external css file. | |
Source Maps | ✅ | When enabled, navigate directly to the style declaration in your javascript file. | |
css as Prop | ✅ | Convenient helper for calling css and appending the generated className during compile time. | |
Contextual Class Names | ✅ | Generated class names include the name of the variable or component they were defined in. |
In
const myStyles = css`
font-size: 20px;
@media (min-width: 420px) {
color: blue;
${css`
width: 96px;
height: 96px;
`};
line-height: 26px;
}
background: green;
${{ backgroundColor: 'hotpink' }};
`
Out
const myStyles = /* #__PURE__ */ css(
'font-size:20px;@media(min-width:420px){color:blue;',
/* #__PURE__ */ css('width:96px;height:96px;'),
';line-height:26px;}background:green;',
{ backgroundColor: 'hotpink' },
';'
)
yarn add --dev babel-plugin-emotion
or if you prefer npm
npm install --save-dev babel-plugin-emotion
.babelrc
(Recommended).babelrc
Without options:
{
"plugins": ["emotion"]
}
With options:
Defaults Shown
{
"plugins": [
[
"emotion",
{
"hoist": false,
"sourceMap": false,
"autoLabel": false,
"extractStatic": false,
"importedNames": {
"styled": "styled",
"css": "css",
"keyframes": "keyframes",
"injectGlobal": "injectGlobal",
"merge": "merge"
}
}
]
]
}
Recommended Setup
.babelrc
{
"env": {
"production": {
"plugins": [["emotion", { "hoist": true }]]
},
"development": {
"plugins": [
["emotion", { "sourceMap": true, "autoLabel": true }]
]
}
}
}
babel --plugins babel-plugin-emotion script.js
require('@babel/core').transform('code', {
plugins: ['babel-plugin-emotion']
})
hoist
boolean
, defaults to false
.
This option enables the following:
css
or styled
is hoisted.By hoisting the argument, or assigning the value to a variable, emotion is able to leverage the use of a WeakMapcache to increase performance. Users of object styles with css
prop will benefit the most from enabling this option.
In
const Sample = () => <div css={{ background: 'brown' }} />
Out
var _css = require('emotion').css;
var _ref = { background: 'brown' };
const Sample = () => <div className={_css(_ref)} />;
sourceMap
boolean
, defaults to false
.
This option enables the following:
autoLabel
boolean
, defaults to false
.
This option enables the following:
label
property to styles so that class names
generated by css
or styled
include the name of the variable the result is
assigned to.In
const brownStyles = css({ color: 'brown' })
Out
const brownStyles = /*#__PURE__*/ css({ color: 'blue' }, 'label:brownStyles;')
brownStyles
's value would be css-1q8eu9e-brownStyles
In
const Profile = () => {
const H1 = styled.h1({
borderRadius: '50%',
transition: 'transform 400ms ease-in-out',
boxSizing: 'border-box',
display: 'flex',
':hover': {
transform: 'scale(1.2)'
}
})
}
Out
const Profile = () => {
const H1 = /*#__PURE__*/ styled('h1', {
label: 'H1'
})({
borderRadius: '50%',
transition: 'transform 400ms ease-in-out',
boxSizing: 'border-box',
display: 'flex',
':hover': {
transform: 'scale(1.2)'
}
})
}
H1
's class name attribute would be css-13djram-H1
extractStatic
boolean
, defaults to false
.
This option enables the following:
importedNames
object
, defaults to
{
"styled": "styled",
"css": "css",
"keyframes": "keyframes",
"injectGlobal": "injectGlobal",
"merge": "merge"
}
This option enables the following:
instances
Array<string>
, defaults to
['emotion', 'react-emotion', 'preact-emotion']
This option allows babel-plugin-emotion
to know which imports to treat as
emotion imports and transform as such. This option is only required if you
use a custom instance of emotion created with create-emotion
or you're
importing emotion from somewhere other than the paths above. Relative paths are
resolved relative to process.cwd()
(the current working directory).
primaryInstance
string
, defaults to
'emotion'
This option allows babel-plugin-emotion
to know where to import emotion from
when it needs to import emotion. Currently this is only used for the css prop to
import css
and merge
but it could be used for other purposes in the future
so it's recommend to make sure that this instance exports everything returned
from createEmotion
,
an up-to-date example of this can be found in the emotion package's source.
Instead of using babel-plugin-emotion
, you can use emotion with babel-plugin-macros
. Add babel-plugin-macros
to your babel config and import whatever you want from emotion but add /macro
to the end. Currently every API except for the css prop is supported by the macro.
import styled from 'react-emotion/macro'
import {
css,
keyframes,
injectGlobal,
flush,
hydrate
} from 'emotion/macro'
FAQs
A recommended babel preprocessing plugin for emotion, The Next Generation of CSS-in-JS.
The npm package babel-plugin-emotion receives a total of 1,304,905 weekly downloads. As such, babel-plugin-emotion popularity was classified as popular.
We found that babel-plugin-emotion demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.