Skip to content

css-razor uses cheerio.js to parse static html to remove unused selectors in CSS.

License

Notifications You must be signed in to change notification settings

tscanlin/css-razor

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

css-razor

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

Getting Started

Install with npm.

npm install --save-dev css-razor

You can then use the cli.

css-razor build/css/index.css build/index.html --stdout > build/css/index.min.css

And you can even pass multiple globs!

css-razor build/css/*.css build/*.html --stdout > build/css/index.min.css

Or 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)
})

Usage with Postcss

const postcssRazor = require('css-razor').postcss

postcss([
    postcssRazor({
      html: "<html>your html string</html>",
    })
  ])
  .process(css, {
    from: 'index.css',
    to: 'output.css'
  })

React to HTML Example

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')

Todo

  • tests for raw and globs
  • test for postcss plugin usage
  • support for http maybe?

About

css-razor uses cheerio.js to parse static html to remove unused selectors in CSS.

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

Contributors 2

  •  
  •