Write your styles with in JavsScript.
Install:
npm install css-js-loader value-loader
Add to your webpack.config.js
:
module.exports = {
...
module: {
loaders: [{
test: /\.css(\.js)?$/,
loaders: ['style-loader', 'css-loader'],
}, {
test: /\.css\.js$/,
loaders: ['css-js-loader', 'value-loader'],
}],
},
};
NOTE: You don't need to chain with value-loader per-se, but doing so gives you caching, nested dependency monitoring/reloading and the ability to use webpack's tree-shaking abilities.
css-js-loader
converts JS modules to CSS markup at runtime.
A .css.js
file:
export default {
'.blueText': {
color: 'blue',
fontSize: 12,
},
};
Yields:
.blueText {
color: blue;
font-size: 12px;
}
CSS classes can be defined as ES6 named exports.
export const blueText = { ... };
export const greenText = { ... };
export default {
'.redText': { ... },
};
Is equivalent to:
export default {
'.blueText': { ... },
'.greenText': { ... },
'.redText' { ... },
};
css-js-loader
works great with CSS Modules. Named class exports map directly to the class names that are imported in your component files.
Style file:
export const base = { ... };
export const inner = { ... };
Component file:
import React from 'react';
import {base, inner} from './component.css.js';
export default () =>
<div className={base}>
<div className={inner}>
...
</div>
</div>;