React and webpack 4
Simple React and Webpack4 Sample
This article is written on 2018/03/25.
Goal
Create React sample with webpack4.
Use css and css loader, too.
Prepare Project
To prepare webpack and other related packages, try following commands.
npm init -y npm i webpack webpack-cli -D npm i webpack-dev-server -D npm i react react-dom -S npm i babel-core babel-loader babel-preset-env babel-preset-react -D npm i html-webpack-plugin -D npm i css-loader style-loader -D
We prepared react, babel, webpack, and loaders.
Project structure(final)
project
|- dist
|- node_modules
|- .babelrc
|- package.json
|- webpack.config.js
|- src
|- index.css
|- index.html
|- index.js
npm additional command
To add build and run commands to npm package.json file.
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --mode development --open",
"build": "webpack --mode production"
}
src
index.js
import React from "react";
import ReactDOM from "react-dom";
import './index.css';
const Index = () => {
return <div className="hello">Hello React!</div>;
};
ReactDOM.render(<Index />,
document.getElementById("root")
);
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>React and Webpack4</title> </head> <body> <section id="root"></section> </body> </html>
index.css
.hello {
color: red;
}
.babelrc
{
"presets": ["env", "react"]
}
webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const htmlPlugin = new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
});
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
plugins: [htmlPlugin]
};
Build and run
npm run start
