A sample program demonstrating modularization with Webpack involves
creating multiple JavaScript modules and then using Webpack to bundle
them into a single, optimized output file.
1. Project Setup:
Create a new directory for your project and initialize a react app :
Code
mkdir webpack-modular-example
cd webpack-modular-example
npm init -y
npm install webpack webpack-cli --save-dev
2. Create Modules:
Create a src directory and define your modules within it. src/[Link].
JavaScript
// src/[Link]
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
src/[Link].
JavaScript
// src/[Link]
import { add, subtract } from './math';
function displayResult() {
const sum = add(5, 3);
const difference = subtract(10, 4);
[Link](`Sum: ${sum}`);
[Link](`Difference: ${difference}`);
}
export default displayResult;
src/[Link] (entry point).
JavaScript
// src/[Link]
import displayResult from './app';
displayResult();
3. Webpack Configuration:
Create a [Link] file in the root of your project:
JavaScript
// [Link]
const path = require('path');
[Link] = {
entry: './src/[Link]', // Entry point of your application
output: {
filename: '[Link]', // Name of the bundled output file
path: [Link](__dirname, 'dist'), // Output directory
},
mode: 'development', // Or 'production' for optimized output
};
4. Build with Webpack:
Run Webpack from your terminal:
Code
npx webpack
This command will bundle src/[Link] and all its dependencies
(like src/[Link] and src/[Link]) into a single file named [Link] inside
the dist directory.
5. Run the Bundled Application:
Create an [Link] file to load your bundled script:
Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Webpack Modular Example</title>
</head>
<body>
<h1>Check the console for results!</h1>
<script src="./dist/[Link]"></script>
</body>
</html>
Open [Link] in a web browser and check the browser's developer
console to see the output from displayResult(). This demonstrates how
Webpack effectively bundles modularized JavaScript code for use in a web
environment.