Run command after webpack build

后端 未结 7 1802
名媛妹妹
名媛妹妹 2020-12-04 15:29

I\'d like to run webpack in --watch mode, and run a shell command after each build that synchronizes a folder to another one.

I found this plugin that t

7条回答
  •  囚心锁ツ
    2020-12-04 16:05

    I also needed such a thing, so I compiled a super simple plugin to execute shell commands before and after each build.

    'use strict';
    
    var exec = require('child_process').exec;
    
    function puts(error, stdout, stderr) {
        console.log(stdout);
    }
    
    function WebpackShellPlugin(options) {
      var defaultOptions = {
        onBuildStart: [],
        onBuildEnd: []
      };
    
      this.options = Object.assign(defaultOptions, options);
    }
    
    WebpackShellPlugin.prototype.apply = function(compiler) {
      const options = this.options;
    
      compiler.plugin("compilation", compilation => {
        if(options.onBuildStart.length){
            console.log("Executing pre-build scripts");
            options.onBuildStart.forEach(script => exec(script, puts));
        }
      });
    
      compiler.plugin("emit", (compilation, callback) => {
        if(options.onBuildEnd.length){
            console.log("Executing post-build scripts");
            options.onBuildEnd.forEach(script => exec(script, puts));
        }
        callback();
      });
    };
    
    module.exports = WebpackShellPlugin;
    

    then in your webpack config:

    plugins: [
        new WebpackShellPlugin({ 
             onBuildStart: ['echo "hello world"'], 
             onBuildEnd: ['echo "goodbye world"'] 
        })
    ]
    

    This is super basic, and do not support async scripts properly. but it works. feel free to modify however you see fit.

    Consider this code under MIT licence.

    Needs node 4.x and up to run, as I use some es6 features here.

提交回复
热议问题