【问题标题】:Hot-reload (HMR) with 'bun dev'使用 \'bun dev\' 进行热重载 (HMR)
【发布时间】:2022-10-23 23:57:57
【问题描述】:

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

我遵循的步骤:

bun create hono test-api
cd test-api
bun dev

然后服务器显示此消息:

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


  Link: http://localhost:3000

当我修改任何文件时,服务器会检测到它然后重新加载应用程序但我不知道如何调用我的应用程序 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

index.ts 中的原始生成代码为:

import { Hono } from "hono";

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}`);

export default {
  port,
  fetch: home.fetch,
};

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

如何调用运行 bun dev 的 hono API Hello-Word?

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

【问题讨论】:

    标签: typescript hot-reload bun hono


    【解决方案1】:

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

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

    bun add -d nodemon
    

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

    {
      "watch": ["src"],
      "ext": ".ts,.js",
      "ignore": [],
      "exec": "bun ./src/index.ts"
    }
    

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

    bun run nodemon
    

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

    【讨论】:

      【解决方案2】:

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

       bun --hot src/index.ts
      

      或者

       bun run --hot src/index.ts
      

      【讨论】:

        猜你喜欢
        • 2021-03-10
        • 2022-07-18
        • 2017-06-16
        • 1970-01-01
        • 2019-04-26
        • 2016-12-28
        • 1970-01-01
        • 2011-04-21
        • 2019-10-29
        相关资源
        最近更新 更多