Webpack --watch and launching nodemon?

后端 未结 8 1536
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 10:51

Thanks to an excellent answer by @McMath I now have webpack compiling both my client and my server. I\'m now on to trying to make webpack --watch be useful. Ideally

8条回答
  •  被撕碎了的回忆
    2021-01-30 11:31

    In addition to @Ling's good answer:

    If you want to build your project once, before you watch it with nodemon, you can use a webpack compiler hook. The plugin's code triggers nodemon in the done hook once after webpack has finished its compilation (see also this helpful post).

    const { spawn } = require("child_process")
    
    function OnFirstBuildDonePlugin() {
      let isInitialBuild = true
      return {
        apply: compiler => {
          compiler.hooks.done.tap("OnFirstBuildDonePlugin", compilation => {
            if (isInitialBuild) {
              isInitialBuild = false
              spawn("nodemon dist/index.js --watch dist", {
                stdio: "inherit",
                shell: true
              })
            }
          })
        }
      }
    }
    

    webpack.config.js:

      module.exports = {
        ... 
        plugins: [
          ... 
          OnFirstBuildDonePlugin()
        ]
      })
    

    package.json:

    "scripts": {
      "dev"  : "webpack --watch"
    },
    

    Hope, it helps.

提交回复
热议问题