【问题标题】:Docker TypeScript: No hot loading when I make changes to the filesDocker TypeScript:更改文件时没有热加载
【发布时间】:2021-09-21 05:08:42
【问题描述】:

基本上,当我对我的 ts 文件进行更改时,它不会反映在浏览器中,也不会反映在应该显示刷新日志的控制台中。我正在使用 nodemon 来处理打字稿更改,并且全部使用 Docker 和 docker-compose。 docker-compose 在 server 文件夹之外,server 文件夹的主要文件存储在 src 子文件夹中

nodemon.json

{
  "watch": [
    "src",
    ".env"
  ],
  
  "ext": "js,ts,json",
  "ignore": [
    "src/**/*.spec.ts"
  ],
  "execMap": {
    "ts": "node --inspect=0.0.0.0:9229 --nolazy -r ts-node/register"
  }
}

packaje.json 脚本

  "scripts": {
    "start": "NODE_PATH=./build node build/app.js",
    "inspect": "nodemon --inspect src/app.ts",
    "dev": "nodemon src/app.ts",
    "build": "tsc -p .",
    "test": "jest"
  },

Docker

FROM node:16
RUN apt-get update
WORKDIR /usr/app
COPY . . 

RUN yarn install

docker-compose 仅​​用于服务器

server:
        container_name: server
        build: 
            context: ./server
        command: yarn run dev 
        volumes: 
            - ./server/src:/usr/app/src
            - ./server/nodemon.json:/usr/app/src/nodemon.json

【问题讨论】:

  • 你能在主机上运行yarn run dev,而不涉及Docker吗?将 Docker 引入此设置有什么好处?
  • yarn run dev 在主机上热重载它。我正在使用 docker,因为我将使用 mongodb 数据库并托管在数字海洋上。

标签: javascript node.js typescript docker nodemon


【解决方案1】:

我通过将 nodemon 设置为在容器内部工作来解决这个问题。首先我全局安装了nodemon

FROM node:16
RUN apt-get update
WORKDIR /usr/app
COPY . .
RUN yarn global add nodemon
RUN yarn install

然后是docker-compose中的命令

command: nodemon /usr/app/src/index.js

【讨论】:

    【解决方案2】:

    您可以在这里尝试做几件事!

    1. Nodemon 配置

    就上下文而言,此建议是在查看了看起来与您正在构建的相似的 this tutorial 后得出的!

    仔细检查 Nodemon 配置文件的格式和命名是否正确。在帖子中,您将其命名为 nodemon.js,而它在 Docker 容器中挂载为 nodemon.json

    同样,可以将 Nodemon 配置中的 src 指令扩展为 src/**/*.ts。我不确定您要更改哪些文件以触发热重载,但这会告诉 Nodemon 搜索 src 文件夹的所有子目录以查找 Typescript 文件更改。

    2。使用 Transpiled Typescript 的替代解决方案

    过去,我使用内置的 Javascript 来在 Docker 容器中为 Typescript 提供热重载。这是在服务器上,具有与您描述的类似的目录结构。这可能是一个可行的最后手段。

    这里有一些步骤:

    1. 安装concurrently(同时运行多个命令的包)
    yarn add -D concurrently
    
    1. package.json 中更新您的脚本
    "scripts": {
      "watch": "tsc -w",    // Typescript watcher, will retranspile TS to JS in the dist folder when changes are made
      "dev": "nodemon -L dist/index.js", // Runs nodemon in legacy mode, 'dist/index.js' is the file the Typescript is transpiled to
      "start": "concurrently -k \"npm:watch\" \"npm:dev\"" // Runs the Typescript watcher and nodemon at the same time
    }
    
    1. 更新您的 compose 挂载(可以添加 nodemon 配置挂载,尽管它是可选的)
     command:
       yarn start  
     volumes:
       ./server/src:/usr/app/src
    

    再一次,完全可能是最后的手段。但是,通过这样做,Typescript 观察程序将在您进行更改时重新编译您的代码,并且 nodemon 将在 dist 中接收这些更改。

    【讨论】:

      猜你喜欢
      • 2019-02-04
      • 2018-03-03
      • 1970-01-01
      • 2016-10-25
      • 2017-08-01
      • 2021-08-26
      • 1970-01-01
      • 2020-10-30
      相关资源
      最近更新 更多