Webpack Installation Guide
Webpack v5 (Modern Version) Installation
Local Installation (Recommended)
For most projects, install webpack locally as a development dependency:
# npm
npm init -y
npm install webpack webpack-cli --save-dev
# yarn
yarn init -y
yarn add webpack webpack-cli --dev
# pnpm
pnpm init
pnpm add webpack webpack-cli -D
Global Installation (Not Recommended)
While possible, global installation is not recommended as it can cause version conflicts between projects:
# npm
npm install --global webpack webpack-cli
# yarn
yarn global add webpack webpack-cli
Basic Project Setup
Create the following directory structure:
project/
├── package.json
├── dist/
│ └── index.html
└── src/
└── index.js
Install a dependency to bundle:
# npm
npm install --save lodash
# yarn
yarn add lodash
# pnpm
pnpm add lodash
Running Webpack
After local installation, you can run webpack using:
# npm
npx webpack
# yarn
yarn webpack
# pnpm
pnpm exec webpack
Webpack v4 Installation
Local Installation
# npm
npm init -y
npm install [email protected] [email protected] --save-dev
# yarn
yarn init -y
yarn add [email protected] [email protected] --dev
Running Webpack v4
npx webpack
Note: Webpack v4 will show a warning about the 'mode' option not being set. You can resolve this by adding --mode=production or --mode=development flag.
NPM Scripts Setup
Add a build script to your package.json for easier usage:
{
"scripts": {
"build": "webpack"
}
}
Then run:
# npm
npm run build
# yarn
yarn build
# pnpm
pnpm run build
Version Selection Recommendations
- New Projects: Use Webpack v5 to take advantage of modern features, better performance, and persistent caching
- Existing Projects: If already using Webpack v4, consider migrating to v5 for performance improvements
- Enterprise Environments: Webpack v4 provides stable long-term support, while v5 offers cutting-edge features
Migration from v4 to v5
Webpack provides a smooth migration path:
- Update dependencies:
npm install webpack@latest webpack-cli@latest - Review breaking changes in the official migration guide
- Update configuration syntax if using ES Modules
- Test thoroughly to ensure compatibility
The official migration guide provides detailed instructions for handling specific breaking changes and deprecated features.
