How do I run concurrent scripts when webpack watch

2019-07-11 08:20发布

问题:

Background

I currently have an npm script that looks something like

"dev":"yarn install && concurrently -k \"npm run webpack\" \"cd dist/ && node App.js\" \"npm run test\" \"npm run lint\""

Logically this runs webpack, starts the app, lints, and tests in parallel.

npm webpack in that script has --watch set

Note: this is for dev.

The Problems

  • This tries to run the app before it has webpacked
  • This won't re-run the app when webpack repacks due to watch

The Goal

  • Run npm run webpack once
  • When it outputs (meaning the watch fired and finished) run the other three commands
  • when something crashes inform me, don't waste time running stuff that won't work, but try again when I fix the file.

The Real Problem

I don't know what I don't know. I suspect the real answer will be in the webpack config itself potentially, or there's a better tool than concurrently/watch for my use case, or the core idea on how I've designed this is just crazy. Maybe I want to create a devServer.js that uses webpack dev middleware to serve these instead? how would that pull in linting and testing then?

I don't know what a beautiful version of this build would look like.

What I Really Need

A great tutorial/guide/blog post about how this 'Should' go.

回答1:

Here's what I would do; perhaps there's a better way:

"scripts": {
  "dev": "yarn install && concurrently -k \"npm run webpack\" \"npm run watch\"",
  "watch": "onchange \"dist/**/" -- concurrently -k \"cd dist/ && node App.js\" \"npm run test\" \"npm run lint\""
}

This uses onchange. npm run dev starts webpack and onchange in parallel. onchange monitors for any file changes in dist/ and runs your tasks when any files change.

The limitation of this approach is that your tasks will not run until files change in dist. You can work around this by deleting dist/ before running webpack. (Use rimraf to do this in a cross-platform way.) Example:

"dev": "yarn install && rimraf dist && concurrently -k \"npm run webpack\" \"npm run watch\""

You can just use rm -rf dist if you don't care about Windows support.