这是我参与11月更文挑战的第13天,活动详情查看:2021最后一次更文挑战
webpack-dev-server的基本使用
1.webpack-dev-server自动打包工具
用于开发时,需要频繁的修改js文件,修改完成后仍需要用webpack打包
- 强制要在本地项目安装webpack和webpack-cli
npm install webpack wepack-cli -D
- 安装webpack-dev-server
安装命令
npm i webpack-dev-server -D
该命令是在项目中安装的webpack-dev-server工具
- 配置webpack-dev-server 需要在package.json文件中配置webpack-dev-server
新增dev属性
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server",
"build": "webpack --config webpack.config.js"
}
- 检验是否安装成功 运行webpack-dev-server命令
npm run dev
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:\wordspace\webpackTest
i 「wdm」: Hash: 3db249357d709d94623d
Version: webpack 4.41.5
保存时有自动编译就是成功
Child html-webpack-plugin for "index.html":
1 asset
Entrypoint undefined = index.html
4 modules
i 「wdm」: Compiled successfully.
2.webpack-dev-server的运行
- 访问打包好的js文件:访问端口+文件名.js(控制台有提示)
打包会按照webpack.config.js中的配置,但是不会参照配置文件中的输出文件,它会将js文件打包到内存中
- 在页面中使用:引入src=/文件名.js(控制台有提示)
页面中看不到这个.js文件,webpack-dev-server自动打包生产的js文件不会放到实际的物理磁盘中,而是直接放在内存中,速度更快。
- 等学到了使用html-webpack-plugins,使用起来就更方便了
webpack-dev-server的命令参数
1.基本命令:webpack-dev-server
加在package.json中scripts对象中
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack-dev-server !!!!!加在这里!!!!!",
"build": "webpack --config webpack.config.js"
},
- 自动打包后自动打开浏览器
--open加在scripts中的dev
- 修改端口
--port 端口号
-
自动打开某个路径
--contentBase路径 -
热重载
--hot局部更新,不整个文件重新打包
可以使浏览器异步刷新
2.webpack-dev-server第二种配置命令方式
webpack-dev-server配置命令
在webpack.config.js中进行配置
- 命令配置 在webpack.config.js中的module.exports中增加
devServer:{
open;true,
port:端口号,
contentBase:'路径',
hot:true
}
- 启用热更新
hot:true
获取webpack对象
const webpack=require('webpack')
在webpack.config.js中的module.exports中增加
//配置热更新的模块对象
plugins:[
new webpack.HotModuleReplacementPlugins({
template:path.join(__dirname,'需要打包的html文件路径'),
filename:'index.html'//输出的文件路径,用于直接访问
})
]