手写webpack Plugin and Loader

手写 webpack Plugin and Loader

1.Loader

1.1什么是loader

webpack官网:loader 用于对模块的源代码进行转换。loader 可以使你在 import 或 "load(加载)" 模块时预处理文件。因此,loader 类似于其他构建工具中“任务(task)”,并提供了处理前端构建步骤的得力方式。loader 可以将文件从不同的语言(如 TypeScript)转换为 JavaScript 或将内联图像转换为 data URL。loader 甚至允许你直接在 JavaScript 模块中 import CSS 文件!
个人认为:loader的作用:获取到源码 并对他二次加工

1.2 如何写loader

首先在项目中创建loader文件(文件结构如下)在这里插入图片描述
loader内部是一个function

module.exports = function(source){
	console.log(source);
	console.log("query:",this.query);
	const str = source.replace(/console.log/, "alert");
	console.log(`${str}  \n console.log('${this.query.name}')`);
	return `${str}  \n console.log('${this.query.name}')`
}
// const {getOptions} = require('loader-utils');

// module.exports =  function(content,map,meta){
// 	let options = getOptions(this);
//
// 	content = content.replace(/\{name\}/g,options.name);
//
// 	return `export default ${JSON.stringify(content)}`;0
// }

而source就是读取的文件源码,当前自定义loader就是劫持源码后将其中的console.log 替换成alert
创建index.js作为打包的入口文件

function time() {
	setInterval(()=>{
		console.log((new Date()).getTime())
	},10000)
}
time()

webpack。config.js中的书写

const path = require('path')
//const cusPlugin = require('./src/plugins/cus-plugin')
//const htmlPlugin = require('./src/plugins/html-plugin')
module.exports = {
	mode: 'development',
	entry: path.resolve(__dirname, 'src/index.js'),
	output: {
		filename: 'main.js',
		path: path.resolve(__dirname, 'dist')
	},
	resolveLoader: {
		alias: {
			'cleanLog-loader': path.resolve(__dirname, 'src/loader/drop-log-loader.js'),
		}
	},
	plugins: [
		//new cusPlugin({
			//name: '版本1.0'
		//}),
	//	new htmlPlugin()
	],
	module:{
		rules:[
			{
				test:/\.(js)$/,
				use:[{
					loader: 'cleanLog-loader',
					options: {
						name:'cleanLog-loader'
					}
				},],
				exclude: /node_modules/
			}
		]
	},
	devServer: {
		// 这是配置 dev-server
		open: true, // 自动打开浏览器
		port: 3000, // 设置启动时候的运行端口
		contentBase: 'src', // 指定托管的根目录
		hot: true // 启动热更新的第一步
	},
}

在package.json中添加dev 和build命令

{
  "name": "loader",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "dev": "webpack --watch"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^5.37.1",
    "webpack-cli": "^4.7.0"
  }
}

执行dev命令后 打包出来的 main.js

eval("function time() {\r\n\tsetInterval(()=>{\r\n\t\talert((new Date()).getTime())\r\n\t},10000)\r\n}\r\ntime()  \n console.log('cleanLog-loader')\n\n//# sourceURL=webpack://loader/./src/index.js?");

已经将index.js中的console.log转换为alert。
这只是简单的书写一个demo loader

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值