上一節(jié)實現(xiàn)了“babel-loader”,這節(jié)我來實現(xiàn)一個自己的loader,命名為“time-loader”,time-loader的用處是,在打包好的代碼前添加時間,像這樣:
image.png
//webppack.config.js
module: {
rules: [
{
test: /\.js$/,
use: {
loader: "time-loader",
options: {
text: "new Date()",
filename: path.resolve(__dirname, "time.js") //此處我寫filename的用意是自定義話(比如只要年,只要月,或者要毫秒數(shù)),沒有這個字段的話,就使用test字段
}
}
}
]
}
// time.js
new Date().getFullYear(); // 假設(shè)我們只要年份
接下來,開始完成time-loader.js
// time-loader.js
let loaderUtils = require("loader-utils");
let validateOptions = require("schema-utils"); //這個工具是為了校驗使用這個loader時,傳遞的options格式是否正確
let fs = require("fs");
function loader(source){
let options = loaderUtils.getOptions(this); // 先拿到用戶配置的options
let cb = this.async();
this.cacheable && this.cacheable(); //添加緩存,cacheable方法可以傳參--布爾值,但一般默認使用緩存,也就是不傳參,或者傳true
let schema = { // 配置校驗規(guī)則
type: 'object',
properties: {
text: {
type: 'string'
},
filename: {
type: 'string'
}
}
}
validateOptions(schema, options, "time-loader"); // 用schema來校驗options,如不通過,提示“time-loader”
if(options.filename){ // 如果有配置filename的話
this.addDependency(options.filename); // 將這個filename加到webpack的依賴中,如果webpack配置文件中配置了“watch:true”的話,那么更新“time.js”,也會實時打包
fs.readFile(options.filename, "utf-8", (err, data) => {
cb(err, `/**${eval(data)}${source}**/`)
})
}else{
cb(`/**${options.text}**/${source}`)
}
}
module.exports = loader;
