webpack5使用
1.安装依赖包
- 创建一个文件夹
- npm init 生成package.json文件夹 然后安装依赖
cnpm webpack webpack-cli html-webpack-plugin webpack-dev-server cross-env -D
- 新建一个webpack.config.js文件写配置
- 新建src/inde.js 文件
- 新建模板文件 src/index.html
- packjson命令
"scripts": {
"build": "webpack", // 直接打包用
"start": "webpack serve", // 启动服务器 可以开发用
},
- 配置好entry 和 output等基本信息就可以使用基础版本的了
module.exports = {
mode: 'development', // 配置的模式
devtool: 'source-map', // 调试工具
context: process.cwd(), // node命令运行的进程的当前目录 就是这个项目根目录
entry: {
main: './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
module: {
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
minify: {
// 压缩html
collapseWhitespace: true, // 压缩空白
removeComments: true // 去除注释
}
}),
]
};
2.安装插件
2.1 日志美化安装
- friendly-errors-webpack-plugin 可以识别某类别的 webpack 错误,并清理,聚合和优先级,以提供更好的开发人员体验
cnpm i friendly-errors-webpack-plugin node-notifier -D
- 使用错误提示插件
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
const notifier = require('node-notifier');
const icon = path.join(__dirname, 'icon.jpg');
plugins: [
...
+ new FriendlyErrorsWebpackPlugin({
+ onErrors: (severity, errors) => {
+ let error = errors[0];
+ notifier.notify({
+ title: 'webpack编译失败了',
+ message: severity + ':' + error.name,
+ subtitle: error.file || '',
+ icon
+ });
+ }
+ }),
]
2.2 速度分析
- speed-measure-webpack5-plugin 进行分析打包速度
cnpm i speed-measure-webpack5-plugin -D
const SpeedMeasureWebpack5Plugin = require('speed-measure-webpack5-plugin');
const smw = new SpeedMeasureWebpack5Plugin();
module.exports = smw.wrap({
// 配置文件
mode: 'development', // 配置的模式
devtool: 'source-map', // 调试工具
context: process.cwd(), // node命令运行的进程的当前目录 就是这个项目根目录
entry: {
main: './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
module: {
},
plugins: [
]
})
时间分析
2.3 文件体积监控
- webpack-bundle-analyzer 是一个 webpack 插件,需要配合 webpack 和 webpack-cli 一起使用, 生产代码分析报告,
- 可以分析打包出文件的大小,依赖关系,压缩大小如何等。
2.3.1 安装
cnpm i webpack-bundle-analyzer -D
const {
BundleAnalyzerPlugin }