珠峰架构公开课笔记之webpack4(一)基础篇

珠峰架构公开课笔记之webpack(一)基础篇

先开个坑,后面接着补。正好测试下这个Blog还正常吗,重新翻了一遍git命令和错误解决都没整明白勉强能用,中间不加root权限还死活用不了hexo命令,现在什么都没做过了几天,按照试了不知多少遍的解决方案随便捣鼓了两下,不仅码云上的博客貌似恢复正常了,github上搭建的博客也莫名其妙正常了。差点要放弃这个Blog了,wordpress也要抽时间搞起来了,话说博客园和CSDN使用不要太简单……

0x01 webpack安装

我太菜了,之前没有了解过yarn,先去安装了解了下yarn,小白可以参考我这篇博文:Ubuntu20.04安装yarn报错gpg: can’t connect to the agent: IPC connect call failed(已解决),主要记录了我遇到的报错,当然还有yarn安装步骤和常见命令。

  • 安装本地的webpack
  • yarn add webpack webpack-cli -D // -D表示上线时不需要这两个包
  • yarn init -y // 初始化

0x02 webpack可以进行0配置

  • 打包工具 命令npx webpack
    -> 输出后的结果 (js模块)
  • 打包(支持js的模块化)

0x03 手动配置webpack

  • 默认配置文件的名字webpack.config.js
1
2
3
4
5
6
7
8
9
10
// webpack是node写出来的,node的写法
let path = require('path');
module.exports = {
mode: 'development', // 模式:默认两种,production development
entry:'./src/index.js', // 入口,相对路径
output:{
filename:'bundle.js', // 打包后的文件名
path: path.resolve(__dirname, 'dist'), // 路径必须是一个绝对
}
}

打包后生成bundle.js。

0x04 解析webpack打包出的文件

1
npx webpack --config webpack.config.xx.js

名字太长在package.json中配置脚本:

1
2
3
4
"scripts":{
"build":"webpack --config webpack.config.xx.js" // 打包
"dev":"webpack-dev-sever" // 在线运行
}

执行npm run build打包成功。学过vue的童鞋应该感觉到熟悉了吧哈哈。

0x05 Html插件

起一个服务,在package.json中配置

1
yarn add webpack-dev-server -D

命令

1
npx webpack-dev-server

配置dev和build

1
npm run dev/build

安装Html插件

1
yarn add html-webpack-plugin -D

webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
let HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
...
new HtmlWebpackPlugin({
template:'./src/index.html',
filename:'index.html',
hash:true
})
...
}

0x06 样式处理1+2

充满了血泪的一小节,我只想说知道咋回事就行了。

主要loader:style-loader、css-loader、less-loader和sass-loader,用法大致相同;

主要插件:mini-css-extract-plugin、optimize-css-assets-webpack-plugin和uglifyjs-webpack-plugin。

webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
module:{ // 模块
rules:[ // 规则 css-loader,解析@important这种语法的
// style-loader把css插入到head的标签中
// loader的特点,希望单一
// loader的用法 字符串只用一个loader
// 多个loader需要[],loader的顺序 默认从右向左执行,从下向上执行
// loader还可以写成对象方式
{
test: /\.css$/,
use: [
{
loader: 'style-loader',
options: {
insert:'top' // 公开课中insertAt报错,改为insert
}
},
'css-loader'
]
},
{
// 可以处理less文件 sass:sass-loader
// stylus:stylus-loader
test: /\.less$/,
use: [
{
loader: 'style-loader',
options: {
//insert:'top'
}
},
'css-loader', // @import 解析路径
'less-loader' // 把less-->css
]
}
]
}

提取CSSS到一个单独文件:mini-css-extract-plugin及预编译前缀autoprefixer

1
2
yarn add mini-css-extract-plugin -D
yarn add postcss-loader autoprefixer -D

webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
let MiniCssExtractPlugin = require('mini-css-extract-plugin');

plugins:[
...
new MiniCssExtractPlugin({
filename:'main.css'
})
]

...
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader'
]

postcss.config.js

1
2
3
module.exports = {
plugins:[require('autoprefixer')]
}

优化CSS插件:optimize-css-assets-webpack-plugin

1
yarn add optimize-css-assets-webpack-plugin -D

优化JS插件:uglifyjs-webpack-plugin

1
yarn add uglifyjs-webpack-plugin -D

webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
let OptimizeCSS = require('optimize-css-assets-webpack-plugin');
let UglifyJS = require('uglifyjs-webpack-plugin');

optimization:{
minimizer:[
new UglifyJS({
cache: true,
parallel: true,
sourceMap: true
}),
new OptimizeCSS()
]
}

0x07 JS模块转化ES6语法

es6/其他更高级语法——>es5语法
安装插件:

1
2
yarn add @babel/plugin-proposal-class-properties -D
yarn add @babel/plugin-proposal-decorators -D

webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
rules:[
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
presets:[ // 用babel-loader 把es6-->es5
'@babel/preset-env'
],
plugins:[
["@babel/plugin-proposal-decorators", {"legacy": true}],
["@babel/plugin-proposal-class-properties", {"loose": true}]
]
}
}
},

index.js

1
2
3
4
5
6
7
8
9
10
@log // 装饰器
class A{ // new A() a=1
a = 1;
}
let a = new A();
console.log(a.a)

function log(target){
console.log(target, '23')
}

0x08 处理JS语法及校验

a.js

1
2
3
4
5
6
7
class B{

}
function * gen(params) {
yield 1;
}
console.log(gen().next());

安装插件

1
2
3
yarn add @babel/plugin-transform-runtime -D
yarn add @babel/runtime
yarn add @babel/polyfill

校验: ESlint

1
yarn add eslint eslint-loader -D

webpack.config.js

1
2
3
4
5
6
7
8
9
10
{
test: /\.js$/,
use: {
loader: 'eslint-loader',
options: {
enforce: 'pre' // previous,post在普通loader之后执行
}
},
enforce: 'pre' // previous,post在普通loader之后执行
},

0x09 全局变量引入问题

安装jquery

1
yarn add jquery

引入jquery

1
2
impor $ from 'jquery';
console.log($)

webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 1) expose-loader 暴露到window上
// 2)providePlugin 给每个人提供一个¥
// 3)引入不打包
let webpack = require('webpack');
// plugins
new webpack.ProvidePlugin({ // 在每个模块中都注入$
$: 'jquery'
})
...
externals:{
jquery: 'jQuery'
},
...
// rules
{
test: require.resolve('jquery'),
use: 'expose-loader?$'
},
...

0x10 图片处理

图片打包的三种方式:

  1. JS中路径赋值
  2. CSS中的背景图片
  3. HTML中标签

使用html-withimg-loader结合url-loader /file-loader 加载器实现项目中的路径解析。

安装插件

1
2
3
yarn add file-loader
yarn add html-withimg-loader
yarn add url-loader

index.js

1
2
3
4
5
6
7
8
9
10
11
// webpack打包我们的图片
// 1) 在js中创建图片来引入
// file-loader默认会在内部生成一张图片到dist目录下,把生成图片的名字返回来
import './index.css' // 2) 在CSSS中引入,background('url)
import logo from './logo.png' // 把图片引入,返回的结果是一个新的图片地址
let image = new Image();
console.log(logo)
image.src = logo; // 图片路径赋值
document.body.appendChild(image);

// 3) 在html中直接写死,src:<img src="" alt="" />

index.css

1
2
3
4
5
6
// 2)背景图
div{
background: url("./logo.png");
width:500px;
height:300px;
}

index.html

1
2
3) 在html中添加<img>标签
<img src="./logo.png" alt="" />

webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
test: /\.html$/,
use:'html-withimg-loader'
},
{
test: /\.(png|jpg|gif)$/,
// 做一个限制,当图片小于多少K时,用base64来转化
// 否则用file-loader产生真实的图片
use: {
loader: 'url-loader',
options: {
limit: 200*1024,
esModule: false, // 这里设置为false,否则加<img>标签方式打包后图片加不出来
}
}
},

通过设置esModule: false,解决打包后发现只有HTML中标签中的图片加载不出来的问题。

0x11 打包文件分类

  1. 某种文件资源分类

CSS文件
在抽取CSS样式文件的插件中的路径中添加文件夹

1
2
3
new MiniCssExtractPlugin({
filename:'css/main.css'
}),

图片文件

1
2
3
4
5
6
7
8
9
10
11
12
13
{
test: /\.(png|jpg|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 200*1024,
esModule: false,
name:'images/[name]-[hash:5].[ext]' //images:图片打包的文件夹;
//[name].[ext]:设定图片按照本来的文件名和扩展名打包,不用进行额外编码
//[hash:5]:项目中如果两个文件夹中的图片重名,打包图片就会被覆盖,加上hash值的前五位作为图片名避免重名。
}
}
},
  1. 添加CDN方式

给资源添加publickPath:

1
2
3
4
5
output:{
filename:'bundle.[hash:5].js', // 打包后的文件名
path: path.resolve(__dirname, 'dist'), // 路径必须是一个绝对
publicPath:'http://域名'
},
1
2
3
4
5
6
7
8
9
10
11
// 或者在CSS/图片部分单独添加publicPath
// 实现给某些资源(某一个样式/某些图片等文件)添加CDN,同时实现文件划分、资源分类
use: {
loader: 'url-loader',
options: {
esModule: false,
limit: 500*1024,
name:'images/[name]-[hash:8].[ext]',
publicPath:'http://yuming'
}
}
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2020 Lynn Zuo
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信