Security News
JSR Working Group Kicks Off with Ambitious Roadmap and Plans for Open Governance
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
The stylis npm package is a lightweight CSS preprocessor that allows developers to write nested CSS, use mixins, and perform other transformations before the CSS is compiled. It is particularly designed to be used with CSS-in-JS libraries and offers a middleware architecture to extend its capabilities.
CSS Preprocessing
Stylis allows you to write nested CSS rules, which it will then flatten into valid CSS. The code sample demonstrates how to preprocess a nested CSS string.
const stylis = require('stylis');
const css = `
.parent {
color: red;
.child {
color: blue;
}
}
`;
const output = stylis('.parent', css);
console.log(output);
Prefixing
Stylis automatically adds vendor prefixes to CSS rules when necessary. The code sample shows how to automatically prefix the 'display: flex;' rule.
const stylis = require('stylis');
const css = `display: flex;`;
const output = stylis('', css);
console.log(output);
Middleware
Stylis supports middleware, allowing you to intercept and transform CSS at various stages of processing. The code sample demonstrates a middleware that changes the color property for elements with the class '.button'.
const stylis = require('stylis');
stylis.use((context, content, selectors, parents, line, column, length) => {
if (context === 2 && selectors[0] === '.button') {
return content.replace('color: red', 'color: blue');
}
});
const css = `.button { color: red; }`;
const output = stylis('', css);
console.log(output);
PostCSS is a tool for transforming CSS with JavaScript plugins. It is more established and has a larger ecosystem of plugins compared to stylis. PostCSS can be used for a wide range of tasks including linting, optimization, and applying polyfills.
Sass is a mature and feature-rich CSS extension language that allows for variables, nesting, mixins, and more. Unlike stylis, Sass has its own syntax and requires compilation to CSS, but it offers a more comprehensive set of features for styling.
Less is another CSS pre-processor that extends the capabilities of CSS with variables, mixins, functions, and more. It is similar to Sass and offers a different syntax and feature set compared to stylis.
A Light–weight CSS Preprocessor.
<script src=stylis.js></script>
<script src=unpkg.com/stylis></script>
npm install stylis --save
a { &:hover {} }
const declaration = {
value: 'color:red;',
type: 'decl',
props: 'color',
children: 'red',
line: 1, column: 1
}
const comment = {
value: '/*@noflip*/',
type: 'comm',
props: '/',
children: '@noflip',
line: 1, column: 1
}
const ruleset = {
value: 'h1,h2',
type: 'rule',
props: ['h1', 'h2'],
children: [/* ... */],
line: 1, column: 1
}
const atruleset = {
value: '@media (max-width:100), (min-width:100)',
type: '@media',
props: ['(max-width:100)', '(min-width:100)'],
children: [/* ... */],
line: 1, column: 1
}
import {compile, serialize, stringify} from 'stylis'
serialize(compile(`h1{all:unset}`), stringify)
compile('h1{all:unset}') === [{value: 'h1', type: 'rule', props: ['h1'], children: [/* ... */]}]
compile('--foo:unset;') === [{value: '--foo:unset;', type: 'decl', props: '--foo', children: 'unset'}]
tokenize('h1 h2 h3 [h4 h5] fn(args) "a b c"') === ['h1', 'h2', 'h3', '[h4 h5]', 'fn', '(args)', '"a b c"']
serialize(compile('h1{all:unset}'), stringify)
import {compile, serialize, stringify, middleware, prefixer } from 'stylis';
serialize(compile('div{display:flex;}'), middleware([prefixer, stringify]))
The middleware helper is a convenient helper utility, that for all intents and purposes you can do without if you intend to implement your own traversal logic. The stringify
middleware is one such middleware that can be used in conjunction with it.
Elements passed to middlewares have a root
property that is the immediate root/parent of the current element in the compiled output, so it references the parent in the already expanded CSS-like structure. Elements have also parent
property that is the immediate parent of the current element from the input structure (structure representing the input string).
serialize(compile('h1{all:unset}'), middleware([(element, index, children) => {
assert(children === element.root.children && children[index] === element.children)
}, stringify])) === 'h1{all:unset;}'
The abstract syntax tree also includes an additional return
property for more niche uses.
serialize(compile('h1{all:unset}'), middleware([(element, index, children, callback) => {
if (element.type === 'decl' && element.props === 'all' && element.children === 'unset')
element.return = 'color:red;' + element.value
}, stringify])) === 'h1{color:red;all:unset;}'
serialize(compile('h1{all:unset}'), middleware([(element, index, children, callback) => {
if (element.type === 'rule' && element.props.indexOf('h1') > -1)
return serialize([{...element, props: ['h2', 'h3']}], callback)
}, stringify])) === 'h2,h3{all:unset;}h1{all:unset;}'
serialize(compile('h1{all:unset}'), middleware([stringify, (element, index, children) => {
assert(element.return === 'h1{all:unset;}')
}])) === 'h1{all:unset;color:red;}'
The middlewares in src/Middleware.js dive into tangible examples of how you might implement a middleware, alternatively you could also create your own middleware system as compile
returns all the nessessary structure to fork from.
CSS variables are supported but a note should be made about the exotic use of css variables. The css spec mentions the following
The allowed syntax for custom properties is extremely permissive. The production matches any sequence of one or more tokens, so long as the sequence does not contain , , unmatched <)-token>, <]-token>, or <}-token>, or top-level tokens or tokens with a value of "!".
That is to say css variables according to the spec allows: --foo: if(x > 5) this.width = 10;
and while this value is obviously useless as a variable, and would be invalid in any normal property, it still might be read and acted on by JavaScript and this is supported by Stylis, however things become slightly undefined when we start to include the {
and }
productions in our use of exotic css variables.
For example consider the following: --foo: {};
While this is valid CSS and supported. It is unclear what should happen when the rule collides with the implicit block termination rule that allows i.e h1{color:red}
(notice the omitted semicolon) to also be a valid CSS production. This results in the following contradiction in: h1{--example: {}
is it to be treated as h1{--foo:{;}
or h1{--foo:{}
the later of which is an unterminated block or in the following: h1{--foo:{} h1{color:red;}
should it be h1 {--foo:{}h1{color:red;};
where {}h1{color:red;
is part of the css variable --foo
and not a new rule or should it be something else?
Nevertheless Stylis still supports the exotic forms highlighted in the spec, however you should consider it as a general rule to delimit such exotic uses of variables in strings or parentheses i.e: h1{--foo:'{'}
or h1{--foo:({)}
.
Stylis is at-least 2X faster than its predecesor.
Stylis is MIT licensed.
FAQs
A Light–weight CSS Preprocessor
We found that stylis demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 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
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.
Security News
Research
An advanced npm supply chain attack is leveraging Ethereum smart contracts for decentralized, persistent malware control, evading traditional defenses.
Security News
Research
Attackers are impersonating Sindre Sorhus on npm with a fake 'chalk-node' package containing a malicious backdoor to compromise developers' projects.