Expanding beyond React, I'm unsure if React itself is the culprit of this issue.
In a React environment with TypeScript, I utilize CSS imports in component files to have specific stylesheets for each component. I assumed these styles would only be added to the <head>
element when the respective component is instantiated. However, I noticed that if I import a component from a file that reexports all components, the styles of unused components are still injected into the DOM.
For instance, let's consider two simple components - Avatar
and Button
located in the lib
folder:
import React from 'react';
import './avatar.css';
const Avatar: React.FC = (props: any) => {
return (
<div className="avatar">
{props.children}
</div>
);
}
export { Avatar };
Then, I create an index.ts
file to reexport the components for easier import paths:
import { Avatar } from './Avatar';
import { Button } from './Button';
export { Avatar, Button };
Subsequently, in my AppComponent
, I intend to use only the Button
:
import React from 'react';
import { Button } from './lib';
const App: React.FC = () => {
return (
<div className="App">
<Button>example</Button>
</div >
);
}
export default App;
To my astonishment, the <style>
tags in the <head>
include not just the Button
styles, but also those of Avatar
. Why does this occur? Is there an issue with my reexport configuration?
If I directly import the component from its file like so -
import { Button } from './lib/Button'
- I do not encounter the Avatar
styles.
While this example is simplistic, the actual scenario pertains to a React component library comprising numerous components with their individual stylesheets. My objective is to mitigate the insertion of unnecessary <style>
tags in the DOM unless absolutely necessary.
Your time and assistance are greatly appreciated!