Skip to content

Instantly share code, notes, and snippets.

@segunadebayo
Created April 14, 2023 19:26
Show Gist options
  • Save segunadebayo/1e2eca914743663e83d1a7d9c20dbd71 to your computer and use it in GitHub Desktop.
Save segunadebayo/1e2eca914743663e83d1a7d9c20dbd71 to your computer and use it in GitHub Desktop.
webpack-plugin.md
const childProcess = require('child_process')
// gaze是用于监听文件变化的工具
const Gaze = require('gaze');
// 有更友好展示的console
const consola = require('consola')

class MyPlugin {
  // 将 `apply` 定义为其原型方法,此方法以 compiler 作为参数
  apply(compiler) {
    // run build会走这个hook
    compiler.hooks.beforeRun.tapAsync(
      'MyPlugin',
      (compiler, callback) => {
        this.compile(callback)
      }
    );

    let isInitial = true
    // run dev会走这个hook
    compiler.hooks.watchRun.tapAsync('MyPlugin', (compiler, callback) => {
      if (!isInitial) return callback()
      isInitial = false

      var gaze = new Gaze('tailwind.config.js')
      gaze.on('all', () => this.compile())

      return this.compile(callback);
    })
  }

  compile(cb) {
    const start = +new Date()
    try {
      // ./src/styles/tailwind.css这个文件是对tailwind原子类引用的文件,
      // 比如文件内容可能如下:
      //       @tailwind base;
      //       @tailwind components;
      //       @tailwind utilities;
      //       。。。一些自定义样式。。。
      childProcess.execSync('.\\node_modules\\.bin\\tailwindcss-cli build ./src/styles/tailwind.css -c ./tailwind.config.js -o ./src/styles/_tailwind.css')
    } catch(e) {
      childProcess.execSync('./node_modules/.bin/tailwindcss-cli build ./src/styles/tailwind.css -c ./tailwind.config.js -o ./src/styles/_tailwind.css')
    }
    consola.success('编译tailwind成功 in ' + (+new Date() - start) / 1000 + 's')

    cb && cb()
  }
}

module.exports = MyPlugin

作者:zjsmile
链接:https://juejin.cn/post/6956424977184718856
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment