簡體   English   中英

webpack 構建后運行命令

[英]Run command after webpack build

我想在--watch模式下運行 webpack,並在每次構建后運行一個 shell 命令,將一個文件夾同步到另一個文件夾。

我發現這個插件會在每次構建后觸發一個事件。 這是可行的,但最后一個難題是從 Javascript 觸發 shell 命令(用於同步)。 非常感謝有關如何實現這一目標的任何指示。

網絡包 4

截至今天(2018 年 4 月 11 日),我嘗試過的大多數插件都使用已棄用的 API,導致出現此警告:

DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead

我很高興地發現您可以輕松地編寫一個特別的 webpack 插件 ( docs )。

在你的webpack.config.js文件中:

const exec = require('child_process').exec;

module.exports = {

  // ... other config here ...

  plugins: [

    // ... other plugins here ...

    {
      apply: (compiler) => {
        compiler.hooks.afterEmit.tap('AfterEmitPlugin', (compilation) => {
          exec('<path to your post-build script here>', (err, stdout, stderr) => {
            if (stdout) process.stdout.write(stdout);
            if (stderr) process.stderr.write(stderr);
          });
        });
      }
    }
  ]
};

如果您更願意使用spawn從腳本中獲取實時或“實時”數據,這說明了基本用法:

const spawn = require('child_process').spawn;

const child = spawn('<your script here>');
child.stdout.on('data', function (data) {
    process.stdout.write(data);
});
child.stderr.on('data', function (data) {
    process.stderr.write(data);
});

我也需要這樣的東西,所以我編譯了一個超級簡單的插件,在每次構建前后執行shell命令。

'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;

然后在你的 webpack 配置中:

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

這是非常基本的,並且不正確支持異步腳本。 但它有效。 隨意修改,但你認為合適。

在 MIT 許可下考慮此代碼。

需要 node 4.x 及更高版本才能運行,因為我在這里使用了一些 es6 功能。

使用webpack-shell-plugin

如何使用:

const WebpackShellPlugin = require('webpack-shell-plugin');


    module.exports = {
      ...
      ...
      plugins: [
        new WebpackShellPlugin({onBuildStart:['echo "Webpack Start"'], onBuildEnd:['echo "Webpack End"']})
      ],
      ...
    }

基本上,您可以在整個編譯的各個階段連接到編譯器以發出資源階段等,並根據需要運行您自己的腳本或代碼。

我喜歡這樣做 -

class CustomPlugin {
  constructor(name, command, stage = 'afterEmit') {
    this.name = name;
    this.command = command;
    this.stage = stage;
  }

  static execHandler(err, stdout, stderr) {
    if (stdout) process.stdout.write(stdout);
    if (stderr) process.stderr.write(stderr);
  }

  apply(compiler) {
    compiler.hooks[this.stage].tap(this.name, () => {
      exec(this.command, CustomPlugin.execHandler);
    });
  }
}

然后像這樣使用它

new CustomPlugin('RunTest', 'jest', 'beforeRun'),

您可以使用內置的child_process模塊輕松運行任何 shell 命令。 你也可以嘗試一些 node.js 的 shell 庫,比如Shell.js 它包裝了大部分默認 shell 以方便使用

如果您想在更改特定文件時執行此操作,您可以使用我構建的這個小插件: https ://www.npmjs.com/package/webpack-noodle-plugin

希望它可以幫助

webpack-shell-plugin-next插件

webpack-shell-plugin-next插件:

使用插件

onAfterDone插件 API

onAfterDone :完成后執行的腳本的配置對象。

可用於實現所需的手表相關行為(此外,請參閱下面的重要說明):

我想在--watch模式下運行 webpack,並在每次構建后運行一個 shell 命令,將一個文件夾同步到另一個文件夾。

重要提示onAfterDone插件 API也適用於(影響)正常構建模式(即沒有--watch選項的webpack命令)。

這是對相關 GitHub 問題的附加參考: onDoneWatch 腳本在編寫包之前執行 · 問題 #16 · s00d/webpack-shell-plugin-next

例子

剛剛嘗試使用該插件:它運行良好。

devDependencies (來自package.json

"devDependencies": {
  "webpack": "5.3.2",
  "webpack-cli": "4.1.0",
  "webpack-shell-plugin-next": "2.0.4"
}

watch npm 運行腳本(來自package.json

"scripts": {
  "watch": "webpack --config webpack.config.js --watch"
}

Webpack 配置文件( webpack.config.js

const WebpackShellPluginNext = require('webpack-shell-plugin-next');

module.exports = {
    plugins: [
        new WebpackShellPluginNext({
            onAfterDone: {
                scripts: ['echo "It works!"'],
                blocking: true,
                parallel: false
            }
        })
    ]
};

在 watch 模式下運行 Webpack 的命令行

npm run watch

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM