自己實現(xiàn)一個loader------time-loader

上一節(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;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容