How to enter port and host using ENV variable in Create React proxy settings?

Is it possible to set proxy settings in CRA differently than with package.json? For example, using ENV variables?

From CRA docs, he points

Use environment variables to enter the correct host and server port in your application.

Is this a suggestion about a proxy server or the development server itself?

According to this and this , the only way to influence proxy settings is through package.json.

+4
source share
3 answers

Regarding

Use environment variables to enter the correct host and server port in your application.

-, -. , , proxy (.. , http, https ws). , api , , - :

axios(process.env.REACT_APP_BASE_URL + endpoint, options).then(data=>{ console.dir(data); })

REACT_APP_BASE_URL.


package.json:

package.json.

. ( CRA)

package.json .

96 CRA start.js. ENV vars / - CRA.

, CRA, . , CRA.


:

npm run eject

... start.js script, , - , . , ENV vars.

, , , .

- CRA - CAN package.json .


ENV vars package.json :

, , , CRA REACT_APP_ env vars ( process.env).

package.json - JSON, , , , "proxy" , ENV vars, , /.

, , script , process.env:

const fs = require('fs');

// read/process package.json
const file = './package.json';
let pkg = JSON.parse(fs.readFileSync(file).toString());

// at this point you should have access to your ENV vars
pkg.proxy = `${process.env.HOST}:${process.env.PORT}`;

// the 2 enables pretty-printing and defines the number of spaces to use
fs.writeFileSync(pkg, JSON.stringify(file, null, 2));

, , " package.json", , .

, DOES " ENV - Create React?"

+1

- CRA , package.json?

. . , , (2017/01/14).

- React , - React env , "" -.

- -?

dev. -, , .

+1

env .   REACT_APP_PORT: "PORT of Application", REACT_APP_HOST: "host of application"

env , webpack define plugin.

, .

const env = require("path to your env file")
//other webpack settings
plugins: {
//plugins
new webpack.DefinePlugin(env)
}

, --, env, port host.

,

, REACT_APP_. , NODE_ENV, , ,

-1

Source: https://habr.com/ru/post/1687303/


All Articles