css-razor removes unused selectors. It accomplishes a similar task as uncss, but rather than loading a webpage with phantomjs and using document.querySelector to detect selector usage, css-razor loads the static HTML (easily generated by react) and parses it with cheeriojs to remove unused selectors.
- Helps trim down your CSS to the essentials
- Built for speed
- Supports multiple files
- Supports raw input
Install with npm.
npm install --save-dev css-razorYou can then use the cli.
css-razor build/css/index.css build/index.html --stdout > build/css/index.min.cssAnd you can even pass multiple globs!
css-razor build/css/*.css build/*.html --stdout > build/css/index.min.cssOr you can use the js api
const cssRazor = require('css-razor').default
cssRazor({
html: ['build/index.html'],
css: ['build/css/index.css'],
}, function(err, data) {
console.log(data.css)
})const postcssRazor = require('css-razor').postcss
postcss([
postcssRazor({
html: "<html>your html string</html>",
})
])
.process(css, {
from: 'index.css',
to: 'output.css'
})Below is an example of building an html file from a react app created with create-react-app. The resulting HTML file can then be used for server rendering and detecting selectors with css-razor.
index.js:
import App from './components/App'
import './index.css'
if (typeof window !== 'undefined') { // Web
ReactDOM.render(
<App />,
window.document.getElementById('root')
)
} else { // Node / server render
global.appToRender = App
}buildStatic.js:
const app = global.appToRender
const markup = ReactDOM.renderToString(ReactDOM.createElement(app));
const html = fs.readFileSync(HTML_FILE)
const newHtml = html.toString().split('<div id="root"></div>').join(
'<div id="root">' + markup + '</div>'
)
fs.writeFileSync(HTML_FILE, newHtml, 'utf8')- tests for raw and globs
- test for postcss plugin usage
- support for http maybe?