如何在 ReactJS Docker 中实现热重载?


热重载是在 Web 浏览器上为 React 应用程序添加动态功能。这意味着如果我们更改应用程序代码中的某些内容,它会立即反映到 Web 应用程序前端。但在“重新加载”任何内容之前,我们必须了解“加载”,即在 Node Docker 容器上创建一些 ReactJs 项目。

创建和容器化 React 应用

步骤 1:React 应用

使用预构建命令创建一个基本的 React 应用程序。

示例

$npx create-react-app reactapp

输出

npx: installed 67 in 19.076s

Creating a new React app in /home/hemant/project/reactapp.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...


> [email protected] postinstall /home/hemant/project/test/reactapp/node_modules/core-js
> node -e "try{require('./postinstall')}catch(e){}"

> [email protected] postinstall /home/hemant/project/test/reactapp/node_modules/core-js-pure
> node -e "try{require('./postinstall')}catch(e){}"

+ [email protected]
+ [email protected]
+ [email protected]
+ [email protected]
added 1407 packages from 624 contributors in 233.937s

213 packages are looking for funding
  run `npm fund` for details


Initialized a git repository.

Installing template dependencies using npm...
npm WARN @apideck/[email protected] requires a peer of ajv@>=8 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of typescript@>= 2.7 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

+ @testing-library/[email protected]
+ @testing-library/[email protected]
+ @testing-library/[email protected]
+ [email protected]
added 72 packages from 89 contributors in 21.128s

226 packages are looking for funding
  run `npm fund` for details

Removing template package using npm...

npm WARN @apideck/[email protected] requires a peer of ajv@>=8 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of typescript@>= 2.7 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

removed 1 package and audited 1479 packages in 9.798s

226 packages are looking for funding
  run `npm fund` for details

found 1 high severity vulnerability
  run `npm audit fix` to fix them, or `npm audit` for details
Git commit not created Error: Command failed: git commit -m "Initialize project using Create React App"
   at checkExecSyncError (child_process.js:790:11)
   at execSync (child_process.js:863:15)
   at tryGitCommit (/home/hemant/project/test/reactapp/node_modules/react-scripts/scripts/init.js:62:5)
   at module.exports (/home/hemant/project/test/reactapp/node_modules/react-scripts/scripts/init.js:350:25)
   at [eval]:3:14
   at Script.runInThisContext (vm.js:134:12)
   at Object.runInThisContext (vm.js:310:38)
   at internal/process/execution.js:81:19
   at [eval]-wrapper:6:22
   at evalScript (internal/process/execution.js:80:60) {
  status: 128,
  signal: null,
  output: [ null, null, null ],
  pid: 8786,
  stdout: null,
  stderr: null
}
Removing .git directory...

Success! Created reactapp at /home/hemant/project/reactapp
Inside that directory, you can run several commands:

  npm start
   Starts the development server.

  npm run build
   Bundles the app into static files for production.

  npm test
   Starts the test runner.

  npm run eject
   Removes this tool and copies build dependencies, configuration files
   and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd reactapp
  npm start

Happy hacking!

执行上述命令后,将创建一个名为“reactapp”的新文件夹。其中包含 React Web 应用程序运行所需的所有必要文件。我们也可以在主机平台上运行此应用程序,但我们的需求是在 Docker 容器上运行此应用程序,并为其提供热重载的功能。

步骤 2:Dockerfile

现在为这个 React 应用程序创建一个 Dockerfile。

示例

#Here we will use node as the base image. FROM node:14.21.1-alpine #create a working directory inside the container. WORKDIR /app #Environment variables. ENV PATH /app/node_modules/.bin:$PATH #copy the files from the host to the container. COPY package.json ./ COPY package-lock.json ./ #install npm and react versions. RUN npm install --silent RUN npm install react-scripts@5.0.1 -g --silent #install nodemon to provide hot-reloading functionality. RUN npm install nodemon --save-dev COPY . ./ #use nodemon to run the react application using npm. CMD ["nodemon", "--exec", "npm", "start"]

步骤 3:创建 Dockerignore

通过创建一个 .dockerignore 文件,我们将忽略一些不需要的文件,避免将其复制到容器中。

示例

node_modules build .dockerignore Dockerfile Dockerfile.prod

