Webpack 4 React JS Configuration
Webpack 4 React JS Configuration
Configuring the React with Webpack 4 is now made very easier. Webpack 4 can also work like Parcel JS’s zero config build system. But configuring Webpack 4 on top of React may seem a bit of mystery for beginners. So let’s dive into the tutorial…
First install the dependencies for React JS:
npm install --save react react-dom
Then install dev dependencies Webpack:
npm install --save-dev webpack webpack-cli babel-loader babel-preset-env babel-preset-react css-loader extract-text-webpack-plugin@next file-loader
Add a new file named webpack.config.js
in your root folder and add the following configurations:
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
mode: "development",
watch: true,
entry: "./src/index.js",
output: {
path: \_\_dirname + "/dist",
filename: "bundle.js"
},
module: {
rules: [
{
test: /\.jsx?$/,
loader: "babel-loader",
options: {
presets: ["react"]
}
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
loader: "css-loader",
options: {
modules: true
}
})
},
{
test: /\.(png|jpg|gif|svg)\$/,
loader: "file-loader",
query: {
name: "[name].[ext]?[hash]"
}
}
]
},
plugins: [new ExtractTextPlugin("style.css")],
resolve: {
extensions: [".js", ".json", ".jsx"]
}
};
Lets update our package.json by adding the following commands inside script section:
...
"scripts": {
"webpack": "npx webpack --config webpack.config.js",
"build": "npx webpack -p --config webpack.config.js"
}
...
You are almost done now.
Just enter the command webpack
when developing, which will bundles all of your assets without compression.
And for the production build, use the command npm run build
.
If you stuck anywhere following the tutorial, just add a comment, am more than happy to help you, thank you 🙂