Introduction to Webpack CLI
Webpack CLI is an essential tool for modern web development. It provides a command line interface for interacting with Webpack, making it easier to bundle and build your projects. Whether you’re a beginner or an experienced developer, Webpack CLI offers powerful and flexible options to optimize your workflow.
Installation
To install Webpack CLI, run the following command:
npm install --save-dev webpack-cli
Common Commands
Webpack CLI supports a variety of commands that can be used to control and configure your builds.
Bundling Your Project
To bundle your project, simply run:
npx webpack
Specify Configuration File
You can specify a custom configuration file with the --config
option:
npx webpack --config webpack.config.js
Watch Mode
Enable watch mode to automatically rebuild your project when source files change:
npx webpack --watch
Production Mode
Build your project in production mode to enable optimizations:
npx webpack --mode production
Development Mode
Build your project in development mode for easier debugging:
npx webpack --mode development
Analyze Bundle
Analyze your bundle with the --profile
and --json
options:
npx webpack --profile --json > stats.json
Serve Your Project
Use the serve command to start a development server:
npx webpack serve
Application Example
Here’s a simple example of a project that uses Webpack and Webpack CLI.
Project Structure
my-app/ ├── src/ │ ├── index.js │ └── style.css ├── dist/ ├── webpack.config.js ├── package.json └── index.html
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
devServer: {
contentBase: './dist',
},
mode: 'development',
};
src/index.js
import './style.css';
function component() {
const element = document.createElement('div');
element.innerHTML = 'Hello, Webpack CLI!';
return element;
}
document.body.appendChild(component());
src/style.css
body {
background: #f5f5f5;
font-family: Arial, sans-serif;
}
With these files in place, you can bundle your project using Webpack CLI and serve it with a development server:
npx webpack serve
Visit localhost:8080
in your browser to see your project in action.
Hash: 418315dae1c84b4894e27f83de667faa8639112c001a8120080074cb4a5b52bc