简体   繁体   中英

In production mode, the style tag that generated by styled-component has no content

Reproduction

https://codepen.io/wqh/pen/KKqjaWL

Steps to reproduce

First, Sorry for my bad English, I hope you can understand what I mean.

Open the codepen link and you can see the phenomenon in the developer tools:

图片

the generated style tag has no content, but actually effective.

The example is of a low version, but the 5.3.3 version of my project has the same problem

Expected Behavior

The content of the generated style tag can also be obtained in production mode.

I saw a Q&A that said that the insertRule will cause the content of the style tag to be unavailable.But I use the css-vars-ponyfill to fix vars in IE11, this needs to get the content of the style tag.

Actual Behavior

In production mode, the generated style tag has no content, this is inconsistent with the development model

Styles get injected in the DOM differently in development and in production environments.

As mentioned here (How styles land in the DOM) ,

This step differs from development mode to production mode.

In development mode, styled-components will inject a style tag inside the head of the page's DOM. This tag will include some data meta properties like the library's version used. And inside the tag, styled-components will append all the styles from your StyledComponents bound to their classNames.

In production mode however, things are a bit different. Since we need to optimize and compress stuff the most we can, the style tag injected by styled-components will still be there, but will be injected as empty.

Edit:

styled-components is handling it differently for 5.0.0 onwards. As mentioned here :

Modifying the way CSS is injected The property disableCSSOMInjections allows us to switch from the CSS Object Model (CSSOM) API to a text node-based CSS injection system.

When a browser parses the HTML code of a page, in addition to creating a tree of nodes called the DOM (Document Object Model), it creates a CSS object model in the form of a tree where each node contains CSS style information for a particular DOM element.

This way, to insert or modify the style of a particular node, we can use either the DOM API:

 document.getElementById('myDiv').style.background = 'blue' Or the CSSOM API: // Assuming there's a stylesheet in the HTML page const style = document.styleSheets[0]; style.sheet.insertRule('#myDiv{background-color: blue}');

This way, when the property disableCSSOMInjections is present or you assign it the value true :

 ReactDOM.render( <StyleSheetManager disableCSSOMInjections={true}> <App /> </StyleSheetManager>, root );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM