One way to incorporate the npm-installed normalize.css
in React is as follows:
import React from 'react';
import ReactDOM from 'react-dom';
import 'normalize.css'; // Add this line
const root = document.getElementById('root');
ReactDOM.render(<h1>Hello, World!</h1>, root);
After implementation, the text will now display like this:
https://i.sstatic.net/pF9BH.png
Take note that the text styling is courtesy of normalize.css
.
To make it function properly, you should have a setup similar to the following:
1) Insert the provided JavaScript code into index.js
2) Add normalize.css
(and other dependencies) to package.json
:
{
"dependencies": {
"normalize.css": "^5.0.0",
"react": "^16.3.2",
"react-dom": "^16.3.2"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.11",
"style-loader": "^0.21.0",
"webpack-dev-server": "^3.1.4",
"webpack": "^4.8.3"
}
}
3) Ensure the correct loaders are utilized in webpack.config.js
:
module.exports = {
mode: 'development',
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
options: { presets: ['env', 'react'] }
},
{
test: /\.css$/,
use: [{ loader: 'style-loader' }, { loader: 'css-loader' }]
}
]
}
};
4) Integrate an index.html
file to view the changes:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="root"></div>
<script src="main.js"></script>
</body>
</html>
5) Install all dependencies by running:
npm install
6) Initiate the Webpack devserver with the command:
./node_modules/.bin/webpack-dev-server --open
NOTE: This guide is based on version 5.0.0
of normalize.css
. Using version 6.0.0
or higher will result in a different font style, as the opinionated rules were removed from normalize.css
in that version.
Update 17/5/2018: Updated instructions to incorporate Webpack 4 and React 16.