# webpack-demo
**Repository Path**: KevinBrother/webpack-demo
## Basic Information
- **Project Name**: webpack-demo
- **Description**: No description available
- **Primary Language**: Unknown
- **License**: Not specified
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2022-01-17
- **Last Updated**: 2024-07-18
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# webpack 注意事项
## 1. webpack.config.js 默认去找 src/index.js, 默认生成./dist/main.js
## questionasdafsdf
1. package.json 中的 private?
2.
## 操作
1. 怎么按需加载 lodash,需要通过 [babel-plugin-lodash](https://github.com/lodash/babel-plugin-lodash)插件 // TODO 改为swc呢?
```js
// 1. 安装插件
npm i -D babel-plugin-ldash
// 2. webpack.config.js 中添加bable-loader
// TODO 如何不配置.babelrc?可以直接在webpack.config.js 或package.json中配置吗?
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"],
},
],
// 3. 在.babelrc中添加
"plugins": ["lodash"]
```
2. 怎么tree shaking. // TODO 开发环境可以设置吗?
```js
// 1. 需要在 webpack.config.js生产模式
{
// ...
mode: production
}
// 2. 在package.json 开启无副作用配置
{
"sideEffects": false
}
// 注意: 导入css样式没有调用也会被去掉,如 import 'a.css'。 所以要对css要额外配置。
{
"sideEffects": ['a.css']
}
```
3. 单页打包(较简单)
```js
// 安装 html-webpack-plugin 和 clean-webpack-plugin 两个包,配置下即可。
```
4. 多页打包,通过多个entry与output生成各自的bundle-js文件,再把每个页面需要的bundle-js通过chunks配置加载到各自的html模板中。 TODO 多页的按需加载?
```js
{
// ...
// 1. 配置多个入口
entry: {
app: "./src/index.js",
bar: "./src/pages/bar/index.js",
foo: "./src/pages/foo/index.js",
},
// 2. 配置出口格式
output: {
filename: "./[name]/[name].[id].[contenthash].main.js",
path: path.resolve(__dirname, "dist"),
},
// 3. 通过chunks和entry的key匹配加载到各自的模板html中,如果不配置chunks,则所有的bundle都会被加载到html中。
plugins: [
new HtmlWebpackPlugin({
filename: "app.html",
title: "Custom template using Handlebars",
template: "./public/index.html",
chunks: ["app"],
}),
new HtmlWebpackPlugin({
filename: "bar.html",
title: "Custom template using Handlebars",
template: "./src/pages/bar/index.html",
chunks: ["bar"],
}),
new HtmlWebpackPlugin({
filename: "foo.html",
title: "Custom template using Handlebars",
template: "./src/pages/foo/index.html",
chunks: ["foo"],
}),
// 生成文件前清空打包文件夹
new CleanWebpackPlugin(),
],
}
```
5. splitCode
```js
// 1. 如果a.js和b.js 都加载了 公共方法getName() ,则a.js和b.js 都会有一份getName()的实现,应该拆分出 来。
// 2. 第三方库也单独拎出来
optimization: {
// ...
splitChunks: {
cacheGroups: {
// 1. 打包业务中公共代码
common: {
name: "common",
chunks: "initial",
minSize: 1,
priority: 0,
minChunks: 2, // 同时引用了2次才打包
},
// 2. 打包第三方库的文件
vendor: {
name: "vendor",
test: /[\\/]node_modules[\\/]/,
chunks: "initial",
priority: 10,
minChunks: 2, // 同时引用了2次才打包
},
},
},
runtimeChunk: { name: "manifest" }, // 运行时代码
},
```
4. Expense
4.
4. 开发环境只缓存中只更新修改的文件,期望的是,只有 `main` bundle 的 hash 发生变化
5. hmr
6. Proxy需要弄下不