0

我在heroku 上部署了一个mern 堆栈应用程序。我的应用程序的目录结构是这样的: -

|__client/  ** THIS IS EVERYTHING FROM THE REACT SIDE **
    |__ node_modules/
        |__ tons of stuff...
    |__ public/
        |__ index.html
        |__ favicon.ico
        |__ etc.
    |__ src/
        |__ index.js
        |__ main/
            |__ App.js
            |__ etc.
|__ models/
    |__ user.js
    |__ todo.js
    |__ etc.
|__ node_modules/
    |__ stuff...
|__ routes
    |__ userRoutes.js
    |__ todoRoutes.js
    |__ etc.
|__ .gitignore
|__ package.json
|__ server.js
|__ etc.

我在 heroku 中为后端设置了一些环境变量,这些环境变量运行得非常好。我正在从 express 应用程序中提供我的 react 构建文件夹。我的反应应用程序有一些我无法访问的环境变量。有什么方法可以从 /client 目录访问 heroku 中的 env 吗?

这是我用于后端的 package.json

{
    "name": "mern-to-heroku",
    "version": "1.0.0",
    "main": "index.js",
    "license": "MIT",
    "dependencies": {
        "body-parser": "^1.18.2",
        "express": "^4.16.2",
        "mongoose": "^4.13.6",
        "morgan": "^1.9.0"
    },
    "scripts": {
        "start": "node server.js",
        "heroku-postbuild": "cd client && npm install --only=dev && npm install && npm run build"
    },
    "engines": {
        "node": "8.9.2"
    }
}
4

1 回答 1

1

环境。仅在npm run build您的 react 应用程序的构建时 ( ) 可用,然后将替换为它们的值。它们在您的应用程序运行时不“可用”,因此在您的 react-app 构建后它们无法更改。

这意味着如果环境变量仅在 heroku 上可用,您将不得不在 heroku 本身上构建您的应用程序。

示例:如果您使用的是deploy-to-heroku按钮,您可以添加到app.json(当然,需要为您的设置定制):

 "scripts": {
    "postdeploy": "npm run build"
 },

用新的环境构建你的 react-app。部署到heroku之后

于 2021-03-11T19:55:17.420 回答