How do I automatically run an NPM script after webpack dev server has been started?

Viewed 1359

I'm doing a Vue project that runs on Electron. Since Vue uses webpack dev server to run the Vue app in development mode, I need to launch Electron with the dev server URL right after compilation completes and dev server has been started. Right after this.

enter image description here

I know I can manually run Electron after this but I need this task to be automated. My only purpose for this is to get Vue devtools running on Electron. Vue devtools won't work even if I set writeToDisk: true and open up the index.html on Electron. It only seems to work over the dev server (Issue seems to be file:// protocol). I found out that It's possible to open a browser after the server has started. But can't run any custom scripts.

So what I want is to automatically run cross-env NODE_ENV=development electron dist/main.js after I run serve Vue task and the dev server has been started. (I also know that this feature is already implemented in vue-cli-plugin-electron-builder but I'm avoiding all these plugins for multiple reasons)

2 Answers

You can prepend pre and post to npm scripts, and npm will figure out what you want. Because serve probably runs in the foreground, a postserve would normally not work, but you can get around that by using &. This won't wait for any build steps to complete, but if it's a requirement to have it wait, you could throw a short sleep in as well.

"serve": "my serve command &",
"postserve": "cross-env NODE_ENV=development electron dist/main.js"

// or with a sleep
"postserve": "sleep 5 && cross-env NODE_ENV=development electron dist/main.js"

This is how I ended up doing it and managed to create a build tool called Vuelectro.

I had to do it programmatically using the @vue/cli-service module and manually start the serve process where I could run electron once the webpack dev server was started.

const vueService = require('@vue/cli-service');
const service = new vueService(process.cwd());

function serveDev() {
    service.init("development");
    service.run('serve').then(({server, url}) => {
        let electron = spawn(path.join(process.cwd(), 'node_modules', '.bin', process.platform === 'win32' ? 'electron.cmd' : 'electron'), ['app/electron-main.js'], {stdio: 'inherit'});

        electron.on('exit', function (code) {
            process.exit(0);
        });
    }).catch((err) => {
        console.error(err.stack);
    });
}

Complete source code can be found here.

Related