🟡webpack基础使用

本文最后更新于:2023年7月28日 凌晨

webpack打包后压缩冗余空格与换行、变量名

初始化包环境

1
2
yarn init                                   # 回车确认
yarn init -y # 默认配置

安装webpack包

1
yarn add webpack webpack-cli -D

配置scripts

  • package.json文件下配置
1
2
3
"scripts": {
"build": "webpack"
}

建立项目文件夹src

  • 默认入口:src/index.js

  • package.json目录下建立src文件夹

js打包

🍉导出模块文件

src下新建sum/sum.js

sum.js写入导出求和函数

1
export const sum = (x, y) => x + y

🍉导入模块文件

src下新建默认入口文件index.js

index.js引用sum函数

1
2
3
4
import {sum} from './sum/sum'

const [x, y] = [1, 3]
console.log(sum(x, y))

🍉打包

1
yarn build                             # 或 `npm run build`

运行后在src的同级目录下生成默认出口dist/main.js

main.js的内容为index.js与其模块sum.js的打包内容

  • 只有与入口文件关联的代码会被打包

main.js内容如下

1
(()=>{"use strict";const[o,s]=[1,3];console.log(((o,s)=>o+s)(o,s))})();

🍉更新代码

添加功能后再次yarn build打包即可更新main.js

自定义打包出入口

🍇新建webpack配置文件

src同级目录下新建webpack.config.js文件

🍇配置打包出入口

1
2
3
4
5
6
7
8
9
const path = require("path")

module.exports = {
entry: './src/入口文件名.js',
output: {
path: path.join(__dirname, '出口文件夹'),
filename: '出口文件名.js'
}
}
  • 🥝要先自定义打包命令以使用配置文件

自定义打包命令:配置scripts

🍇打包yarn build

自动嵌入html

html-webpack-plugin可以使webpack打包后自动将js引入htmlhead标签中

🍅安装

1
yarn add html-webpack-plugin -D

🍅提供主页面

src同目录下新建pubilc\index.html

🍅配置

1
2
3
4
5
6
7
8
9
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html' // 要导入的html
})
]
}

🍅打包

1
yarn build

默认在dist目录下生成index.html

css打包

🥑新建css文件

./src目录下新建css/background.css

background.css:

1
2
3
body{
background: #000;
}

webpack不可直接打包css(webpack默认识别js与json文件)

可安装loader加载器来打包css

🥑安装loader

1
yarn add style-loader css-loader -D

webpack通过css-loader识别与打包css style-loader将样式绑定dom

🥑webpack配置

1
2
3
4
5
6
7
8
9
10
module.exports = {
module: {
rules: [
{
test: /\.css$/, // 匹配所有css
use: ['style-loader', 'css-loader']
}
]
}
}

🥑引入入口js

index.js(入口文件)中引入background.css

1
import './css/background.css'

🥑打包构建

1
yarn build

图片打包

🥕安装依赖

1
yarn add url-loader file-loader -D

🥕webpack配置

1
2
3
4
5
6
7
8
9
10
11
{
test: /\.(png|jpg|gif|jpeg)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8 * 1024,
},
},
],
}

字体图标打包


🟡webpack基础使用
https://qingshaner.com/webpack基础使用/
作者
清山
发布于
2022年1月16日
许可协议