将React应用程序作为后台进程运行

3

我完全不了解如何部署前端代码,所以有以下问题。 我有一个React应用程序,我需要将其作为后台进程运行,但是我对如何实现这一点有些困惑。 我运行一个npm脚本

npm run build

构建、压缩并在服务器上提供项目。 构建过程的相关代码如下。

"prebuild": "npm-run-all clean-dist test lint build:html",
"build": "babel-node tools/build.js",
"postbuild": "babel-node tools/distServer.js"

这是distServer.js文件中的代码。
import express from 'express';
import path from 'path';
import open from 'open';
import compression from 'compression';


const port = 3000;
const app = express();

app.use(compression());
app.use(express.static('dist'));

app.get('*', function(req, res){
  res.sendFile(path.join(__dirname, '../dist/index.html'));
});

app.listen(port, function(err){
  if(err){
    console.log(err);
  }else{
    open(`http://localhost:${port}`);
  }
});

这个可以运行,项目也能正常进行,但是一旦关闭终端,项目就会停止。构建过程会创建三个文件。

index.html
index.js
styles.css

现在,如果我导航到index.html并在浏览器中打开它,但自然地,什么也不会显示出来。因此,我假设我必须将其作为一个节点进程运行。在生产服务器上如何做到这一点,并将其作为后台进程运行,以便即使我退出终端应用程序仍然可以继续运行。 我已经检查了这个问题, 如何使node.js应用程序永久运行? 但是这个问题的入口点是一个javascript文件,而在我的情况下它是一个html文件。我不确定如何修改我的脚本,以便将前端应用程序永久地作为后台进程运行。任何帮助都将不胜感激。

对于开发来说,“后台进程”至少可以是终端仿真器中的另一个选项卡,它并不总是需要使用init系统设置为守护程序。显然,在生产环境中需要这样做,但是... - ssube
2个回答

3

您的 Javascript 文件 (distServer.js) 您的入口点 - 这是您运行以启动服务器的文件。您的 HTML 文件 (index.html) 仅作为响应请求而提供。

babel-node 在开发中可以使用,但不适用于生产环境。您可以将 JavaScript 文件预编译为普通的 JavaScript,然后按照您在已链接的问题中所述使用 foreverpm2 来保持服务器运行,即使您关闭终端也是如此。

您如何组织源文件和编译文件取决于您自己,但以下是一种方法 (引用自一个使用 Babel 的示例 Node 服务器的文档):

Getting ready for production use

So we've cheated a little bit by using babel-node. While this is great for getting something going. It's not a good idea to use it in production.

We should be precompiling your files, so let's do that now.

First let's move our server index.js file to lib/index.js.

$ mv index.js lib/index.js

And update our npm start script to reflect the location change.

  "scripts": {
-   "start": "nodemon index.js --exec babel-node --presets es2015,stage-2"
+   "start": "nodemon lib/index.js --exec babel-node --presets es2015,stage-2"
  }

Next let's add two new tasks npm run build and npm run serve.

  "scripts": {
    "start": "nodemon lib/index.js --exec babel-node --presets es2015,stage-2",
+   "build": "babel lib -d dist --presets es2015,stage-2",
+   "serve": "node dist/index.js"
  }

Now we can use npm run build for precompiling our assets, and npm run serve for starting our server in production.

$ npm run build
$ npm run serve

This means we can quickly restart our server without waiting for babel to recompile our files.

Oh let's not forget to add dist to our .gitignore file.

$ touch .gitignore

dist

This will make sure we don't accidentally commit our built files to git.


经过一番努力,我已经想出了类似的解决方案,但问题是我似乎无法在Linux上安装babel-node。在Mac上开发时,我使用了babel-node,它似乎可以工作,但看起来在Linux上不起作用。有没有绕过这个问题的方法? - user6761897
@StochasticNerd 你的依赖项中有安装 babel-cli npm 包,对吗? - Viktor

0
尝试运行 'npm install -g pm2',然后跟着输入 'pm2 start npm --(你的应用名称) -- start'
React 应用程序将在你关闭终端后继续在后台运行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接