How to configure Webpack into the React app(Code Splitting)

Adil
3 min readSep 25, 2023

--

The implementation of Webpack in a React project involves setting up a Webpack configuration file, installing necessary packages, and using it to build and run your application. Here’s a step-by-step guide on how to do this:

1. Create a new React project or use an existing one: If you don’t have a React project yet, you can create one using create-react-app or set up a custom project structure with React.

2. Install Webpack and related packages: In your project directory, you’ll need to install Webpack and other related packages using npm or yarn:

npm install --save-dev webpack webpack-cli webpack-dev-server

3. Create a Webpack configuration file: Create a webpack.config.js file in your project root directory. This file will define how Webpack should bundle and process your application.

Here’s a basic example of a Webpack configuration for a React project:

const path = require('path');
module.exports = {
entry: './src/index.js', // Entry point of your application
output: {
path: path.resolve(__dirname, 'dist'), // Output directory
filename: 'bundle.js', // Output bundle filename
},
module: {
rules: [
{
test: /\.(js|jsx)$/, // Process JavaScript and JSX files
exclude: /node_modules/,
use: {
loader: 'babel-loader', // Use Babel for transpilation
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
},
},
},
{
test: /\.css$/, // Process CSS files
use: ['style-loader', 'css-loader'],
},
],
},
optimization: { splitChunks: { chunks: 'all' }},
devServer: {
contentBase: './dist', // Serve files from the 'dist' directory
port: 3000, // Port for development server
hot: true,
publicPath: '/',
},
};

In the optimization section, we enable code splitting by setting splitChunks.chunks to 'all'. This tells Webpack to split common dependencies into separate chunks, resulting in smaller and more efficient bundles.

If you’re using Webpack Dev Server for development, it’s essential to ensure that it serves these dynamically loaded chunks correctly by setting host: true.

4. To indicate which parts of your code should be split into separate chunks, you can use dynamic import() statements in your React components. For example:

// src/components/Home.js
import React, { lazy } from 'react';

const LazyComponent = lazy(() => import('./LazyComponent'));

function Home() {
return (
<div>
<p>Home Page</p>
<LazyComponent />
</div>
);
}

export default Home;

In this example, import('./LazyComponent') is a dynamic import statement, and Webpack will automatically create a separate chunk for the LazyComponent module.

5. Install Babel and necessary presets: Since the configuration above uses Babel for transpilation, you need to install Babel and the required presets:

npm install --save-dev @babel/core @babel/preset-env @babel/preset-react babel-loader

6. Update your package.json scripts: In your package.json file, add scripts to build and run your application using Webpack:

"scripts": {
"start": "webpack-dev-server --mode development --open",
"build": "webpack --mode production"
}
  • The start script launches the development server with HMR enabled.
  • The build script creates a production-ready bundle.

7. Create a simple React component: Write your React components in the src directory. For example, you can create a file named App.js with a basic component:

// src/App.js
import React, { lazy, Suspense } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

const Home = lazy(() => import('./components/Home'));
const About = lazy(() => import('./components/About'));

function App() {
return (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Switch>
</Suspense>
</Router>
);
}

export default App;

8. Create an entry point: In your src directory, create an entry point (e.g., index.js) where you import and render your main React component:

// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

9. Start the development server: Run the development server using the following command:

npm start

Your React application should now be accessible at http://localhost:3000, and changes you make to your code will be automatically reflected in the browser thanks to HMR.

10. Build for production: When you’re ready to deploy your React application, run the following command to create a production-ready bundle:

npm run build

This will generate optimized and minified files in the dist directory, which you can deploy to a web server or hosting platform.

That’s a basic overview of how to implement Webpack in a React project. You can further enhance your configuration and add more loaders, plugins, and optimizations as needed for your specific project requirements.

--

--

Adil

Senior UI Developer | Imperva | Ex- Oracle-cerner