目录
1.webpack基础配置
#初始化项目
#安装本地webpack
#运行webpack命令进行打包
#使用VS插件code runner
#手动配置webpack
#直接使用 npm run build 命令执行打包
#生成本地服务配置
#自动生成dist中的index.html文件 - 安装html-webpack-plugin插件
#生产环境下进行文件压缩
yarn init -y
yarn add webpack webpack-cli -D
-D --当前为开发依赖 上线无效
npx webpack
会自动生成dist-->main.js
在扩展程序中安装code runner插件,然后在指定文件,如main.js中,右键run code直接执行
- 默认配置名字 webpack.config.js
- 手动指定配置文件名
npx webpack --config 自定义配置文件名
在package.json中加入
"scripts": {
"build":"webpack --config webpack.config.js"
},
yarn add webpack-dev-server -D
-开启服务(默认 http://localhost:8080/ 显示目录文件)
npx webpack-dev-server
-在package.json-->scripts中配置
"dev":"webpack-dev-server"
-在webpack.config.js-->module.exports中添加配置
devServer:{//开发服务器的配置
port:3000,
progress:true, //滚动条
contentBase:'./dist' ,//静态服务目录
compress:true //压缩
},
-运行
npm run dev
通过http://localhost:3000 打开dist-->index.html文件
yarn add html-webpack-plugin -D
-在webpack.config.js中添加
let HtmlpackPlugin = require('html-webpack-plugin')
-在webpack.config.js-->module.exports中添加
plugins:[ //数组,放着所有的webpack插件
new HtmlpackPlugin({
template:'./src/index.html', //模板文件,src下一个空html格式文件
filename:'index.html' //生成的文件名
})
]
-重新打包
npm run build
-启动服务
npm run dev
-在webpack.config.js-->module.exports中
--修改mode参数为production
--plugins-->HtmlpackPlugin中添加
minify:{
removeAttributeQuotes:true,//去掉html标签中的双引号
collapseWhitespace:true,//折叠空行
},
hash:true //为每个html增加hash戳
--为生成的bundle.js文件名添加hash,在output->filename中添加
filename:'bundle.[hash:8].js' //冒号后为hash位数