Code Monkey home page Code Monkey logo

used-styles's Introduction

used-styles


Get all the styles, you have used to render a page.
(without any puppeteer involved)

Build Status NPM version

Bundler and framework independent CSS part of SSR-friendly code splitting

Detects used css files from the given HTML, and/or inlines critical styles. Supports sync or stream rendering.

Read more about critical style extraction and this library: https://dev.to/thekashey/optimising-css-delivery-57eh

  • ๐Ÿš€ Super Fast - no browser, no jsdom, no runtime transformations
  • ๐Ÿ’ช API - it's no more than an API - integrates with everything
  • ๐Ÿค Works with strings and streams
  • โณ Helps preloading for the "real" style files

Works in two modes:

  • ๐Ÿš™ inlines style rules required to render given HTML - ideal for the first time visitor
  • ๐Ÿ‹๏ธโ€โ™€๏ธinlines style files required to render given HTML - ideal for the second time visitor (and code splitting)

Critical style extraction:

  • ๐Ÿงฑ will load all used styles at the beginning of your page in a string mode
  • ๐Ÿ’‰ will interleave HTML and CSS in a stream mode. This is the best experience possible

How it works

  1. Scans all .css files, in your build directory, extracting all style rules names.
  2. Scans a given html, finding all the classes used.
  3. Here there are two options: 3a. Calculate all style rules you need to render a given HTML. 3b. Calculate all the style files you have send to a client.
  4. Injects <styles> or <links>
  5. After the page load, hoist or removes critical styles replacing them by the "real" ones.

Limitation

For the performance sake used-styles inlines a bit more styles than it should - it inlines everything it would be "not fast" to remove.

  • inlines all @keyframe animations
  • inlines all html, body and other tag-based selectors (hello css-reset)
  • undefined behavior if @layer a,b,c is used multiple times

Speed

Speed, I am speed!

For the 516kb page, which needs 80ms to renderToString(React) resulting time for the getCriticalRules(very expensive operation) would be around 4ms.

API

Discovery API

Use it to scan your dist/build folder to create a look up table between classNames and files they are described in.

  1. discoverProjectStyles(buildDirrectory, [filter]): StyleDef - generates class lookup table

    you may use the second argument to control which files should be scanned

filter is very important function here. It takes fileName as input, and returns false, true, or a number as result. False value would exclude this file from the set, true - add it, and number would change the order of the chunk. Keeping chunk ordered "as expected" is required to preserve style declaration order, which is important for many existing styles.

// with chunk format [chunkhash]_[id] lower ids are potentialy should be defined before higher
const styleData = discoverProjectStyles(resolve('build'), (name) => {
  // get ID of a chunk and use it as order hint
  const match = name.match(/(\d)_c.css/);
  return match && +match[1];
});

โš ๏ธ generally speaking - this approach working only unless there are no order-sensive styles from different chunks applied to a single DOM Element. Quite often it never happen, but if you are looking for a better way - follow to #26 โ˜ฃ๏ธ

  1. loadStyleDefinitions is a "full control API", and can used to feed used-styles with any custom data, for example providing correct critical css extraction in dev mode (no files written on disk)
return loadStyleDefinitions(
  /*list of files*/ async () => cssFiles,
  /*data loader*/ (file) => fetchTxt(`http://localhost:${process.env.DEV_SERVER_PORT}/${file}`)
  /*filter and order */ // (file) => order.indexOf(cssToChunk[file])
);

Scanners

Use to get used styled from render result or a stream

  1. getUsedStyles(html, StyleDef): string[] - returns all used files, you will need to import them

  2. getCriticalStyles(html, StyleDef) : string - returns all used selectors and other applicable rules, wrapped with style

  3. getCriticalRules(html, StyleDef): string - the same, but without <style> tag, letting you handle in a way you want

  4. createStyleStream(lookupTable, callback(fileName):void): TransformStream - creates Transform stream - will inject <links

  5. createCriticalStyleStream(lookupTable, callback(fileName):void): TransformStream - creates Transform stream - will inject <styles.

