npx 和webpack 手工创建项目
随着前端技术的不断发展,项目的复杂性也在不断提高。为了能够高效地管理前端项目,打包工具成为了必须的工具。而在这些打包工具中,Webpack 是一个非常流行的选择。
但是无论你用webpack、vue、react等构建一定要注意关键点,共通性
1、本身都是node.js项目
2、package.json是核心(包括package-lock.json)
3、node_modules目录是项目依赖包,都是通过npm install <package-name> 安装上的
项目都会经过一个开发、测试、编译、部署等全周期流程。然后各自都会有自己的一些开发特点。
比如: webpack会有webpack.config.js文件
vue会有 vue.config.js等
webpack-cli项目地址:
git clone https://github.com/webpack/webpack-cli
源代码目录 ...\webpack-cli\test 里面也有一些实例
创建my-webpack-k项目(手工建一个文件夹即可)
npm init 命令会创建一个 package.json 文件,用于描述项目的元数据。其中 -y 参数表示使用默认设置创建 package.json 文件。
D:\nodevue\my-webpack-k>npm init -y
Wrote to D:\nodevue\my-webpack-k\package.json:
{
"name": "my-webpack-k",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs"
}
第一步:安装 Webpack
首先,我们需要安装 Webpack。打开命令行,输入以下命令:
npm install webpack webpack-cli --save-dev
D:\nodevue\my-webpack-k>npm install webpack webpack-cli --save-dev added 119 packages, and audited 120 packages in 7s 19 packages are looking for funding run `npm fund` for details found 0 vulnerabilities
这个命令会自动将 webpack 安装到 node_modules 目录下(node_module目录没有会自动创建),并将 webpack 和 webpack-cli 添加到 devDependencies 中。
查看npm info webpack 包是否安装
D:\nodevue\my-webpack-k>npm info webpack webpack@5.103.0 | MIT | deps: 25 | versions: 862 Packs ECMAScript/CommonJs/AMD modules for the browser. Allows you to split your codebase into multiple bundles, which can be loaded on demand. Supports loaders to preprocess files, i.e. json, jsx, es7, css, less, ... and your custom stuff. https://github.com/webpack/webpack bin: webpack dist .tarball: https://registry.npmjs.org/webpack/-/webpack-5.103.0.tgz .shasum: 17a7c5a5020d5a3a37c118d002eade5ee2c6f3da .integrity: sha512-HU1JOuV1OavsZ+mfigY0j8d1TgQgbZ6M+J75zDkpEAwYeXjWSqrGJtgnPblJjd/mAyTNQ7ygw0MiKOn6etz8yw== .unpackedSize: 5.7 MB dependencies: @types/eslint-scope: ^3.7.7 browserslist: ^4.26.3 json-parse-even-better-errors: ^2.3.1 @types/estree: ^1.0.8 chrome-trace-event: ^1.0.2 loader-runner: ^4.3.1 @types/json-schema: ^7.0.15 enhanced-resolve: ^5.17.3 mime-types: ^2.1.27 @webassemblyjs/ast: ^1.14.1 es-module-lexer: ^1.2.1 neo-async: ^2.6.2 @webassemblyjs/wasm-edit: ^1.14.1 eslint-scope: 5.1.1 schema-utils: ^4.3.3 @webassemblyjs/wasm-parser: ^1.14.1 events: ^3.2.0 tapable: ^2.3.0 acorn-import-phases: ^1.0.3 glob-to-regexp: ^0.4.1 terser-webpack-plugin: ^5.3.11 acorn: ^8.15.0 graceful-fs: ^4.2.11 watchpack: ^2.4.4 (...and 1 more.) ....
查看webpack-cli信息的包信息
D:\nodevue\my-webpack-k>npm info webpack-cli webpack-cli@6.0.1 | MIT | deps: 13 | versions: 125 CLI for webpack & friends https://github.com/webpack/webpack-cli/tree/master/packages/webpack-cli keywords: webpack, cli, scaffolding, module, bundler, web bin: webpack-cli dist .tarball: https://registry.npmjs.org/webpack-cli/-/webpack-cli-6.0.1.tgz .shasum: a1ce25da5ba077151afd73adfa12e208e5089207 .integrity: sha512-MfwFQ6SfwinsUVi0rNJm7rHZ31GyTcpVE5pgVA3hwFRb7COD4TzjUUwhGWKfO50+xdc2MQPuEBBJoqIMGt3JDw== .unpackedSize: 109.6 kB dependencies: @discoveryjs/json-ext: ^0.6.1 commander: ^12.1.0 interpret: ^3.1.1 @webpack-cli/configtest: ^3.0.1 cross-spawn: ^7.0.3 rechoir: ^0.8.0 @webpack-cli/info: ^3.0.1 envinfo: ^7.14.0 webpack-merge: ^6.0.1 @webpack-cli/serve: ^3.0.1 fastest-levenshtein: ^1.0.12 colorette: ^2.0.14 import-local: ^3.0.2 ....
查看当前项目下的第三方包和全局包
npm install <package-name> 表示安装在本项目的 node_modules目录下,初始安装时会生成node_modules目录
D:\nodevue\my-webpack-k>npm list my-webpack@1.0.0 D:\nodevue\my-webpack `-- webpack-cli@6.0.1
D:\nodevue\my-webpack-k>npm install webpack(安装一个webpack包,注意如果加上 -g ,包会安装在全局目录下,而不是当前项目下)
up to date, audited 120 packages in 1s
19 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
D:\nodevue\my-webpack-k>npm list (再次查下)
my-webpack@1.0.0 D:\nodevue\my-webpack
+-- webpack-cli@6.0.1
`-- webpack@5.103.0
D:\nodevue\my-webpack-k>npm list -g C:\Users\king\AppData\Roaming\npm +-- @modelcontextprotocol/server-everything@2025.11.25 +-- @vue/cli@5.0.9 +-- create-react-app@5.1.0 +-- download@8.0.0 +-- mocha@11.7.5 `-- npx@10.2.2
查看package.json(这个文件里面尽量先不要有中文,否则你打包的时候,莫名其妙会导致npx webpack 命令打包时会认为配置文件出错)
{ "name": "my-webpack-k", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "type": "commonjs", "devDependencies": { "webpack": "^5.103.0", "webpack-cli": "^6.0.1" } #自动添加进去 }
第三步:创建文件
我们需要创建入口文件和输出文件。在项目目录中创建一个名为 src 的文件夹,并在其中创建一个 index.js 文件。加入代码
console.log('aozhjin');
接下来,我们需要创建一个 dist 文件夹,用于存放输出文件。
第四步:编写配置文件
为了使用 Webpack,我们需要编写一个配置文件。在项目目录中创建一个名为 webpack.config.js 的文件,并输入以下代码:
const path = require('path'); module.exports = { entry: './src/index.js', output: { filename: 'main.js', path: path.resolve(__dirname, 'dist'), }, };
webpack.config.js配置文件的选项参考:
https://webpack.js.org/configuration/
这个配置文件说明了 Webpack 的输入和输出。
第五步:使用 Webpack 打包项目
1、方式一
在当前项目下,使用npx webpack 命令 打包项目。在命令行中请输入以下命令:
D:\nodevue\my-webpack-k>npx webpack --mode=development (npx webpack) asset main.js 1.3 KiB [emitted] (name: main) ./src/index.js 105 bytes [built] [code generated] webpack 5.103.0 compiled successfully in 61 ms
--mode=development 请参考: https://webpack.js.org/configuration/mode/
--mode=<development,production,none>
这个命令会使用 Webpack 对 index.js 文件进行打包,并生成一个名为 main.js 的输出文件。输出文件位于 dist 文件夹中。
现在,你可以在命令行中输入以下命令来运行输出文件:
D:\nodevue\my-webpack-k>node dist/main.js
aozhejin
2、方式二
增加项目中的package.json文件,增加一行 "build":"webpack" ,来调用 webpack组件
{ "name": "my-webpack-k", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "echo \"hello\" && exit 1", "build":"webpack" }, "keywords": [], "author": "", "license": "ISC", "type": "commonjs", "devDependencies": { "webpack": "^5.103.0", "webpack-cli": "^6.0.1" } }
执行npm run build, 如果使用npx webpack 就更简洁,直接调用了webpack,不需要额外配置 ,而npm需要在package.json配置中,增加 "build":"webpack" ,
实际build名称你可以改成任意简单的名字都可以,比如npm run b 只要对应在scripts标签中 写明 "b": "webpack" 即可
下面执行编译:
D:\nodevue\my-webpack-k>npm run build > my-webpack-k@1.0.0 build > webpack asset main.js 24 bytes [emitted] [minimized] (name: main) ./src/index.js 24 bytes [built] [code generated] WARNING in configuration The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment. You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/ webpack 5.103.0 compiled with 1 warning in 138 ms
第六步、增强html
Webpack 本身只能处理 JS 模块,如需编译html ,需安装html-webpack-plugin插件(Plugin) 用于扩展其功能。
github地址: https://github.com/jantimon/html-webpack-plugin
HtmlWebpackPlugin是一个专为Webpack设计的插件,主要功能是在构建过程中自动生成HTML文件,并将打包后的资源(如JavaScript、CSS文件)自动注入到生成的HTML中。这大大简化了前端项目的构建流程,确保资源路径的正确性。
安装: npm install html-webpack-plugin --save-dev
D:\nodevue\my-webpack-k>npm install html-webpack-plugin --save-dev added 31 packages, and audited 151 packages in 5s 29 packages are looking for funding run `npm fund` for details found 0 vulnerabilities --save-dev 将自动更新package.json
修改webpack.config.js配置(红色即为增加部分)
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { filename: 'main.js', path: path.resolve(__dirname, 'dist'), }, optimization: { chunkIds: 'named', }, plugins: [ new HtmlWebpackPlugin({ title: 'Webpack html', template: path.join(__dirname, 'src/index.html') }) ] };
src下新建index.html
aozhejin
他会自动把src下的index.html 编译到dist/index.html里面
<head><script defer="defer" src="main.js"></script></head>aozhejin
第七、html编译实例, 红色部分修改如下
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { filename: 'main.js', path: path.resolve(__dirname, 'dist'), }, optimization: { chunkIds: 'named', }, plugins: [ new HtmlWebpackPlugin({ title: 'Webpack html', template: './src/template.html', filename: 'test.html', }) ] };
在src下创建 template.html 自定义模板如下
<!-- src/template.html --> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 脚本将自动注入此处或头部(根据inject配置) --> <title><%= htmlWebpackPlugin.options.title %></title> <link rel="icon" href="<%= htmlWebpackPlugin.options.favicon %>"> </head> <body> <div id="app"></div> </body> </html>
编译后,template.html 模板文件将作为test.html的生成模板 ,一些变量会注入到test.html中,test.html会被编译到dist下,main.js会自动添加到最终的test.html页面里面
生成的test.html如下:
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Webpack html</title><link rel="icon" href="false"><script defer="defer" src="main.js"></script></head><body><div id="app"></div></body></html>
第八、复杂一些的应用配置
继续修订 webpack.config.js文件
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = {
showerrors
cache:false, //开发中禁用缓存 entry: './src/index.js', output: { filename: 'main.js', path: path.resolve(__dirname, 'dist'), }, optimization: { chunkIds: 'named', }, plugins: [ new HtmlWebpackPlugin({ title: '我的html', template: './src/template.html', filename: 'test.html', meta: { viewport: 'width=device-width, initial-scale=1.0' }, minify: { //优化一些页面的设置 removeComments: true, //删除注解 collapseWhitespace: true, removeAttributeQuotes: true }, inject: 'body', chunks: ['main'], excludeChunks: ['dev-helper'], hash: true, xhtml: true, scriptLoading: 'defer' }) ] };
修改webpack.config.js文件
增加一个页面about.html,相关的webpack.config.js的变化
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { cache: false, entry: './src/index.js', output: { filename: 'main.js', path: path.resolve(__dirname, 'dist'), }, optimization: { chunkIds: 'named', }, plugins: [ new HtmlWebpackPlugin({ template: './src/template.html', title: 'about page', filename: 'about.html', //create about.html }), new HtmlWebpackPlugin({ title: 'test page', template: './src/template.html', filename: 'test.html', //create test.html meta: { viewport: 'width=device-width, initial-scale=1.0' }, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, inject: 'body', chunks: ['main'], excludeChunks: ['dev-helper'], hash: true, xhtml: true, scriptLoading: 'defer' }), ] };
第九、解决编码问题
使用的是webpack-encoding-plugin插件,npm install webpack-encoding-plugin 安装,同时在webpack.config.json中进行配置
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const EncodingPlugin = require('webpack-encoding-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); module.exports = { cache: false, entry: './src/index.js', output: { filename: 'main.js', path: path.resolve(__dirname, 'dist'), }, optimization: { chunkIds: 'named', }, plugins: [ new CleanWebpackPlugin(), new EncodingPlugin({ encoding: 'UTF-8' }), new HtmlWebpackPlugin({ template: './src/template/about.html', title: 'about page', filename: 'about.html', }), new HtmlWebpackPlugin({ template: './src/template/us.html', title: 'us page', filename: 'us.html', }), new HtmlWebpackPlugin({ template: './src/template/test.html', title: 'test page', filename: 'test.html', meta: { viewport: 'width=device-width, initial-scale=1.0' }, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, inject: 'body', chunks: ['main'], excludeChunks: ['dev-helper'], hash: true, xhtml: true, scriptLoading: 'defer' }), ] };
第十、启动本地服务器
npm run http (http是我自己定义的命令) ,我在package.json中添加了
"http":"webpack serve"
它会调用 webpack serve 这个组件
如果本地没有安装,则询问你是否要下载 webpack-dev-server 这个组件,键入y 即可安装 ,同时安装完毕,本地会自动更新package.json,即红色的部分
默认端口是8080, 实现的是热更新,一旦修改代码,立即更新,无需手动打包
{ "name": "my-webpack-k", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "echo \"hello\" && exit 1", "build": "webpack", "http":"webpack serve" }, "keywords": [], "author": "", "license": "ISC", "type": "commonjs", "devDependencies": { "html-webpack-plugin": "^5.6.5", "webpack": "^5.103.0", "webpack-cli": "^6.0.1", "webpack-dev-server": "^5.2.2" }, "dependencies": { "webpack-encoding-plugin": "^0.3.1" } }
十一、项目复制
如果你想保留现场,可以复制copy整个项目,项目依然会很正常的运行。
十二、clean-webpack-plugin 安装
clean-webpack-plugin是一个清除文件的插件。在每次打包后,磁盘空间会存有打包后的资源,在再次打包的时候,我们需要先把本地已有的打包后的资源清空。
需要 npm install clean-webpack-plugin 进行安装
里面会有一些配置的方法以及使用方法等。
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const EncodingPlugin = require('webpack-encoding-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); module.exports = { cache: false, entry: './src/index.js', output: { filename: 'main.js', path: path.resolve(__dirname, 'dist'), }, optimization: { chunkIds: 'named', }, plugins: [ new CleanWebpackPlugin(), new EncodingPlugin({ encoding: 'UTF-8' }), new HtmlWebpackPlugin({ template: './src/template/about.html', title: 'about page', filename: 'about.html', }), new HtmlWebpackPlugin({ template: './src/template/us.html', title: 'us page', filename: 'us.html', }), new HtmlWebpackPlugin({ template: './src/template/test.html', title: 'test page', filename: 'test.html', meta: { viewport: 'width=device-width, initial-scale=1.0' }, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, inject: 'body', chunks: ['main'], excludeChunks: ['dev-helper'], hash: true, xhtml: true, scriptLoading: 'defer' }), ] };

浙公网安备 33010602011771号