webpack使用教程
1.新建相关目录
- 新建webpack工作根目录 webpack-study
- 在webpack根目录下新建dist,src文件夹
- 在src目录下新建css,images,js文件夹和main.js,index.html文件(main.js 是我们项目的JS入口文件)
2.运行npm init
初始化项目
D:\workspace\springBoot\src\main\resources\webpack-study>npm init -y
Wrote to D:\workspace\springBoot\src\main\resources\webpack-study\package.json:
{
"name": "webpack-study",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
3.下载jquery.js
通过命令cnpm i jquery -S下载jquery,有兴趣的可以访问资源官网查看下载命令
D:\workspace\springBoot\src\main\resources\webpack-study>cnpm i jquery -S
√ Installed 1 packages
√ Linked 0 latest versions
√ Run 0 scripts
√ All packages installed (1 packages installed from npm registry, used 562ms(network 559ms), speed 768.08kB/s, json 1(5.93kB), tarball 423.43kB)
4.编写案例
4.1 初始案例
main.js
// 1. 导入 Jquery
// import *** from *** 是ES6中导入模块的方式
// 由于 ES6的代码,太高级了,浏览器解析不了,所以,这一行执行会报错
import $ from 'jquery'
// 注意: webpack 处理第三方文件类型的过程:
// 1. 发现这个 要处理的文件不是JS文件,然后就去 配置文件中,查找有没有对应的第三方 loader 规则
// 2. 如果能找到对应的规则, 就会调用 对应的 loader 处理 这种文件类型;
// 3. 在调用loader 的时候,是从后往前调用的;
// 4. 当最后的一个 loader 调用完毕,会把 处理的结果,直接交给 webpack 进行 打包合并,最终输出到 bundle.js 中去
$(function () {
$('li:odd').css('backgroundColor', 'yellow')
$('li:even').css('backgroundColor', function () {
return '#' + 'D97634'
})
})
执行命令
命令格式: webpack 要打包的文件的路径 打包好的输出文件的路径
webpack ./src/main.js -o ./dist --mode=development
命令结果
D:\workspace\webpack-study>webpack ./src/main.js -o ./dist --mode=development
asset main.js 326 KiB [emitted] (name: main)
runtime modules 937 bytes 4 modules
cacheable modules 284 KiB
./src/main.js 2.46 KiB [built] [code generated]
./node_modules/jquery/dist/jquery.js 282 KiB [built] [code generated]
webpack 5.28.0 compiled successfully in 297 ms
dist 目录下多了main.js文件
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="..\dist\main.js"></script>
</head>
<body>
<ul>
<li>这是第1个li</li>
<li>这是第2个li</li>
<li>这是第3个li</li>
<li>这是第4个li</li>
<li>这是第5个li</li>
<li>这是第6个li</li>
</ul>
</body>
</html>
4.2 案例优化
在根目录下新增webpack.config.js文件,配置入口文件和输出文件,这样我们的命令就可以简化为" webpack --mode=development "
webpack.config.js
const path = require('path')
module.exports = {
mode: 'development',
entry: path.join(__dirname, './src/main.js'), // 入口,表示,要使用 webpack 打包哪个文件
output: { // 输出文件相关的配置
path: path.join(__dirname, './dist'), // 指定 打包好的文件,输出到哪个目录中去
filename: 'bundle.js' // 这是指定 输出的文件的名称
}
};
在package.json新增"dev": “webpack --mode=development”,这样我们就可以使用npm命令(npm run dev)
package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack --mode=development"
}
5.webpack-dev-server教程
安装webpack-dev-server
cnpm i webpack-dev-server -g
启动服务
webpack-dev-server
--实际运行结果
D:\workspace\webpack-study>webpack-dev-server
i 「wds」: Project is running at http://localhost:8080/
i 「wds」: webpack output is served from /
i 「wds」: Content not from webpack is served from D:\workspace\webpack-study
i 「wdm」: asset bundle.js 693 KiB [emitted] (name: main)
runtime modules 1.25 KiB 6 modules
cacheable modules 620 KiB
modules by path ./node_modules/_webpack-dev-server@3.11.2@webpack-dev-server/client/ 20.9 KiB 10 modules
modules by path ./node_modules/_html-entities@1.4.0@html-entities/lib/*.js 61 KiB 5 modules
modules by path ./node_modules/_querystring@0.2.0@querystring/*.js 4.51 KiB
./node_modules/_querystring@0.2.0@querystring/index.js 127 bytes [built] [code generated]
./node_modules/_querystring@0.2.0@querystring/decode.js 2.34 KiB [built] [code generated]
./node_modules/_querystring@0.2.0@querystring/encode.js 2.04 KiB [built] [code generated]
modules by path ./node_modules/_webpack@5.28.0@webpack/hot/*.js 1.42 KiB
./node_modules/_webpack@5.28.0@webpack/hot/emitter.js 75 bytes [built] [code generated]
./node_modules/_webpack@5.28.0@webpack/hot/log.js 1.34 KiB [built] [code generated]
modules by path ./node_modules/_url@0.11.0@url/*.js 23.1 KiB
./node_modules/_url@0.11.0@url/url.js 22.8 KiB [built] [code generated]
./node_modules/_url@0.11.0@url/util.js 314 bytes [built] [code generated]
./node_modules/webpack/hot/ sync nonrecursive ^\.\/log$ 170 bytes [built] [code generated]
webpack 5.28.0 compiled successfully in 481 ms
i 「wdm」: Compiled successfully.
浏览器输入其服务输出地址http://localhost:8080/可以查看相关的信息
注意:当你访问http://localhost:8080/bundle.js是会发现也有一个bundle.js文件但是本地是不存在的。这是因为webpack-dev-server帮我们打包生成的bundle.js文件并没有写入实际磁盘,而是直接托管到虚拟内存中,所以我们在根目录中无法找到bundle.js,但是由于http://localhost:8080/bundle.js可以访问到它,所以我们可以在需要的页面通过<script src="/bundle.js"></script>
引入资源。并且webpack-dev-server并不会更新或生成/dist/bundle.js。
5.1 webpack-dev-server命令参数
第一种方式:package.json
"scripts": {
"devser": "webpack-dev-server --open --port 3000 --contentBase src --hot",
}
第二种方式 webpack.config.js
devServer: { // 这是配置 dev-server 命令参数的第二种形式,相对来说,这种方式麻烦一些
// --open --port 3000 --contentBase src --hot
open: true, // 自动打开浏览器
port: 3000, // 设置启动时候的运行端口
contentBase: 'src', // 指定托管的根目录
hot: true // 启用热更新
}
上面的命令意思是当服务启动,直接打开浏览器(–open),服务的端口是–open(–port 3000),默认地址路径为src(–contentBase src),并且js改动后不需要刷新浏览器,就能在页面上生效(–hot)
常见命令参数
devServer: {
contentBase: "./",//本地服务器所加载的页面所在的目录
historyApiFallback: true,//不跳转
host:'0.0.0.0', //IP地址
port:7000, //端口
hot:true,
inline: true,//实时刷新
hot:true,//Enable webpack's Hot Module Replacement feature
compress:true,//Enable gzip compression for everything served
overlay: true, //Shows a full-screen overlay in the browser
stats: "errors-only" ,//To show only errors in your bundle
open:true, //When open is enabled, the dev server will open the browser.
proxy: {
"/api": {
target: "http://localhost:3000",
pathRewrite: {"^/api" : ""}
}
},//重定向
}
6 webpack插件(plugin)
6.1 安装
npm install --save-dev html-webpack-plugin
6.2 基本使用
webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'development',
entry: path.join(__dirname, './src/main.js'), // 入口,表示,要使用 webpack 打包哪个文件
output: { // 输出文件相关的配置
path: path.join(__dirname, './dist'), // 指定 打包好的文件,输出到哪个目录中去
filename: 'bundle.js' // 这是指定 输出的文件的名称
},
devServer: { // 这是配置 dev-server 命令参数的第二种形式,相对来说,这种方式麻烦一些
open: true, // 自动打开浏览器
port: 3000, // 设置启动时候的运行端口
contentBase: 'src', // 指定托管的根目录
hot: true // 启用热更新 的 第1步
},
plugins: [ // 配置插件的节点
new HtmlWebpackPlugin({ // 创建一个 在内存中 生成 HTML 页面的插件
template: path.join(__dirname, './src/index.html'), // 指定 模板页面,将来会根据指定的页面路径,去生成内存中的 页面
filename: 'index.html' // 指定生成的页面的名称
})
]
};
运行结果
从运行结果上可以看出 <script src="/bundle.js"></script><script defer src="bundle.js"></script>
其中<script src="/bundle.js"></script>
是我们自己手写的而第二个<script defer src="bundle.js"></script>
是插件帮我们生成的,所以使用html-webpack-plugin插件后,我们无需手写<script src="/bundle.js"></script>
7 loader
webpack 只能理解 JavaScript 和 JSON 文件,这是 webpack 开箱可用的自带能力。loader 让 webpack 能够去处理其他类型的文件,并将它们转换为有效 模块,以供应用程序使用,以及被添加到依赖图中。
7.1 支持加载css文件
在 css下新建index.css文件
index.css
li{
list-style: none;
}
你可以使用 loader 告诉 webpack 加载 CSS 文件,或者将 TypeScript 转为 JavaScript。为此,首先安装相对应的 loader:
npm install --save-dev css-loader style-loader
main.js
// 使用 import 语法,导入 CSS样式表
import './css/index.css'
webpack.config.js
module: { // 这个节点,用于配置 所有 第三方模块 加载器
rules: [ // 所有第三方模块的 匹配规则
{ test: /\.css$/, use: ['style-loader','css-loader'] } // 配置处理 .css 文件的第三方loader 规则
]
}
运行成功
加入index.css前
加入index.css后
对比可以发现加入index.css样式后●不见了,说明webpack成功引入了index.css
7.2 支持加载图片
安装依赖
npm install --save-dev url-loader
webpack.config.js
{ test: /\.(jpg|png|gif|bmp|jpeg)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 20480
}
}
]
}
7.3 支持转义 ES6/ES7/JSX
安装依赖
npm install -D babel-loader @babel/core @babel/preset-env webpack
npm i @babel/plugin-proposal-class-properties -D
webpack.config.js
{ test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: [
[require("@babel/plugin-proposal-class-properties"), { "loose": true }]
]
}
}
}
上一章:windows安装webpack和相关工具
下一章:webpack中使用vue
更多学习在官方网址:webpack 官方中文文档