0.0.8 • Published 7 years ago
rollup-plugin-stylus-js-modules v0.0.8
rollup-plugin-stylus-js-modules
A Rollup plugin to embed CSS into JS.
Installation
npm install --save-dev rollup-plugin-stylus-js-modules
Usage
1. Write a style with Stylus
// main.styl
.{public('header')}
font-size 14px
background-image url(../images/header.png)
border-bottom solid 1px #000000
.{private('headerItem')}
background-color rgba(0, 0, 0, 0.3)
border solid 1px #999999
2. Require the stylus-sheet in your script
You should call compileCSS()
imported from rollup-plugin-stylus-js-modules/compileCSS
in your script.
// main.js
import classes from './main.styl';
import compileCSS from 'rollup-plugin-stylus-js-modules/compileCSS';
compileCSS();
document.body.innerHTML = [
`<header class="${classes.header}">`,
...['one', 'two', 'three'].map((itemName) => {
return `<div class="${classes.headerItem}">${itemName}</div>`;
}),
'</header>'
].join('\n');
3. Rollup!
import { rollup } from 'rollup';
import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
import stylusJsModules from 'rollup-plugin-stylus-js-modules';
rollup({
entry: 'main.js',
plugins: [
// Put stylusJsModules before nodeResolve.
stylusJsModules({
// An object passed to postcss.
// You can use autoprefixer, cssnano, etc.
postcss: {...},
// An array of stylus plugins
stylusPlugins: [...]
}),
nodeResolve(...),
commonjs(...)
]
}).then(...)
You'll get the code like below.
class CSSStore {
// See cssStore.js
}
var cssStore = new CSSStore();
cssStore.add([ // This array represents the CSS blocks.
[
0, // ._0
[1, 2], // font-size: 14px
[3, 4, 5, 6, 7], // background-image: url("../images/header.png")
[8, 9, 10, 11] // border-bottom: solid 1px #000
],
[
12, // ._1
[13, 14, 5, 15, 7], // background-color: rgba(0,0,0,0.3)
[16, 9, 10, 17] // border: solid 1px #999
]
]);
var classes = {
"header": "_0",
"headerItem": "_1"
};
function decode(encodedRule, data) {
// See compileCSS.js
}
var compileCSS = function () {
const doc = document;
const styleSheet = doc.head.appendChild(doc.createElement('style')).sheet;
const data = [
"._0", // 0
"font-size", // 1
"14px", // 2
"background-image", // 3
"url", // 4
"(", // 5
"\"../images/header.png\"", // 6
")", // 7
"border-bottom", // 8
"solid", // 9
"1px", // 10
"#000", // 11
"._1", // 12
"background-color", // 13
"rgba", // 14
"0,0,0,0.3", // 15
"border", // 16
"#999" // 17
];
cssStore.listen((encodedRule) => {
styleSheet.insertRule(decode(encodedRule, data), styleSheet.cssRules.length);
});
};
compileCSS();
document.body.innerHTML = [
`<header class="${classes.header}">`,
...['one', 'two', 'three'].map((itemName) => {
return `<div class="${classes.headerItem}">${itemName}</div>`;
}),
'</header>'
].join('\n');
License
MIT