Configure React with Webpack (react & pwa & webpack)
#react
#pwa
#webpack
Configure React with Webpack
1. Add modules
- create
src
directory
- create
public
directory
- add modules for es6
yarn add -D @babel/core @babel/preset-env @babel/preset-react
2. Install webpack modules
yarn add -D webpack webpack-cli webpack-dev-server babel-loader css-loader style-loader html-webpack-plugin
3. webpack.config.js
webpack.config.js
const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const htmlPlugin = new HtmlWebpackPlugin({ template: './public/index.html', filename: './index.html', }) const config = mode => { const isDevelopMode = mode === 'development' return { entry: './src/index.js', output: { path: path.join(__dirname, '/build'), filename: 'index.bundle.js', }, module: { rules: [ { test: /\\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader', }, }, { test: /\\.(css)$/, use: [ { loader: 'style-loader', }, { loader: 'css-loader', options: { modules: { localIdentName: isDevelopMode ? '[path][name]__[local]--[hash:base64:5]' : '[name]__[local]--[hash:base64:5]', }, importLoaders: 1, sourceMap: true, }, }, ], }, ], }, plugins: [htmlPlugin], } } module.exports = (env, argv) => { const { mode } = argv return config(mode) }
4. Add index.html in public directory
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 PWA Webpack</title> </head> <body> <div id="root"></div> </body> </html>
5. Configure Babel
.babelrc
{ "presets": ["@babel/env", "@babel/react"] }
6. Install React
yarn add react react-dom
7. Create src/index.js
src/index.js
import React from 'react' import ReactDOM from 'react-dom' const Root = () => <div>Hello World!</div> ReactDOM.render(<Root />, document.getElementById('root'))
8. Add package.json scripts
package.json
"scripts": { "build:prod": "webpack --mode=production", "build:dev": "webpack --mode=development" }
9. establish dev server with hot reload
package.json
"scripts": { "start:dev": "webpack-dev-server --mode=development --open --hot" }