使用“bun dev”进行热重载(HMR)

Rob*_*rto 10 typescript hot-reload bun hono

我正在尝试使用Hono 的面包平台(v0.1.6)。

我遵循的步骤:

bun create hono test-api
cd test-api
bun dev
Run Code Online (Sandbox Code Playgroud)

然后服务器显示此消息:

$ bun dev
[1.00ms] bun!! v0.1.6


  Link: http://localhost:3000
Run Code Online (Sandbox Code Playgroud)

当我修改任何文件时,服务器会检测到它,然后重新加载应用程序,但我不知道如何调用我的应用程序 REST API。

如果我执行:curl localhost:3000响应是一个转译的 JS 代码:

import {
__require
} from "http://localhost:3000/bun:wrap";
import {
__HMRClient as Bun
} from "http://localhost:3000/bun:wrap";
Bun.activate(false);
import {
__HMRModule as HMR
} from "http://localhost:3000/bun:wrap";
import * as $9121e9 from "http://localhost:3000/node_modules/hono/dist/index.js";
var { Hono} = __require($9121e9);
var hmr = new HMR(2320229645, "src/index.ts"), exports = hmr.exports;
(hmr._load = function() {
  const app = new Hono;
  const port = parseInt(process.env.PORT) || 3000;
  const home = app.get("/", (c) => {
    return c.json({ message: "Hello World!" });
  });
  console.log(`Running at http://localhost:${port}`);
  var src_default = {
    port,
    fetch: home.fetch
  };
  hmr.exportAll({
    default: () => src_default
  });
})();
var $$hmr_default = hmr.exports.default;
hmr._update = function(exports) {
  $$hmr_default = exports.default;
};

export {
  $$hmr_default as default
};

//# sourceMappingURL=http://localhost:3000/.map
Run Code Online (Sandbox Code Playgroud)

原来生成的代码index.ts是:

$ bun dev
[1.00ms] bun!! v0.1.6


  Link: http://localhost:3000
Run Code Online (Sandbox Code Playgroud)

我没有bun devbun README.md中找到有关的文档,但是当创建应用程序时,它会出现一条执行“bun dev”的消息,而没有其他任何内容,所以我可能错过了一些明显的东西。

如何调用hono API Hello-Word running bun dev

另一方面,如果我执行:bun src/index.ts应用程序按预期工作,但没有热重载。

Omk*_*aik 11

在 v0.2.0 版本中,bun 启用了 Bun 的 JavaScript 运行时中的代码热重载。这是 Bun v0.2.0 中提供的一个非常实验性的功能。--hot 的官方文档。对于上面的代码,您可以使用:

 bun --hot src/index.ts
Run Code Online (Sandbox Code Playgroud)

或者

 bun run --hot src/index.ts
Run Code Online (Sandbox Code Playgroud)

  • 需要注意的重要一点是,订单很重要。`bun run --hot server.js` 有效,但 `bun run server.js --hot` 无效。 (2认同)

Rob*_*rto 6

对于当前版本(从 0.2.0 开始),请参阅已接受的答案。

在当前版本(v 0.1.6)中,该命令bun dev仅适用于前端项目,不适用于后端(REST API...)。根据Bun Discord 服务器中的一个 Bun 提交者的回答

然而,我们可以使用nodemon工具获得类似的结果:

bun add -d nodemon
Run Code Online (Sandbox Code Playgroud)

将文件添加nodemon.json到项目根目录,内容如下:

{
  "watch": ["src"],
  "ext": ".ts,.js",
  "ignore": [],
  "exec": "bun ./src/index.ts"
}
Run Code Online (Sandbox Code Playgroud)

然后,使用以下命令执行您的项目:

bun run nodemon
Run Code Online (Sandbox Code Playgroud)

节点监控输出

当您更改源文件时,该命令将bun自动重新启动解释器