步骤 4:构建镜像

现在所有前提条件都已完成,我们只需为这个 React 应用程序创建镜像,然后在容器上运行它进行测试。

示例

$docker build -t react_img .

输出

Sending build context to Docker daemon  587.3kB
Step 1/10 : FROM node:14.21.1-alpine
 ---> 87112681acad
Step 2/10 : WORKDIR /app
 ---> Using cache
 ---> 0b207dfe1b40
Step 3/10 : ENV PATH /app/node_modules/.bin:$PATH
 ---> Using cache
 ---> 8a6c9d9d6d96
Step 4/10 : COPY package.json ./
 ---> Using cache
 ---> 97342fa619fa
Step 5/10 : COPY package-lock.json ./
 ---> Using cache
 ---> 8c04867af3e6
Step 6/10 : RUN npm install --silent
 ---> Using cache
 ---> 0ab355131c9e
Step 7/10 : RUN npm install [email protected] -g --silent
 ---> Using cache
 ---> 1698f24cd34c
Step 8/10 : RUN npm install nodemon --save-dev
 ---> Using cache
 ---> 8b2ed3bc8422
Step 9/10 : COPY . ./
 ---> Using cache
 ---> f69b093c6605
Step 10/10 : CMD ["nodemon", "--exec", "npm", "start"]
 ---> Using cache
 ---> 13071aaea8eb
Successfully built 13071aaea8eb
Successfully tagged react_img:latest

步骤 5:创建容器

在这里,我们必须为上面创建的镜像“react_img”创建 Docker 容器。此外,在容器化过程中,我们需要将端口号从主机发布到容器。

示例

$docker run -it --name react_container_app -p 3000:3000 react_img

输出

[nodemon] 2.0.20
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `npm start`

> [email protected] start /app
> react-scripts start

Compiled successfully!
You can now view reactapp in the browser.

   Local:            https://127.0.0.1:3000
   On Your Network:  http://172.17.0.2:3000

Note that the development build is not optimized.
To create a production build, use npm run build.

webpack compiled successfully

在“localhost:3000”上检查服务器,应用程序正常工作。

热重载应用程序服务器

有两种方法可以热重载 React 应用程序,一种是在 Docker 容器内部更改代码,另一种是在容器外部更改代码。

从容器内部

首先,使用 exec 命令进入容器内部

$docker exec -it react_container_app sh

现在将目录更改为 app/src/ 并更改 App.js 内部的代码,查看 Web 应用程序中是否出现了任何更改。将文本更改为“THIS IS TUTORIALSPOINT REACT APPLICATION”。

示例

$cd src/ $vi App.js

输出

import logo from './logo.svg';
import './App.css';

function App() {
   return (
      <div className="App">
      <header className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      <p>
         THIS IS TUTORIALSPOINT REACT APPLICATION.
      </p>
      <a
         className="App-link"
         href="https://reactjs.ac.cn"
         target="_blank"
         rel="noopener noreferrer"
      >
         Learn React
      </a>
      </header>
   </div>
  );
}

export default App;
~
~
~
~

现在检查更改是否生效。

因此,React 应用程序对代码中的任何实时更改都有响应。

从容器外部

要执行此任务,您需要创建一个新的容器并将该容器绑定到卷或应用程序目录,这将允许容器检测主机机器上代码的任何更改。

创建容器。

示例

$docker run -it \ --name new_react_container \ --volume ./reactapp/:/app/ \ -p 3000:3000 react_img

检查服务器是否正在运行。

现在在主机目录中更改代码并查看更改。

示例

$cd /reactapp/src $vi App.js

输出

import logo from './logo.svg';
import './App.css';

function App() {
   return (
      <div className="App">
      <header className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      <p>
         CHANGES FROM OUTSIDE THE CONTAINER.
      </p>
      <a
         className="App-link"
         href="https://reactjs.ac.cn"
         target="_blank"
         rel="noopener noreferrer"
      >
         Learn React
      </a>
      </header>
   </div>
   );
}

export default App;
~
~
~
~

检查更改是否已反映到 Web 应用程序中。

这些是在应用程序更新时热重载 React 容器的一些方法。

更新于: 2022-12-28

10K+ 浏览量

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告