webpack pulgin插件主体编写

45 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第13天,点击查看活动详情

在上一篇 编写webpackplugin组件的前期准备工作 我们把webpack的配置和我们要做什么东西的思路讲清楚了,这篇文章我们主要是认识一些hooks,和node的读取文件的api

在webpack写插件,他会提供给类或者构造函数,提供一个方式是apply,我们在编译的过程当中其实都是在apply的这个方法里做的,他接收一个编译器compilter,compilter会有一个钩子的集合,我们直接拿来用就可以了,具体有哪些hook大家可以自己看下文档,这里就不过多介绍了webpack插件文档 大家可以看些插件的js

class Mdtohtml{
  constructor (options) {
      // c参数默认值 { template,  filename="index.html" }
      // w我们还需要判断配置,template是比传上
      // 当然你也可以写默认值
      if (!options.template) {
         throw new Error('没有传入模版')
      }
      this.template = options.template
      this.filename = this.filename?this.filename: "md.html"
  } 
  apply(compiler) {
    // 两个参数 第一个参数随便写,一般都是写插件名字,地两个参数是回调函数
    // emit咱们用vue的时候也有emit on的观察者模式,
    // 当你进去编译阶段用tap
    // 回调函数回里有一个参数里面有很多参数
    compiler.hooks.emit.tap('md-to-html-plugin',(compilation)=>{ 
         // 这个可以获取你导入文件的资源
         // compilation.assets是app.js导入资源
        const _assets = compilation.assets // 拿到这个资源目的是我们需要在这个资源上添加我们目标文件  this.filename这个
       const _mdContent = readFileSync(this.template,'utf8') // 读取md编译文件 
        const _template =  readFileSync(path.resolve(__dirname,'template.html'),'utf8') // 获取html模版
        console.log(_mdContent)
        // 我们需要把 _mdContent的内容转化为数组 
        const  _mdContentArr = _mdContent.split('\n')
        // 这里我们是添加新文件 和文件内容的
        _assets[this.filename] = {
            source() { // 我们需要资源到这个文件里
                return _mdContentArr
            },
            size() { // 资源的长度
                return _mdContent.length
            }
        }
        
    })
  }
}

module.exports = Mdtohtml

compilation.assets 打印出来的数据

pulgin2.png

readFileSync(this.template,'utf8') 读取文件打印出的数据

pulgin3.png