用Webpack 基础配置快速搭建项目开发环境
Webpack 是一个现代 JavaScript 应用程序的静态模块打包工具,但是Webpack有大量的配置项,对新手不太友好,但是我们可以根据webpack-cli
的init
命令根据项目需求快速生成webpack的配置文件,本文将手把手教你如何用 Webpack 和 npm 快速搭建一个基础开发环境。
一、初始化项目
首先,新建项目文件夹并初始化:
mkdir webpack_test
cd webpack_test
npm init -y
二、使用 webpack-cli 初始化配置
Webpack 提供了快速初始化配置的能力:
npx webpack init
报错后提示我们安装webpack-cli
,输入yes
CLI for webpack must be installed.webpack-cli (https://github.com/webpack/webpack-cli)We will use "npm" to install the CLI via "npm install -D webpack-cli".
Do you want to install 'webpack-cli' (yes/no):
提示我们init
命令无法识别
[webpack-cli] Unknown command or entry 'init'
[webpack-cli] Did you mean 'info' (alias 'i')?
[webpack-cli] Run 'webpack --help' to see available commands and options
我们安装先安装webpack-cli
npm i -D @webpack-cli
再安装@webpack-cli/init
,错误提示webpack-cli版本太高了,package.json中也可以看到webpack-cli的版本是6.0.1
E:\Code\Node-Code\webpack_test>npm i -D @webpack-cli/init
npm error code ERESOLVE
npm error ERESOLVE unable to resolve dependency tree
npm error
npm error While resolving: webpack_test@1.0.0
npm error Found: webpack-cli@6.0.1
npm error node_modules/webpack-cli
npm error dev webpack-cli@"^6.0.1" from the root project
npm error
npm error Could not resolve dependency:
npm error peer webpack-cli@"4.x.x" from @webpack-cli/init@1.1.3
npm error node_modules/@webpack-cli/init
npm error dev @webpack-cli/init@"*" from the root project
npm error
npm error Fix the upstream dependency conflict, or retry
npm error this command with --force or --legacy-peer-deps
npm error to accept an incorrect (and potentially broken) dependency resolution.
npm error
npm error
npm error For a full report see:
npm error E:\Environment\Node.js\node_cache\_logs\2025-04-14T09_08_54_013Z-eresolve-report.txt
npm error A complete log of this run can be found in: E:\Environment\Node.js\node_cache\_logs\2025-04-14T09_08_54_013Z-debug-0.log
{"name": "webpack_test","version": "1.0.0","main": "index.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"keywords": [],"author": "","license": "ISC","description": "","devDependencies": {"webpack-cli": "^6.0.1"}
}
先将它降低到v4
版本
npm i -D webpack-cli@4
降低到v4
后,再运行npx webpack init
,提示我们安装@webpack-cli/generators
,我们选择yes
E:\Code\Node-Code\webpack_test>npx webpack init
[webpack-cli] Would you like to install '@webpack-cli/generators' package? (That will run 'npm install -D @webpack-cli/generators') (Y/n) y
安装好后就到配置询问环节了,示例如下:
? Which of the following JS solutions do you want to use? (Use arrow keys)
> noneES6Typescript
我选的配置如下:
# 选择ES6,还是TypeScript
? Which of the following JS solutions do you want to use? ES6# 是否选择开发服务器,我们选择是
? Do you want to use webpack-dev-server? Yes# 是否将打包的js文件自动给我们注入HTML文件,我们选择是
? Do you want to simplify the creation of HTML files for your bundle? Yes# PWA(Progressive Web App)是可安装、支持离线访问的网页应用形式,我们选择否
? Do you want to add PWA support? No# 我使用的CSS方案是SASS方案,选择CSS only也可以
? Which of the following CSS solutions do you want to use? SASS# PostCSS方便后续对CSS进行扩展,我们选择是
? Will you be using PostCSS in your project? Yes# 是否将CSS抽离为单个文件,我们选择仅在生成模式下,这样便于缓存
? Do you want to extract CSS for every file? Only for Production# Prettier 是一个流行的代码格式化工具,选择是否都可以
? Do you like to install prettier to format generated configuration? Yes# 我们选择npm进行包管理,当然pnpm和yarn也可以
? Pick a package manager: pnpm# 选择重写 overwrite ,重写package.json文件
? Overwrite package.json? (ynarxdeiH)
回答完毕后,会自动安装相关依赖包,包括:
@babel/core, @babel/preset-env, babel-loader,
css-loader, style-loader, postcss, postcss-loader,
autoprefixer, mini-css-extract-plugin,
html-webpack-plugin, webpack-dev-server, prettier 等
三、配置文件说明
生成的 webpack.config.js
示例代码如下:
// Generated using webpack-cli https://github.com/webpack/webpack-cli
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const isProduction = process.env.NODE_ENV == 'production';
const stylesHandler = isProduction ? MiniCssExtractPlugin.loader : 'style-loader';const config = {// 入口文件entry: './src/index.js',// 出口文件夹output: {path: path.resolve(__dirname, 'dist'),},// 开发服务器devServer: {open: true,host: 'localhost',},// webpack插件plugins: [new HtmlWebpackPlugin({template: 'index.html',}),// Add your plugins here// Learn more about plugins from https://webpack.js.org/configuration/plugins/],// webpack解析器module: {rules: [{test: /\.(js|jsx)$/i,loader: 'babel-loader',},{test: /\.s[ac]ss$/i,use: [stylesHandler, 'css-loader', 'postcss-loader', 'sass-loader'],},{test: /\.css$/i,use: [stylesHandler, 'css-loader', 'postcss-loader'],},{test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,type: 'asset',},// Add your rules for custom modules here// Learn more about loaders from https://webpack.js.org/loaders/],},
};module.exports = () => {if (isProduction) {config.mode = 'production';config.plugins.push(new MiniCssExtractPlugin());} else {config.mode = 'development';}return config;
};
可以使用的命令在package.json中可以看到
"scripts": {"test": "echo \"Error: no test specified\" && exit 1","build": "webpack --mode=production --node-env=production","build:dev": "webpack --mode=development","build:prod": "webpack --mode=production --node-env=production","watch": "webpack --watch","serve": "webpack serve"},
四、项目启动开发服务器热模块替换
运行npm run serve
命令
E:\Code\Node-Code\webpack_test>npm run serve
> webpack serve[webpack-cli] Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.- options has an unknown property '_assetEmittingPreviousFiles'. These properties are valid:object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, ipc?, liveReload?, onListening?, open?, port?, proxy?, server?, app?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? }
用内置开发服务器启动项目报错,将webpack-cli
版本变成v5
版本
npm uninstall webpack-cli
npm i -D webpack-cli@5
重新启动项目,提示我们缺少@babel/plugin-syntax-dynamic-import
依赖,关闭服务器,安装依赖
npm install -D @babel/plugin-syntax-dynamic-import
重新执行npm run serve
即可在浏览器看到项目首页
因为没有开启HMR热模块替换,在编辑器中修改内容浏览器刷新才可以看到变换,我们在webpack.config.js
修改开发服务器配置
devServer: {open: true, // 自动打开浏览器host: 'localhost', // 设置本机为主机地址port: 8080, // 添加端口设置hot: true, // 开启热更新static: {directory: path.join(__dirname, 'dist'), // 设置静态资源路径},historyApiFallback: true, // 支持 HTML5 History API},
目录结构即内容如下:
index.html
<!DOCTYPE html>
<html><head><meta charset="utf-8" /><title>Webpack</title></head><body><div id="app"></div><!-- Webpack 会自动注入打包后的脚本 --></body></html>
index.js
const app = document.getElementById('app');
app.innerHTML = '<h1>Hello, Webpack Hot Update!</h1>';
五、常用命令整理
启动开发服务
npm run serve
构建项目
npm run build
六、更多资源推荐
官方配置文档: 链接: webpack初始配置
之后,我们就可以根据项目需求在webpack.config.js配置Loader和Plugin来扩展webpack的功能