React

There are only two things about react:

  1. to inline critical styles use another helper - getCriticalRules which does not wrap result with style letting you do it
import { getCriticalRules } from 'used-styles';

const Header = () => (
  <style data-used-styles dangerouslySetInnerHTML={{ __html: getCriticalRules(markup, styleData) }} />
);
  1. React produces more valid code, and you might enable optimistic optimization, making used-styles a bit faster.
import { enableReactOptimization } from 'used-styles';

enableReactOptimization(); // just makes it a but faster

Example

Demo

Static rendering

There is nothing interesting here - just render, just getUsedStyles.

import {discoverProjectStyles, getUsedStyles} from 'used-styles';


// generate lookup table on server start
const stylesLookup = discoverProjectStyles('./build');

async function MyRender() {
  await stylesLookup;// it is "thenable"
  // render App
  const markup = ReactDOM.renderToString(<App/>)
  const usedStyles = getUsedStyles(markup, stylesLookup);

  usedStyles.forEach(style => {
    const link = `<link  rel="stylesheet" href="build/${style}">\n`;
    // or
    const link = `<link rel="prefetch" as="style" href="build/${style}">\n`;
    // append this link to the header output or to the body
  });

// or

  const criticalCSS = getCriticalStyles(markup, stylesLookup);

// append this link to the header output

Any bulk CSS operations, both getCriticalStyles and getUsedStyles are safe and preserve the selector rule order. You may combine both methods, to prefetch full styles, and inline critical CSS.

! Keep in mind - calling two functions is as fast, as calling a single one !

Stream rendering

Please keep in mind - stream rendering in NOT SAFE in terms of CSS, as long as it might affect the ordering of selectors. Only pure BEM and Atomic CSS are "safe", just some random CSS might be not compatible. Please test results before releasing into production.

If you do not understand why and how selector order is important - please do not use stream transformer.

Stream rendering is much harder, and much more efficient, giving you the best Time-To-First-Byte. And the second byte.

Stream rendering could be interleaved(more efficient) or block(more predictable).

Interleaved Stream rendering

In case or React rendering you may use interleaved streaming, which would not delay TimeToFirstByte. It's quite similar how StyledComponents works

import express from 'express';
import { 
  discoverProjectStyles, 
  loadStyleDefinitions,
  createCriticalStyleStream, 
  createStyleStream,
  createLink,
} from 'used-styles';

const app = express();

// generate lookup table on server start
const stylesLookup = isProduction
  ? discoverProjectStyles('./dist/client') 
  // load styles for development
  : loadStyleDefinitions(async () => []);

app.use('*', async (req, res) => {
  await stylesLookup;

  try {
    const renderApp = (await import('./dist/server/entry-server.js')).default;

    // create a style steam
    const styledStream = createStyleStream(stylesLookup, (style) => {
      // _return_ link tag, and it will be appended to the stream output
      return createLink(`dist/${style}`) // <link href="dist/mystyle.css />
    });

    // or create critical CSS stream - it will inline all styles
    const styledStream = createCriticalStyleStream(stylesLookup); // <style>.myClass {...

    await renderApp({ res, styledStream });
  } catch (err) {
    res.sendStatus(500);
  }
});
// entry-server.js
import React from 'react';
import { renderToPipeableStream } from 'react-dom/server';
import App from './App';

const ABORT_DELAY = 10000;

async function renderApp({ res, styledStream }) {
  let didError = false;
  
  const { pipe, abort } = renderToPipeableStream(
    <React.StrictMode>
      <App />
    </React.StrictMode>,
    {
      onShellError() {
        res.sendStatus(500);
      },
      onAllReady() {
        res.status(didError ? 500 : 200);
        res.set({ 'Content-Type': 'text/html' });

        // allow client to start loading js bundle
        res.write(`<!DOCTYPE html><html><head><script defer src="client.js"></script></head><body><div id="root">`);

        styledStream.pipe(res, { end: false });
        
        // start by piping react and styled transform stream
        pipe(styledStream);

        styledStream.on('end', () => {
          res.end('</div></body></html>');
        });
      },
      onError(error) {
        didError = true;
        console.error(error);
      }
    },
  );

  setTimeout(() => {
    abort();
  }, ABORT_DELAY);
}

export default renderApp;

!! THIS IS NOT THE END !! Interleaving links and react output would break a client side rehydration, as long as _ injected_ links were not rendered by React, and not expected to present in the "result" HTML code.

You have to move injected styles out prior rehydration.

import React from 'react';
import { moveStyles } from 'used-styles/moveStyles';
import ReactDOM from 'react-dom/client';
import App from './App';

// Call before `ReactDOM.hydrateRoot`
moveStyles()

ReactDOM.hydrateRoot(
  document.getElementById('root'),
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

You might want to remove styles after rehydration to prevent duplication. Double check that corresponding real CSS is loaded.

import { removeStyles } from 'used-styles/moveStyles';

removeStyles();

Block rendering

Not sure this is a good idea

Idea is to:

  • push initial line to the browser, with the-main-script inside
  • push all used styles
  • push some html between styles and content
  • push content
  • push closing tags

That's all are streams, concatenated in a right order. It's possible to interleave them, but that's is not expected buy a hydrate.

import { discoverProjectStyles, createStyleStream, createLink } from 'used-styles';
import MultiStream from 'multistream';

// .....
// generate lookup table on server start
const lookup = await discoverProjectStyles('./build'); // __dirname usually

// small utility for "readable" streams
const readableString = (string) => {
  const s = new Readable();
  s.push(string);
  s.push(null);
  s._read = () => true;
  return s;
};

// render App
const htmlStream = ReactDOM.renderToNodeStream(<App />);

// create a style steam
const styledStream = createStyleStream(lookup, (style) => {
  // emit a line to header Stream
  headerStream.push(createLink(`dist/${style}`));
  // or
  headerStream.push(`<link href="dist/${style}" rel="stylesheet">\n`);
});

// allow client to start loading js bundle
res.write(`<!DOCTYPE html><html><head><script defer src="client.js"></script>`);

const middleStream = readableString('</head><body><div id="root">');
const endStream = readableString('</head><body>');

// concatenate all steams together
const streams = [
  headerStream, // styles
  middleStream, // end of a header, and start of a body
  styledStream, // the main content
  endStream, // closing tags
];

MultiStream(streams).pipe(res);

// start by piping react and styled transform stream
htmlStream.pipe(styledStream, { end: false });
htmlStream.on('end', () => {
  // kill header stream on the main stream end
  headerStream.push(null);
  styledStream.end();
});

This example is taken from Parcel-SSR-example from react-imported-component.

Hybrid usage

The advanced pattern described in Optimizing CSS Delivery article proposes to:

  • inline critical CSS for a first time customers
  • use cached .css files for recurring

This library does not provide a way to distinguish "one" cohort of customers from another, although, provides an API to optimize the delivery.

  • use createCriticalStyleStream/getCriticalStyles to inline critical CSS
  • use createStyleStream/getUsedStyles to use .css files
  • use alterProjectStyles with filter options to create two different sets of styles: not yet cache set for critical styles, and the cached ones for used.
  • yes - you have to use or two transformers, or call two functions, one after another.

Theoretically - all styles "critical" now, are "cached" ones next view.

Performance

Almost unmeasurable. It's a simple and single RegExp, which is not comparable to the React Render itself.

Comparison

comparing with tools listed at Google's Optimize CSS Delivery

  • penthouse - a super slow puppetter based solution. No integration with a real run time renderer is possible. Generates one big style block at the beginning of a file.

  • critical - a super slow puppetter based solution. Able to extract critical style "above the fold".

  • inline-critical - slow jsdom based solution. Generates one big style block at the beginning of a file, and replaces all other links by async variants. However, it does not detect any critical or used styles in provided HTML - HTML is used only as a output target. ๐Ÿ‘Ž

  • critters-webpack-plugun - is the nearest analog of used-styles, build on almost same principles.

used-styles is faster that libraries listed above, and optimized for multiple runs.

License

MIT

used-styles's People

Contributors

alexandrhoroshih avatar hnrchrdl avatar ibadichan avatar nickolaj-jepsen avatar raminjafary avatar shlensky avatar thekashey avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

used-styles's Issues

Action required: Greenkeeper could not be activated ๐Ÿšจ

๐Ÿšจ You need to enable Continuous Integration on Greenkeeper branches of this repository. ๐Ÿšจ

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didnโ€™t receive a CI status on the greenkeeper/initial branch, itโ€™s possible that you donโ€™t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how itโ€™s configured. Make sure it is set to run on all new branches. If you donโ€™t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, youโ€™ll need to re-trigger Greenkeeperโ€™s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

Make CLI

It will be great if you will add CLI for that tool

renderToNodeStream example

In Readme file you mentioned using of this Readable :

// small utility for "readable" streams
const readable = () => {
  const s = new Readable();
  s._read = () => true;
  return s;
};

But there is no usage for this variable , is it correct?

Rule filtering

Not all rules are welcomed for critical extraction. Let's keep @media as a separate problem, but we can safely remove:

  • :focus
  • :hover
  • random test-facing selector

We can't remove:

  • :disabled
  • :before / :after
  • :first-/:nth-
  • many others

Unlock selectors on discovery

Currently, any selector will be inlined when the last part of it is found, however we can accept only those ones, which first part was found before as well

.dark-theme .header
โฌ‡๏ธ
<div class='header'>does nothing</div>

<div class="dark-theme"> "unlocks .dark-theme"
 <div class='header'>uses style</div> 

`:not()` pseudo selector support

At now classes with :not() pseudo selector ignored, simple example:

<!-- html -->
<div class="test"></div>
/* css */
.test {
  display: inline-block;
}

.test:not(.some) {
  padding: 10px;
}

getCriticalRules for this data will produce styles without .test:not(.some) selector:

.test {
  display: inline-block;
}

missing css

we use this library in our project, but find missing some style, the css selector is like this:

.downloads-1u5ev.downloadsFallback-1btP7 .logo-2Dv5-,.downloads-1u5ev.downloadsV5-3wG0y .logo-2Dv5- {
    margin-left: .08rem;
    position: relative;
    width: .5rem;
    height: .5rem
}
<div class="downloads-1u5ev downloadsV5-3wG0y"><svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" class="logo-2Dv5-" role="img" fill="#fb7701" stroke="none" stroke-width="18.962962962962962" preserveAspectRatio="none"></svg></div>

could you fix this problem?

Correct rules order

Right now documentation proposed the following way to intent the "right" order of styles

// with chunk format [chunkhash]_[id] lower ids are potentialy should be defined before higher
const styleData = discoverProjectStyles(resolve('build'), name => {
  // get ID of a chunk and use it as order hint
  const match = name.match(/(\d)_c.css/);
  return match && +match[1];
});

which is generally not correct, even if working in the majority of the use cases.

Issue with styles injected into select element

Another issue popped up, where styles are injected into a <select> element, but are not wrapped into a <style> tag, which means moveStyles won't recognize them, so they are not moved into head before hydration, and therefore breaking hydration.

image

Anything we can do about this to fix it? :)

Below The Fold

Based on inspiration from @mikesherov - https://twitter.com/theKashey/status/1403516526955679748


right now there are two modes:

  • block mode, when styles are extracted from the whole HTML
  • stream mode, when styles are extracted from every single rendering "chunk", which is basically unknown

Proposal

  • add Fold components, which will act as a "separator" between "block-extracted" styles
    • in block mode styles will be separated into:
      • unmatchable
      • above the Fold
      • below the Fold
    • in stream mode styles, as well as HTML will be accumulated between two sibling Folds, providing better control on extraction if needed.

Usage of CSSO

Check the ability to use CSSO to minify the output.
However - it might not optimize anything, as long as styles are already minimised.

media query support

are media queries supposed to be supported by this library? I guess not properly, I do not seem to get any critical css for selectors that are behind media queries.

CSS Cascade Layers support

Relates to #26

Hello and thank you for the awesome library! ๐Ÿ‘‹

Since CSS Cascade Layers support is gettng better in the browsers, i was wondering if there any plans to support this feature?

Right now it seems to be not supported:
I wrote some snapshot tests and current version of used-styles just adds all @layer-related stuff into the critiical styles without considering, if any of styles in that layer are actually used

So it looks like that some special handling, like it is done for @media rules, is needed ๐Ÿค”

There is a polyfill for CSS Layers and it does work much better with used-styles, but since this feature is getting wider support in the browsers (90% according to caniuse), i think, it is a good time to introduce a native support

CSS Layers are pretty cool, since by using it

Authors can create layers to represent element defaults, third-party libraries, themes, components, overrides, and other styling concerns โ€“ and are able to re-order the cascade of layers in an explicit way, without altering selectors or specificity within each layer, or relying on source-order to resolve conflicts across layers

which is basically a native CSS solution to issue #26

What do you think?

Don't inline "non-selectors" from "non-used" files

Right now used-styles inlines everything it can't "match" - font declarations and animations.
However - it might do it only for the limited set of files, which might be known from the "bunder integration" for example

It's already partially supported via filter filters in different APIs, and should be just better documented and tested

  • shares the implementation with #14

Don't inline all keyframes

Sample code from critters

// detect used keyframes
            if (decl.property === 'animation' || decl.property === 'animation-name') {
              // @todo: parse animation declarations and extract only the name. for now we'll do a lazy match.
              const names = decl.value.split(/\s+/);
              for (let j = 0; j < names.length; j++) {
                const name = names[j].trim();
                if (name) criticalKeyframeNames.push(name);
              }
            }

Override inline styles

Hello. I want to describe a simple case. Imagine:
Page on an initial state has simple div with class my-box and style

.my-box {
  margin: 0 auto;
}

We already get this style as critical in <style></style> tag.
Later we did API-request add '.extra-class' to our div with 'my-box' class.

.extra-class {
  margin: 10px 20px;
}

Now we have .my-box class in style tag with hight priority, .my-box and .extra-class in CSS file. And margin from .extra-class will be ignore.
Does exist some way to manage inline styles maybe? For ex:

  1. Prepare multiple style tags by getCriticalStyles split by source with data-used-styles
  2. Remove this style after load equal CSS file.

What kind of pitfalls did I miss?

[Q/A] "used-style" is simple ?

I read that you scan html and css but maybe isnt so easy ...
and also put 'hybrid', server side rendering and whatever ...

Can you tell me if you can expose a "main" function with html string (or whatever), css string (or whatever) as input
and then have as output, a css used ?

Styles with same selector and content but different media are missing

Given

.content {    
}

@media screen and (min-width: 768px) {
    .content {
        grid-column:1/6
    }
}

@media screen and (min-width: 1024px) {
    .content {
        grid-column:1/7
    }
}

/*this style duplicates 768 one, had the hash before*/
@media screen and (min-width: 1600px) {
    .content {
        grid-column:1/6
    }
}

The last style will be missing due to hash collide between 768px and 1600px media

Usage example for CRA

Would be awesome have an example of usage of this package together with cra (create-react-app). I could help with the ssr/server part of this, if needed.

Cloudflare workers compatibility

Hello ๐Ÿ‘‹๐Ÿป

We are wanting to use this library with Cloudflare workers, and thes during SSR we cannot scan the directory.

export const getFileContent = (file: string) => pReadFile(file, 'utf8');

((await scanDirectory(rootDir, undefined, () => false)) as string[])

So was hoping we can extract the core functionality into a series of helpers so that during node, for sure you can scan a file system, and in workers one can use Workers KV to read the css files (or local fetch within context of Pages).

loadStyleDefinitions doesn't require to be in that file.


So mainly about 2 main moments.

  1. split functionality from runtime
  2. allow non-tree shaken bundles to load correctly.
    • we noticed that webpack5 doesn't treeshake in dev mode, as such loading this file in workers context cannot bind fs.

createCriticalStyleStream: problem with inserting styles into existing style tag

There is an issue with interleaving styles when using style tags in react.

Suppose we have this react code:

// inside some react component
<div>
    <style>{`
        .myEl { color: red; }
    `}</style>
    <div className="some-class">
        some content
    </div>
</div>

Depending on the size of the style contents (and mostly when there is a lot of content in it), interleaving of critical css (using createCriticalStyleStream) outputs this:

<!-- server renders this -->
<style type="text/css" data-used-styles="some-file.css">
    .some-class { whatever: whatever; }
</style>
.myEl { color: red; } <!-- not wrapped in a style tag anymore! -->

Which leaves the custom css that was declared in the component without a style tag, meaning it will show up on the page as plain text (until the styles are moved / removed for hydration).

Hopefully, this can be fixed. I tried debugging the source, but I am lacking some knowledge around streams and transforms, so I was unable to come up with a proper solution to fix it.

React 17 support

Currently, with npm >= 7 new peer deps resolution, npm can't correctly install react 17
Please update package.json peer deps to support react 17

Inline critical CSS

Right now used-styles will inline link, while it could inline really used CSS.

No dist in published package

hi, I tried to use this package in my project but I don't see dist directory in node_modules/used-styles, shouldn't it be published?

Styles priority

Hi,
I have weird problem.
image

As you can see on the image, selected div has two classes:

container Products__mobilePadding__27tZs

.container class has

padding-right: 1.875rem; padding-left: 1.875rem;

And Products__mobilePadding__27tZs class has

padding: 0 1rem;

Why second in order class with a single padding definition does not exclude container class dual padding definition and their have a higher priority?

Thanks for help!

Production build: Error: Cannot find module 'tslib'

I'm facing this error in production build:

build pipeline:

npm i
npm run build
npm prune --production
npm start

Error message after npm start

Error: Cannot find module 'tslib'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (XXXXXXX/node_modules/used-styles/dist/es5/scanForStyles.js:3:15)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)

The file containing the error: ....node_modules/used-styles/dist/es5/scanForStyles.js:3:15)

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib"); // <--- this lib is not listed as prod or peer dependency so it's crashing
var fs_1 = require("fs");
// .... etc

package.json snippet:

"scripts": {
    "dev": "npm run build:generate-imported-component && concurrently -r \"npm:type-check:watch\" \"npm:dev:start\"",
    "dev:start": "parcel ./src/index.html",
    "build": "npm run build:clean && npm run build:generate-imported-component && npm run type-check && npm run build:client && npm run build:server",
    "build:client": "cross-env BABEL_ENV=client parcel build ./src/index.html -d dist/client --public-url /dist ",
    "build:server": "cross-env BABEL_ENV=server parcel build ./src/server.ts -d dist/server --public-url /dist --target=node",
    "build:clean": "del-cli dist",
    "build:generate-imported-component": "imported-components src src/imported.ts",
    "start": "node ./dist/server/server.js",
    "start:debug": "node --inspect --debug-brk ./dist/server/server.js",
    "type-check": "tsc --noEmit",
    "type-check:watch": "tsc --noEmit --watch",
  },
"dependencies": {
    "babel-polyfill": "^6.26.0",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-helmet": "^5.2.1",
    "react-imported-component": "^5.5.3",
    "react-markdown": "^4.2.1",
    "react-on-screen": "^2.1.1",
    "react-progressive-image": "^0.6.0",
    "react-promise": "^3.0.2",
    "react-router-dom": "^5.0.0",
    "react-scroll": "^1.7.11",
    "react-transition-group": "^4.0.1",
    "reflect-metadata": "^0.1.13",
    "serialize-javascript": "^1.9.0",
    "used-styles": "^2.0.3"
  },
