Skip to content

Commit da163f0

Browse files
authored
[system] Use a custom sheet to set prepend for GlobalStyles (#43632)
1 parent 701a364 commit da163f0

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

packages/mui-styled-engine/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
"dependencies": {
4040
"@babel/runtime": "^7.25.6",
4141
"@emotion/cache": "^11.13.1",
42+
"@emotion/sheet": "^1.4.0",
4243
"csstype": "^3.1.3",
4344
"prop-types": "^15.8.1"
4445
},

packages/mui-styled-engine/src/StyledEngineProvider/StyledEngineProvider.js

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,43 @@ import * as React from 'react';
33
import PropTypes from 'prop-types';
44
import { CacheProvider } from '@emotion/react';
55
import createCache from '@emotion/cache';
6+
import { StyleSheet } from '@emotion/sheet';
7+
8+
// We might be able to remove this when this issue is fixed:
9+
// https://github.com/emotion-js/emotion/issues/2790
10+
const createEmotionCache = (options) => {
11+
const cache = createCache(options);
12+
13+
/**
14+
* This is for client-side apps only.
15+
* A custom sheet is required to make the GlobalStyles API work with `prepend: true`.
16+
* This is because the [sheet](https://github.com/emotion-js/emotion/blob/main/packages/react/src/global.js#L94-L99) does not consume the options.
17+
*/
18+
class MyStyleSheet extends StyleSheet {
19+
constructor(args) {
20+
super(args);
21+
this.prepend = cache.sheet.prepend;
22+
}
23+
}
24+
25+
// Do the same as https://github.com/emotion-js/emotion/blob/main/packages/cache/src/index.js#L238-L245
26+
cache.sheet = new MyStyleSheet({
27+
key: cache.key,
28+
nonce: cache.sheet.nonce,
29+
container: cache.sheet.container,
30+
speedy: cache.sheet.isSpeedy,
31+
prepend: cache.sheet.prepend,
32+
insertionPoint: cache.sheet.insertionPoint,
33+
});
34+
35+
return cache;
36+
};
637

738
// prepend: true moves MUI styles to the top of the <head> so they're loaded first.
839
// It allows developers to easily override MUI styles with other styling solutions, like CSS modules.
940
let cache;
1041
if (typeof document === 'object') {
11-
cache = createCache({ key: 'css', prepend: true });
42+
cache = createEmotionCache({ key: 'css', prepend: true });
1243
}
1344

1445
export default function StyledEngineProvider(props) {

pnpm-lock.yaml

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)