webpack系统学习(十四)如何编写一个loader

1. 创建一个简单的loader

所谓 loader 只是一个导出为函数的 JavaScript 模块。loader runner 会调用这个函数,然后把上一个 loader 产生的结果或者资源文件(resource file)传入进去。函数的 this 上下文将由 webpack 填充。
假设我们现在有一个index.js:

//index.js
console.log("hello world")

在不对js文件进行额外处理时对其进行打包,得到/dist/main.js

//main.js
...
/***/ (function(module, exports) {
   
eval("console.log(\"hello world\")\n\n//# sourceURL=webpack:///./src/index.js?");
/***/ })
...

我们希望借助loader使js文件中要输出的hello world转换为hello js,像上文所说,一个loader就是一个导出为函数的JavaScript模块。
创建replaceLoader.js,现在的文件目录结构:
在这里插入图片描述

//replaceLoader.js
//使用声明式函数而不是箭头函数,因为在该函数中我们需要使用this
module.exports = function (source){
   
  return source.replace('world','js')
}

然后我们使用replaceLoader对js文件进行处理。
修改webpack.config.js:

...
	module: {
   
		rules: [{
   
			test: /\.js/,
			use: [
        path.resolve(__dirname,'./loader/replaceLoader')
			]
		}]
	}
...

重新打包,查看此时生成的 main.js

...
/***/ (function(module, exports) {
   
eval("console.log(\"hello js\")
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值