Giter Site home page Giter Site logo

lyd9607 / isomorphic-style-loader Goto Github PK

View Code? Open in Web Editor NEW

This project forked from kriasoft/isomorphic-style-loader

0.0 1.0 0.0 110 KB

CSS style loader for Webpack that is optimized for isomorphic (universal) web apps

Home Page: https://reactstarter.com

License: MIT License

JavaScript 100.00%

isomorphic-style-loader's Introduction

Isomorphic CSS style loader for Webpack

NPM version NPM downloads Build Status Coverage Status Dependency Status

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
// MyComponent.scss
.root { padding: 10px; }
.title { color: red; }
// MyComponent.js
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './MyComponent.scss';

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

export default withStyles(s)(MyComponent);        // <--

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 ReactDOM from 'react-dom';
import router from './router.js'; // <-- isomorphic router, see react-starter-kit for example

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 context = { insertCss: (...styles) => styles.forEach(style => css.add(style._getCss())); };
  router.dispatch({ ...req, context }).then((component, state) => {
    const body = ReactDOM.renderToString(component);
    const html = `<!doctype html>
      <html>
        <head>
          <script async src="/client.js"></script>
          <style type="text/css">${[...css].join('')}</style>
        </head>
        <body>
          <div id="root">${body}</div>
        </body>
      </html>`;
    res.status(state.statusCode).send(html);
  }).catch(next);
});

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">
      .MyComponent_root_Hi8 { padding: 10px; }
      .MyComponent_title_e9Q { color: red; }
    </style>
  </head>
  <body>
    <div id="root">
      <div class="MyComponent_root_Hi8" data-reactid=".cttboum80" data-react-checksum="564584530">
        <h1 class="MyComponent_title_e9Q" data-reactid=".cttboum80.0">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.

Hot Reload

You can activate hot module reload for style by setting the debug option to true in your webpack configuration. If you are using webpack 2, you need to supply it though the LoaderOptionsPlugin because the debug option has been removed.

Related Projects

License

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


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

isomorphic-style-loader's People

Contributors

alexanderchr avatar arnoldstoba avatar dsernst avatar everettss avatar extg avatar frenzzy avatar hishayness avatar ifwu avatar inian avatar jasonsanjose avatar jorrit avatar koistya avatar nodkz avatar plemarquand avatar rivertam avatar tevcef avatar tinder-rhsiao avatar vishalvijay avatar yurynix avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.