[英]Pass environment variable from package.json to React app
I'm building a React / Node / Express / Webpack (2.2.1) application and would like to know how to approach the following: 我正在构建一个React / Node / Express / Webpack(2.2.1)应用程序,并且想知道如何处理以下内容:
I would like an environment variable to be visible in the React client - the purpose being for certain api requests to use either the localhost or otherwise the IP address of the production server. 我希望环境变量在React客户端中可见-目的是某些api请求使用本地主机或生产服务器的IP地址。
Is it possible to get an environment variable from running a script in package.json, to the webpack build, and then compiled and visible in the bundled javascript. 是否有可能通过在package.json中运行脚本来获取环境变量,然后到webpack构建中进行编译,然后在捆绑的javascript中显示该变量。
So in terminal run: 所以在终端运行:
npm run build-dev // pass to Webpack something like APP_ENV="development"
or 要么
npm run build-prod // pass to Webpack something like APP_ENV="production"
and the script definition being something like: 脚本定义类似于:
"scripts": {
"build-dev": "webpack --define APP_ENV='development'"
}
...help greatly appreciated ...帮助非常感谢
--define
option using webpack.DefinePlugin
so you must pass a string value into app. 使用
webpack.DefinePlugin
--define
选项,因此您必须将字符串值传递给应用程序。
"scripts": { "build-dev": "webpack --define APP_ENV=\\"'development'\\"" }
APP_ENV="development" npm run build-dev
nodejs set environment variables at the head of command.you can use webpack.EnvironmentPlugin
to expose process.env into bundle.js that I have tested. APP_ENV="development" npm run build-dev
在命令开头APP_ENV="development" npm run build-dev
nodejs设置环境变量。您可以使用webpack.EnvironmentPlugin
将process.env暴露到我测试过的bundle.js中。
"scripts": { "build-dev": "APP_ENV=development webpack" }
Test
describe('string-replace-webpack-loader', () => { it('environment exists', () => { expect(process.env.APP_ENV).toBe('dev'); }); it('replace environment variables', compile({ entry: './env.js', plugins: [ new webpack.EnvironmentPlugin(Object.keys(process.env)) ] }).then(({log}, files) => { expect(files['/bundle.js']).toMatch(/(["'])dev\\1/); })); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.