用Webpack 基础配置快速搭建项目开发环境

Webpack 是一个现代 JavaScript 应用程序的静态模块打包工具,但是Webpack有大量的配置项,对新手不太友好,但是我们可以根据webpack-cliinit命令根据项目需求快速生成webpack的配置文件,本文将手把手教你如何用 Webpack 和 npm 快速搭建一个基础开发环境。

一、初始化项目

首先,新建项目文件夹并初始化:

bash 复制代码
mkdir webpack_test
cd webpack_test
npm init -y

二、使用 webpack-cli 初始化配置

Webpack 提供了快速初始化配置的能力:

bash 复制代码
npx webpack init

报错后提示我们安装webpack-cli,输入yes

bash 复制代码
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命令无法识别

bash 复制代码
[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

bash 复制代码
npm i -D @webpack-cli

再安装@webpack-cli/init,错误提示webpack-cli版本太高了,package.json中也可以看到webpack-cli的版本是6.0.1

bash 复制代码
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
json 复制代码
{
  "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版本

bash 复制代码
npm i -D webpack-cli@4

降低到v4后,再运行npx webpack init,提示我们安装@webpack-cli/generators,我们选择yes

bash 复制代码
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

安装好后就到配置询问环节了,示例如下:

bash 复制代码
? Which of the following JS solutions do you want to use? (Use arrow keys)
> none
  ES6
  Typescript

我选的配置如下:

bash 复制代码
# 选择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)

回答完毕后,会自动安装相关依赖包,包括:

txt 复制代码
@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 示例代码如下:

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中可以看到

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命令

bash 复制代码
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版本

bash 复制代码
npm uninstall webpack-cli
npm i -D webpack-cli@5

重新启动项目,提示我们缺少@babel/plugin-syntax-dynamic-import依赖,关闭服务器,安装依赖

bash 复制代码
npm install -D @babel/plugin-syntax-dynamic-import

重新执行npm run serve即可在浏览器看到项目首页

因为没有开启HMR热模块替换,在编辑器中修改内容浏览器刷新才可以看到变换,我们在webpack.config.js修改开发服务器配置

js 复制代码
devServer: {
        open: true, // 自动打开浏览器
        host: 'localhost', // 设置本机为主机地址
        port: 8080, // 添加端口设置
        hot: true,  // 开启热更新
        static: {
            directory: path.join(__dirname, 'dist'),  // 设置静态资源路径
        },
        historyApiFallback: true,  // 支持 HTML5 History API
    },

目录结构即内容如下:

index.html

html 复制代码
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Webpack</title>
    </head>
    <body>
        <div id="app"></div>
         <!-- Webpack 会自动注入打包后的脚本 -->
    </body>
    
</html>

index.js

js 复制代码
const app = document.getElementById('app');
app.innerHTML = '<h1>Hello, Webpack Hot Update!</h1>';

五、常用命令整理

启动开发服务

bash 复制代码
npm run serve

构建项目

bash 复制代码
npm run build

六、更多资源推荐

官方配置文档: 链接: webpack初始配置

之后,我们就可以根据项目需求在webpack.config.js配置Loader和Plugin来扩展webpack的功能

相关推荐
崔庆才丨静觅28 分钟前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60611 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了1 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅1 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅2 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅2 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment2 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅2 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊3 小时前
jwt介绍
前端
爱敲代码的小鱼3 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax