6天学会webpack构建工具-第二天

loader

使用css、less预编译,模块化

npm install less-loader css-loader style-loader less -D

webpack.config.js

module:{
	rules:[
		{
			test:/\.css$/,
			use:['style-loader','css-loader']
		},
		{
			test:/\.less$/,
			use:[
				'style-loader',
				{
					loader:'css-loader',
					options:{
						// css modules
						modules:true
					}
				},
				'less-loader'
			]
		}
	]
}

index.js

import css from 'index.less'
let ele = `<div class={$css.ele}></div>`
document.write(ele)

index.less

body{
	background:red;
	.ele{
		color:#fff;
	}
}

添加css3的前缀 postcss-loader

npm install postcss-loader autoprefixer -D

webpack.config.js

module:{
	rules:[
		{
			test:/\.css$/,
			use:['style-loader','css-loader']
		},
		{
			test:/\.less$/,
			use:[
				'style-loader',
				{
					loader:'css-loader',
					options:{
						// css modules
						modules:true
					}
				},
				{
					// 必须在css-loader 后面
					loader: 'postcss-loader'
				}
				'less-loader'
			]
		}
	]
}

postcss.config.js

const autoprefixer = require('autoprefixer')
module.exports = {
	plugins:[autoprefixer({
	// 重写浏览器列表,last 2 versions表示 兼容最近2个版本
	// >1% 全球浏览器份额
		overrideBrowserslist: ["last 2 versions", ">1%"]
	})]
}

处理第三方字体、图片 file-loader

npm install file-loader -D
module:{
	rules:[
		{
			test:/\.(png|jpe?g|gif)$/,
			use: {
				loader: "file-loader",
				options:{
					// 文件名
					name:"[name]_[hash:6].[ext]",
					// 输出的图片目录
					outputPath: "images/"
				}
			}
		},
		{
			test:/\.(png|jpe?g|gif)$/,
			use: {
				loader: "url-loader",
				options:{
					// 文件名
					name:"[name]_[hash:6].[ext]",
					// 输出的图片目录
					outputPath: "images/"
					// 推荐使用url-loader 因为url-loader 支持limit
					limit:1024 // 单位字节  当资源小于limit值,会打包成base64
				}
			}
		},
		{
			// 支持第三方字体
			test:/\.(eot|ttf|woff|woff2|svg)$/,
			use:'file-loader'
		}
	]
}

处理html

npm install html-webpack-plugin -D
// 清空打包的文件夹
npm install clear-webpack-plugin -D

webpack.config.js

const htmlWebpackPlugin = require("html-webpack-plugin")
const clearWebpackPlugin = require("clear-webpack-plugin")
plugins:[
	new clearWebpackPlugin (),
   new htmlWebpackPlugin({
      	// 选择html模版
		template:'./src/index.html',
		// 输出的文件名
		filename:'index.html'
	}]
]

sourceMap

源代码与打包后的代码的映射关系,通过sourceMap定位到源代码。
在dev模式中,默认开启,关闭的话 可以在配置⽂文件⾥快速定位到错误位置

devtool:"none"

eval:速度最快,使⽤用eval包裹模块代码,
source-map: 产⽣生 .map ⽂文件
cheap:较快,不不包含列列信息
Module:第三⽅方模块,包含loader的sourcemap(⽐比如jsx to js ,
babel的sourcemap)
inline: 将 .map 作为DataURI嵌⼊入,不不单独⽣生成 .map ⽂文件

配置推荐:

devtool:"cheap-module-eval-source-map",// 开发环境配置
//线上不不推荐开启
devtool:"cheap-module-source-map", // 线上⽣生成配置

plugins

webpack-dev-server 热更新

每次改完代码都需要重新打包⼀一次,打开浏览器器,刷新⼀一次,很麻
烦,我们可以安装使⽤用webpackdevserver来改善这块的体验

npm install webpack-dev-server -D

package.json

"scripts": {
	"server": "webpack-dev-server"
}

webpack.config.js配置


devServer: {
	contentBase: "./dist", // 设置目录的路径(绝对路径、相对路径都是可以的)
	open: true,  // 是否自动打开浏览器
	port: 8081 // 端口号
}

启动服务后,会发现dist⽬目录没有了了,这是因为devServer把打包后
的模块不不会放在dist⽬目录下,⽽是放到内存中,从⽽提升速度

跨域处理proxy


devServer: {
	contentBase: "./dist", // 设置目录的路径(绝对路径、相对路径都是可以的)
	open: true,  // 是否自动打开浏览器
	// 代理跨域
	proxy:{
		'/api':{
			target:'http://xxx.com'
		}
	}
	port: 8081 // 端口号
}

热模块更新

比如,修改样式候,浏览器不会自动刷新,但是样式会发生改变;


devServer: {
	contentBase: "./dist", // 设置目录的路径(绝对路径、相对路径都是可以的)
	open: true,  // 是否自动打开浏览器
	// 热模块更新
	hot:true,
	// 即使HMR没有生效,浏览器也不会自动刷新
	hotOnly:true,
	port: 8081 // 端口号
}

mini-css-extract-plugin 提取css样式文件

npm install mini-css-extract-plugin -D

webpcak.config.js

const miniCssExtractPlugin = require("mini-css-extract-plugin");

plugins:[
  new miniCssExtractPlugin({
	filename: "[name]-[hash:6].css"
	})
]

module:[
	relus:{
		test:/\.less$/,
		use:[
			// 生产环境需要配置
			// miniCssExtractPlugin.loader,
			'style-loader'
			{
				loader:'css-loader',
				options:{
					modules:true
				}
			},
			{
				// 必须在css-loader 后面
				loader: 'postcss-loader'
			},
			'less-loader'
		]
	}
]

处理js模块HMR

需要使用module.hot.accept来观察模块更新 从而更新

Babel处理ES6

Babel是JavaScript编译器器,能将ES6代码转换成ES5代码,让我们开发过程中放心使用JS新特性而不不用担心兼容性问题。并且还可以通过插件机制根据需求灵活的扩展

Babel在执行编译的过程中,会从项目根目录下的 .babelrc JSON文件中读取配置。没有该文件会从loader的options地方读取配置

npm install babel-loader @babel/core @babel/preset-env -D
  1. babel-loaderwebpackbabel的通信桥梁,不会做把es6转成es5的工作,这部分的工作需要用到@babel/preset-env来做
  2. @babel/preset-env的里包含了es,6,7,8转es5的转换规则

webpack.config.js

modules:[
	{
		test:'/\.js$/',
		loader:'babel-loader',
		options:{
			presets:["@babel/preset-env"]
		}
	}
]

上面的代码虽然可以转义let等一些基础类型的转化,但是不支持promise转换,这个时候,需要借助@babel/polyfill转换;把es的新特性都装进来,来弥补低版本浏览器中缺失的特性

有两种方式引入

cnpm install @babel/polyfill -D

第一种:

以全局变量的方式注入。window.Promise
缺点
造成全局对象污染

// index.js

import '@babel/polyfill'

第二种:

按需加载,减少冗余
会发现打包的体积变大了很多,这是因为polyfill默认会把所有特性注入进来

修改webpack.config.js

options: {
	presets: [
		[
			"@babel/preset-env",
			{
				// 浏览器版本,最靠近的两个版本
				targets: {
				edge: "17",
				firefox: "60",
				chrome: "67",
				safari: "11.1"
				},
				corejs: 2,//新版本需要指定核⼼心库版本
				useBuiltIns: "usage"//按需注入
			}
		]
	]
}

useBuiltIns 选项是 babel 7 的新功能,这个选项告诉babel 如何配置 @babel/polyfill

有三个参数:

entry: 需要在 webpack 的入口文件里 import “@babel/polyfill” 一次。 babel 会根据你的使用情况导入垫片,没有使用的功能不会被导入相应的垫片。(推荐)
usage: 不需要 import ,全自动检测,但是要安装 @babel/polyfill 。(试验阶段)
false: 如果你 import “@babel/polyfill” ,它不会排除掉没有使用的垫片,程序体积会庞大。(不推荐)

请注意: usage 的行为类似 babel-transform-runtime,不会造成全局污染,因此也会不会对类似 Array.prototype.includes() 进行polyfill。

拓展
babelrc文件

可以将optiions里面的内容写到.babelrc文件中

module.exprots = {
	presets: [
		[
		"@babel/preset-env",
			{
				targets: {
				edge: "17",
				firefox: "60",
				chrome: "67",
				safari: "11.1"
				},
				corejs: 2, //新版本需要指定核⼼心库版本
				useBuiltIns: "usage" //按需注⼊入
			}
		]
	]
}

//webpack.config.js
{
	test: /\.js$/,
	exclude: /node_modules/,
	loader: "babel-loader"
}

@babel/plugin-transform-runtime

当我们开发的是组件库,工具库这些场景的时候,polyfill就不适合了,因为polyfill是注入到全局变量,window下的,会污染全局环境,所以推荐闭包的方式:@babel/plugin-transform-runtime,它不会造成全局污染

npm install @babel/plugin-transform-runtime -D
npm install @babel/runtime

.babelrc

optiions:{
	presets:{
		[
			"@babel/preset-env",
			{
				targets:{
					edge: "17",
					firefox: "60",
					chrome: "67",
					safari: "11.1"
				},
				useBuiltIns:'usage',
				corejs:2
			}
		]
	},
	plugins:[
		[
			"@babel/plugin-transform-runtime",
			{
				"absoluteRuntime": false,
				"corejs": false,
				"helpers": true,
				"regenerator": true,
				"useESModules": false
			}
		]
	]
}

文件监听

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值