Webpack loader for using external CSS files with Material UI.
Install | Usage | Description | Features | Demo | Linting | Help out
npm install css-to-mui-loader
- [email protected] and up supports material-ui v4
- [email protected] and down supports material-ui v3
- [email protected] and up supports jss v10
- [email protected] and down supports jss v9
styles.css
.button {
background: $(theme.palette.primary.main);
padding: 2su; /* Material UI spacing units */
}
.button:hover {
background: $(theme.palette.primary.light);
}
MyComponent.js
import Button from '@material-ui/core/Button';
import { withStyles } from '@material-ui/core/styles';
import styles from './styles.css';
const MyComponent = withStyles(styles)(({ classes }) => (
<Button className={classes.button}>
Click Me
</Button>
));
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [ 'css-to-mui-loader' ]
}
]
}
}
The css-to-mui-loader
allows you to write external CSS files then import them for use in your Material UI components. It provides shortcuts for accessing the Material UI theme within the CSS itself.
Why?
- CSS is more concise
- Designers don't want to write JS
- You can copy/paste CSS directly from Chrome Inspector
- You still get component-scoped CSS and a centralized theme
Provides custom unit for Material UI spacing
.spacing {
padding: 10su; /* Equal to theme.spacing.unit * 10 */
}
Provides access to the Material UI theme
.theme {
color: $(theme.palette.primary.main);
z-index: $(theme.zIndex.appBar);
}
Supports media queries using the Material UI theme breakpoints
@media $(theme.breakpoints.down('sm')) {
.media {
display: none;
}
}
Allows Material UI theme objects to be included as mixins
.mixins {
-mui-mixins: theme.typography.display4, theme.shape;
}
Supports classes, child selectors and pseudo-classes
.parent.qualifier .child:hover * {
padding: 10px;
}
Supports CSS variables
:root {
--small-spacing: 2su;
}
.variables {
margin: var(--small-spacing);
}
Supports keyframes
@keyframes my-animation {
0% { opacity: 0; }
100% { opacity: 1; }
}
.keyframes {
animation: my-animation 1s ease-in-out;
}
If you want to know what the loader output looks like, take a look at the tests.
Check out the css-to-mui-loader-example repository for a bare-bones demo bootstrapped with create-react-app.
Some linters might complain about the custom syntax, but there are usually rules you can enable to address this. For example, the following .stylelintrc
for stylelint does not raise any errors with the custom css-to-mui-loader
syntax:
{
"extends": "stylelint-config-standard",
"plugins": [
"stylelint-order"
],
"rules": {
"function-name-case": null,
"property-no-unknown": [
true,
{
"ignoreProperties": ["-mui-mixins"]
}
],
"unit-no-unknown": [
true,
{
"ignoreUnits": ["/^su$/"]
}
]
}
}
Pull requests, issues, complaints and suggestions are all welcome.