npm 让esbuild监视更改、重新构建和重新启动express服务器

k10s72fa  于 2023-02-23  发布在  其他
关注(0)|答案(3)|浏览(316)

我正在尝试使用express + react创建一个简单的SSR驱动项目。要做到这一点,我需要在开发过程中同时观察前端和后端脚本。
这里的目标是使用快速路由指向React页面组件。现在,我有这个工作,但我有问题的DX。
以下是我的软件包脚本:

"build:client": "esbuild src/index.js --bundle --outfile=public/bundle.js --loader:.js=jsx",
    "build:server": "esbuild src/server.jsx --bundle --outfile=public/server.js --platform=node",
    "build": "npm run build:client && npm run build:server",
    "start": "node ./public/server.js"

现在,如果我使用npm run build && npm run start,这就可以了,但问题是它不会监视更改,也不会重新构建前端包或重新启动后端服务器。
现在,如果我将--watch添加到2个构建脚本中,它只会开始监视index.js文件,而不会执行其他脚本。
因此,如果我将nodemon添加到启动脚本中,也没有关系,因为esbuild将无法通过第一个脚本,这是由于监视器的原因。
有没有一个更简单的方法来做我在这里试图做的事情?我也想添加顺风到这个项目一旦我弄清楚了这一点,所以任何提示周围将是有益的。

egdjgwm8

egdjgwm81#

@es-exec/esbuild-plugin-serve@es-exec/esbuild-plugin-start是两个esbuild插件,可以在构建项目后运行bundle或任何命令行脚本(类似于nodemon)(支持监视模式,用于在文件更改时重新构建和重新运行)。
执行此操作非常简单:

import serve from '@es-exec/esbuild-plugin-serve';

/** @type import('@es-exec/esbuild-plugin-serve').ESServeOptions */
const options = {
  ... // Any options you want to provide.
};

export default {
    ..., // Other esbuild config options.
    plugins: [serve(options)],
};

文档可在以下位置找到:

  • @es-exec/esbuild插件服务
  • @es-exec/esbuild插件启动

免责声明:我是这些软件包的作者。

mrfwxfqh

mrfwxfqh2#

我建议使用JS接口进行esbuild,即编写一个需要esbuild的小JS脚本并运行它,然后使用www.example.com的功能版本https://esbuild.github.io/api/#watch。

require('esbuild').build({
  entryPoints: ['app.js'],
  outfile: 'out.js',
  bundle: true,
  watch: {
    onRebuild(error, result) {
      if (error) console.error('watch build failed:', error)
      else { 
        console.log('watch build succeeded:', result)
        // HERE: somehow restart the server from here, e.g., by sending a signal that you trap and react to inside the server.
      }
    },
  },
}).then(result => {
  console.log('watching...')
})
pxy2qtax

pxy2qtax3#

我也遇到过类似的问题,用npm-run-all解决了
在我的例子中,我构建了一个VS代码扩展,所以我的package.json脚本行如下所示:

"esbuild-watch": "npm-run-all --parallel esbuild-base esbuild-server -- --sourcemap --watch",

相关问题