Quickstart
Get started with webpack by creating a simple project and bundling it.
Create a project directory
Create a new directory for your project and initialize npm:mkdir webpack-demo
cd webpack-demo
npm init -y
Install webpack
Install webpack and webpack-cli as dev dependencies:npm install --save-dev webpack webpack-cli
Create source files
Create a src directory and add your JavaScript files:src/index.jsimport { add } from './math.js';
console.log('webpack is working!');
console.log('2 + 3 =', add(2, 3));
src/math.jsexport function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
Create webpack configuration
Create a webpack.config.js file in the root directory:const path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
Add build script
Update your package.json to include a build script:{
"scripts": {
"build": "webpack"
}
}
Build your bundle
Run webpack to create your bundle:Webpack will create a dist/bundle.js file with your bundled code. Create an HTML file
Create dist/index.html to load your bundle:<!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!
What Just Happened?
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
Production Build
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_ENV to production
Adding CSS
To bundle CSS files, install loaders:
npm install --save-dev style-loader css-loader
Update 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));
Loaders transform files before they’re added to the bundle. CSS files are converted to JavaScript that injects styles into the page.
Next Steps
Core Concepts
Learn about entry points, output, loaders, and plugins
Configuration
Explore all configuration options
Code Splitting
Split your code for better performance
Development
Set up a development environment with dev server and HMR