| title | description |
|---|---|
Quickstart |
Get started with webpack and create your first bundle |
Get started with webpack by creating a simple project and bundling it.
Create a new directory for your project and initialize npm:```bash
mkdir webpack-demo
cd webpack-demo
npm init -y
```
<CodeGroup>
```bash npm
npm install --save-dev webpack webpack-cli
```
```bash yarn
yarn add --dev webpack webpack-cli
```
```bash pnpm
pnpm add -D webpack webpack-cli
```
</CodeGroup>
**src/index.js**
```javascript
import { add } from './math.js';
console.log('webpack is working!');
console.log('2 + 3 =', add(2, 3));
```
**src/math.js**
```javascript
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
```
```javascript
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
```
```json
{
"scripts": {
"build": "webpack"
}
}
```
```bash
npm run build
```
Webpack will create a `dist/bundle.js` file with your bundled code.
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>webpack Demo</title>
</head>
<body>
<h1>webpack Quickstart</h1>
<script src="bundle.js"></script>
</body>
</html>
```
Open `dist/index.html` in your browser and check the console!
Webpack:
- Started from the entry point (
src/index.js) - Analyzed all imports and created a dependency graph
- Bundled all modules into a single file (
dist/bundle.js) - Generated optimized JavaScript that runs in the browser
For production, change the mode to production:
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};Production mode automatically:
- Minifies your code
- Enables tree shaking
- Optimizes bundle size
- Sets
process.env.NODE_ENVtoproduction
To bundle CSS files, install loaders:
npm install --save-dev style-loader css-loaderUpdate webpack.config.js:
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
],
},
};Create src/style.css:
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}Import it in src/index.js:
import './style.css';
import { add } from './math.js';
console.log('webpack is working!');
console.log('2 + 3 =', add(2, 3));