thekashey / used-styles Goto Github PK
View Code? Open in Web Editor NEW📝All the critical styles you've used to render a page.
License: MIT License
📝All the critical styles you've used to render a page.
License: MIT License
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
Hello, could you help me, where can I find an example with renderToPipeableStream?
Thank you.
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?
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);
}
}
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!
Simplify streaming
#62
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.
Not all rules are welcomed for critical extraction. Let's keep @media
as a separate problem, but we can safely remove:
:focus
:hover
We can't remove:
:disabled
:before
/ :after
:first-
/:nth-
Right now used-styles will inline link
, while it could inline really used CSS.
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"
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?
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.
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 HTMLstream
mode, when styles are extracted from every single rendering "chunk", which is basically unknownFold
components, which will act as a "separator" between "block-extracted" styles
block
mode styles will be separated into:
Fold
Fold
stream
mode styles, as well as HTML will be accumulated between two sibling Folds
, providing better control on extraction if needed.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>
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?
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.
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.
It will be great if you will add CLI for that tool
Hello 👋🏻
We are wanting to use this library with Cloudflare workers, and thes during SSR we cannot scan the directory.
used-styles/src/scanForStyles.ts
Line 18 in cb432b1
used-styles/src/scanForStyles.ts
Line 157 in cb432b1
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.
fs
.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.
🚨 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.
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
used coverage
original file
might be downloaded in a low priorityAt 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;
}
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
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:
style
tags by getCriticalStyles
split by source with data-used-styles
What kind of pitfalls did I miss?
Just upgraded from 2.1.3 to 2.6.0. It seems that imports from the moveStyles module are not exposed anymore.
Here is the culprit:
3fdefdc#diff-7ae45ad102eab3b6d7e7896acd08c427a9b25b346470d7bc6507b6481575d519L37
Let me know if I am missing anything or if you would like a PR to fix it.
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/*"],
"~/*": ["./*"]
}
}
}
Critical ERROR
Failed to compile.
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.
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)
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
This leads to unexpected behavior and has to be detected and avoided.
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?
Need ability to inline complete .css files and exclude those files from the extracted list of css files. so it's not loaded twice.
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!');
}
}
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 ?
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)
}
Check the ability to use CSSO to minify the output.
However - it might not optimize anything, as long as styles are already minimised.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.