Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

isomorphic-style-loader-forked

mikeyshing88108MIT5.1.5

CSS style loader for Webpack optimized for critical path CSS rendering and isomoprhic web apps

webpack, webpack-loader, webpack loader, loader, css, scss, style, styles, style-loader, style loader, react, reactjs, isomorphic, universal, critical-css, critical css, critical-path-css, critical path css

readme

Isomorphic CSS style loader for Webpack

NPM version NPM downloads Library Size Online Chat

CSS style loader for Webpack that works similarly to style-loader, but is optimized for critical path CSS rendering and also works great in the context of isomorphic apps. It provides two helper methods on to the styles object - ._insertCss() (injects CSS into the DOM) and ._getCss() (returns a CSS string).

See getting started  |  changelog  |  Join #react-starter-kit chat room on Gitter to stay up to date

How to Install

$ npm install isomorphic-style-loader --save-dev

Getting Started

Webpack configuration:

module.exports = {
  /* ... */
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'isomorphic-style-loader',
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1
            }
          },
          'postcss-loader'
        ]
      }
    ]
  }
  /* ... */
}

Note: Configuration is the same for both client-side and server-side bundles. For more information visit https://webpack.js.org/configuration/module/.

React component example:

/* App.css */
.root { padding: 10px }
.title { color: red }
/* App.js */
import React from 'react'
import withStyles from 'isomorphic-style-loader/withStyles'
import s from './App.scss'

function App(props, context) {
  return (
    <div className={s.root}>
      <h1 className={s.title}>Hello, world!</h1>
    </div>
  )
}

export default withStyles(s)(App) // <--

P.S.: It works great with CSS Modules! Just decorate your React component with the withStyles higher-order component, and pass a function to your React app via insertCss context variable (see React's context API) that either calls styles._insertCss() on a client or styles._getCss() on the server. See server-side rendering example below:

import express from 'express'
import React from 'react'
import ReactDOM from 'react-dom'
import StyleContext from 'isomorphic-style-loader/StyleContext'
import App from './App.js'

const server = express()
const port = process.env.PORT || 3000

// Server-side rendering of the React app
server.get('*', (req, res, next) => {
  const css = new Set() // CSS for all rendered React components
  const insertCss = (...styles) => styles.forEach(style => css.add(style._getCss()))
  const body = ReactDOM.renderToString(
    <StyleContext.Provider value={{ insertCss }}>
      <App />
    </StyleContext.Provider>
  )
  const html = `<!doctype html>
    <html>
      <head>
        <script src="client.js" defer></script>
        <style>${[...css].join('')}</style>
      </head>
      <body>
        <div id="root">${body}</div>
      </body>
    </html>`
  res.status(200).send(html)
})

server.listen(port, () => {
  console.log(`Node.js app is running at http://localhost:${port}/`)
})

It should generate an HTML output similar to this one:

<html>
  <head>
    <title>My Application</title>
    <script async src="/client.js"></script>
    <style type="text/css">
      .App_root_Hi8 { padding: 10px }
      .App_title_e9Q { color: red }
    </style>
  </head>
  <body>
    <div id="root">
      <div class="App_root_Hi8">
        <h1 class="App_title_e9Q">Hello, World!</h1>
      </div>
    </div>
  </body>
</html>

Regardless of how many styles components there are in the app.js bundle, only critical CSS is going to be rendered on the server inside the <head> section of HTML document. Critical CSS is what actually used on the requested web page, effectively dealing with FOUC issue and improving client-side performance. CSS of the unmounted components will be removed from the DOM.

Then on client-side use hydrate to make your markup interactive:

import React from 'react'
import ReactDOM from 'react-dom'
import StyleContext from 'isomorphic-style-loader/StyleContext'
import App from './App.js'

const insertCss = (...styles) => {
  const removeCss = styles.map(style => style._insertCss())
  return () => removeCss.forEach(dispose => dispose())
}

ReactDOM.hydrate(
  <StyleContext.Provider value={{ insertCss }}>
    <App />
  </StyleContext.Provider>,
  document.getElementById('root')
)

React Hooks Support:

You can also use useStyles inside your React Functional Components, instead of using withStyles. Please note that you still need to pass insertCss function to StyleContext.Provider from top of the tree.

import React from 'react'
import useStyles from 'isomorphic-style-loader/useStyles'
import s from './App.scss'

const App = (props) => {
  useStyles(s);
  return (
    <div className={s.root}>
      <h1 className={s.title}>Hello, world!</h1>
    </div>
  )
};

export default App;

License

The MIT License © 2015-present Kriasoft (@kriasoft). All rights reserved.


Made with ♥ by Konstantin Tarkus (@koistya, blog), Vladimir Kutepov (frenzzy) and contributors

changelog

Isomorphic Style Loader Change Log

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog and this project adheres to Semantic Versioning.

v5.1.0 - 2019-05-27

  • Add useStyles(style) hook for React.js (#159)

v5.0.0 - 2019-02-18

  • Migration to new Context API introduced in React.js 16.3.0 (#141)
    - import withStyles from 'isomorphic-style-loader/lib/withStyles';
    + import withStyles from 'isomorphic-style-loader/withStyles';
  • Allow to override style id prefix with _insertCss({ prefix: 's' }) (#124)
  • Update hoist-non-react-statics from v2 to v3
  • Remove babel-runtime dependency

v4.0.0 - 2017-08-14

  • Bump hoist-non-react-statics and babel-runtime
  • Remove Babel and ESLint sections from package.json
  • Add a safety check on componentWillUnmount of withStyles to only setTimeout if this.removeCss is defined (#104)
  • Call the insertCss with the spread operator (#101)

v3.0.0 - 2017-07-07

  • Bump hoist-non-react-statics (#97)

v2.0.0 - 2017-04-20

  • Pull PropTypes from prop-types package for compatibility with React 15.3.0 and higher (#90)

v1.1.0 - 2016-10-30

  • Disable source maps in IE9 and below, to prevent runtime errors in development mode (#69)
  • Improve source maps support by making sourceURL field unique (#44, #69)
  • Add access to content to deduplicate server-side generated styles (#56)
  • Use HMR (Hot Module Replacement) if available, no debug option required (#57)
  • Use hoist-non-react-statics to copy non-react specific statics from a child to a parent component inside withStyles HOC (Higher-Order Component) (#38)
  • Add CHANGELOG.md file with the past and future (planned) changes to the project

v1.0.0 - 2016-04-15

  • Improve comparability with Hot Module Replacement (HMR) (#33)
  • Add support of ES2015+ decorator syntax, e.g. @withStyles(s) class MyComponent extends Component { .. } PR#21 (BREAKING CHANGE)

v0.0.12 - 2016-03-04

  • Fix style not getting removed for multiple instance (#23)