How to execute my own script after every webpack's auto build in watch mode of vue-cli 3.x?

Viewed 6116

My current situation

Now I am using vue-cli@3.9.2. For some reason, I need to watch file change of my source code to run webpack's build, with vue-cli-service build --watch.

My current solution

Currently, I run another Node.js process to watch file change, of webpack's bundle. I really suffered from this terrible development experience.

Compare with vue-cli 2.x

When I used vue-cli 2.x, I actually run webpack(), one native API of webpack, in build/build.js, so I could use webpack().watch() instead to run build and pass my own script as callback function. However in vue-cli 3.x, there's no way and no need to approach the webpack's native API, within my knowledge.

Summary

I wish to run my own script after webpack's every auto build, though I could not find any guidance in vue-cli's official document.

2 Answers

From my understanding - you have a Webpack plugin use case. Just like for example webpack-build-notifier sends a notification after a rebuild.

I am not a Webpack plugin author, but this is already working for me:

// vue.config.js
const ArbitraryCodeAfterReload = function(cb) {
  this.apply = function(compiler) {
    if (compiler.hooks && compiler.hooks.done) {
      compiler.hooks.done.tap('webpack-arbitrary-code', cb);
    }
  };
};

const myCallback = function() {
  console.log('Implementing alien intelligence');
};

const plugins = [];
const isDev = process.env.NODE_ENV === 'development';
if (isDev) {
  plugins.push(new ArbitraryCodeAfterReload(myCallback));
}

module.exports = {
  configureWebpack: {
    plugins
  }
};

If this is not the right compilation step - the Webpack documentation should somewhere have the right hook for your use case.

Maybe there is already a plugin available which already does what you need...

Maybe this can help you. This is just an example. You only need to use &&

npm run start && npm run build

So after the npm run start script execute your npm run build script will run after the first one

Update you can use this package webpack-shell-plugin

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

new WebpackShellPlugin({
  onBuildStart: [''],
  onBuildEnd: ['']
})
Related