"devDependencies": {
    "@babel/core": "^7.5.5",
    "@babel/plugin-syntax-dynamic-import": "^7.2.0",
    "@babel/preset-react": "^7.0.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-react": "^6.24.1",
    "concurrently": "^4.1.0",
    "cross-env": "^5.2.0",
    "del-cli": "^2.0.0",
    "jest": "^24.7.1",
    "marked": "^0.7.0",
    "parcel-bundler": "^1.12.3",
    "parcel-plugin-bundle-visualiser": "^1.2.0",
    "parcel-plugin-markdown-string": "^1.4.0",
    "react-test-renderer": "^16.8.6",
    "react-testing-library": "^6.1.2",
    "ts-jest": "^24.0.2",
    "tslint": "^5.16.0",
    "tslint-config-airbnb": "^5.11.1",
    "tslint-config-prettier": "^1.18.0",
    "tslint-react": "^4.0.0",
    "typescript": "^3.4.4"
  }

usage: middleware.tsx

import { discoverProjectStyles, getUsedStyles } from 'used-styles'

const projectStyles = discoverProjectStyles(`${__dirname}/../client`)

export default (req: Request, res: Response) => {
      // ...
      //some code above 
      const usedStyles = getUsedStyles(markup, projectStyles)
      console.log('used styles', usedStyles)

      // and some code after ...
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "esnext",
    "moduleResolution": "node",
    "sourceMap": true,
    "strict": true,
    "jsx": "react",
    "rootDir": "./src",
    "incremental": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "lib": ["es2015", "es2016", "es2017", "dom"],
    "types": ["reflect-metadata"],
    "baseUrl": "./src",
    "allowSyntheticDefaultImports": true,
    "paths": {
      "*": ["./@types/*"],
      "~/*": ["./*"]
    }
  }
}

TypeError: Cannot read property 'isReady' of undefined

I did same steps as explained in example but got this error :

/Users/user/projcect/node_modules/used-styles/dist/es5/utils.js:39
    if (!def.isReady) {
             ^

TypeError: Cannot read property 'isReady' of undefined
    at Object.exports.assertIsReady (/Users/user/projcect/node_modules/used-styles/dist/es5/utils.js:39:14)
    at Transform.transform [as _transform] (/Users/user/projcect/node_modules/used-styles/dist/es5/reporters/used.js:37:21)

my code looks like :

import React from 'react';
import through from 'through';
import { renderToNodeStream } from 'react-dom/server';
import { StaticRouter, matchPath } from 'react-router-dom';
import { HelmetProvider } from 'react-helmet-async';
import { Provider as ReduxProvider } from 'react-redux';
import { ServerStyleSheet } from 'styled-components';
import { ChunkExtractor } from '@loadable/server';
import {
  createLink,
  createStyleStream,
  discoverProjectStyles,
} from 'used-styles';
import MultiStream from 'multistream';
import Hoc from 'components/Common/Hoc';

import { readableString } from './utils/readable';
import createStore from '../../app/config/configureStoreSSR';
import { indexHtml } from './indexHtml';

export async function renderServerSideApp(req, res) {
  const context = {};
  const helmetContext = {};

  /**
   * Styled component instance
   * @type {ServerStyleSheet}
   */
  const sheet = new ServerStyleSheet();

  try {
    const { store, history } = createStore(req.url);

    /**
     * A box of components which will load Server app
     * @returns {*}
     * @constructor
     */
    const ServerApp = () => (
      <HelmetProvider context={helmetContext}>
        <ReduxProvider store={store}>
          <StaticRouter history={history} location={req.url} context={context}>
            <Hoc routerProvider="server" />
          </StaticRouter>
        </ReduxProvider>
      </HelmetProvider>
    );

    const stats = require(`${process.cwd()}/build/${process.env.PUBLIC_URL}/loadable-stats.json`);
    const chunkExtractor = new ChunkExtractor({ stats });
  
    const stylesLookup = discoverProjectStyles(`${process.cwd()}/build`); // __dirname usually
  
    /**
     * Handle 404 and 301
     */
    if (context.url) {
      return res.redirect(301, context.url);
    }
    if (context.status === 404) {
      res.status(404);
    }
  
    const [header, footer] = indexHtml({
      helmet: helmetContext.helmet,
      state: store.getState(),
    });
  
    /**
     * Get styledComponents global styles
     */
    const jsx = chunkExtractor.collectChunks(
      sheet.collectStyles(<ServerApp />),
    );
  
    const endStream = readableString(footer);
  
    res.set({ 'content-type': 'text/html; charset=utf-8' });
    res.write([header, '<div id="root">'].join(''));
  
    // Pipe that HTML to the response
    const HtmlStream = sheet.interleaveWithNodeStream(renderToNodeStream(jsx));
  
    const lookup = await stylesLookup;
    // create a style steam
    const styledStream = createStyleStream(
      lookup,
      style =>
        // _return_ link tag, and it will be appended to the stream output
        createLink(`dist/${style}`), // <link href="dist/mystyle.css />
    );
    new MultiStream([styledStream, endStream]).pipe(res);
  
  
    HtmlStream.pipe(
      .pipe(styledStream, { end: false }).pipe(
      through(
        function write(data) {
          this.queue(styledStream);
          this.queue(data);
        },
        async function end() {
          this.queue('</div>');
          this.queue(chunkExtractor.getScriptTags());
          this.queue(chunkExtractor.getStyleTags());
          this.queue(endStream);
          this.queue(null);
  
          res.end();
        },
      ),
    );
  } catch (error) {
    res.status(500).send('Oops, better luck next time!');
  }
}

Skip certain media

During SSR itโ€™s possible to detect the device and remove some media targets, which are not expected to be used (like remove desktop for mobile)

Report use percentage

Sometimes, by fact quite often, almost all styles might be inlined. And then the "real" file would be downloaded, doubling the traffic.

So, what about

  • reporting used coverage
  • and if it is above some threshold (80%) - inline the rest
  • and somehow report that the original file might be downloaded in a low priority

Support publicURL

Sometimes CSS files are hosted on other domain, and resources used in CSS would refer to other domains.

useStyles should support publicURL as well as the ability to rewrite url in, for example, backgrounds.

Don't inline "known files"

In some circumstances the customer might already download the original styles in the past, and they might be not inlined, as long as there is no penalty to just import them in a "usual way"

  • provide per-session configuration with the ability to remove some files from known list

Is moving / removing styles mandatory?

i am streaming my markup with react and interleave critical styles with createCriticalStyleStream.
is moving / removing the styles really neccessry in this case? i don't have any issues with hydrating the client.

CSS truncated incorrectly

Due to how our components stylesheets target svg classes for lottie player :

i.e.

.-lottie-player svg path[fill="rgb(255,255,255)"] {
  fill: var(--color-background)
}

The resulting critical styles (from getCriticalStyles) gets truncated incorrectly like so :

.lottie-lottie-player svg path[fill="rgb(255 { fill: var(--color-background); }

The expected style from the critical styles would be :

.-lottie-player svg path[fill="rgb(255,255,255)"] {
  fill: var(--color-background)
}

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.