To ensure that a CSS file applies to each child component, you can import it into the parent component. Utilizing a bundler like webpack will help in reading the CSS import and loading it correctly. For more information on how to load a CSS file with webpack, refer to this webpack guide on loading CSS
import '../styles.css'
export default function App() {
return (
<main></main>
)
}
Alternatively, you can also directly import the CSS style in the HTML like so:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="root"></div>
<script type="text/javascript" src="react.js"></script>
</body>
</html>
Here is a simple webpack configuration example:
module.exports = {
entry: {
bundle: './src/app.tsx'
},
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: ['*', '.ts', '.tsx', '.js']
},
module: {
rules: [
/*
* Typescript files.
*/
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader"
}
]
},
{
enforce: "pre",
test: /\.js$/,
loader: "source-map-loader"
},
/*
* Miscellaneous Files.
*/
{
test: /\.(png|svg|jpg|gif|ttf|otf)$/,
exclude: /node_modules/,
use: [
'file-loader'
]
},
/*
* CSS Files.
*/
{
test: /\.css$/,
exclude: /node_modules/,
use: [
'style-loader',
'css-loader',
"postcss-loader"
]
}
]
},
plugins: [
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
};
To download the necessary dependencies using npm, run the following command:
npm i style-loader css-loader postcss-loader