原文:Using React in Multiple Environments
你的 React 應用可以在本地運行厦坛,但是如何讓它能在不同的環(huán)境中也順利運行呢旦事?
包括生產(chǎn)環(huán)境,測試環(huán)境物舒,預覽環(huán)境等等织盼,所有這些環(huán)境都有自己的服務器闻牡、配置文件,甚至在不同的環(huán)境應用會打開或者關閉特定的功能俺亮。
那么驮捍,如何實現(xiàn)上述需求呢?下面我們介紹幾種方法
動態(tài)配置
如果不同環(huán)境是通過不同的域名訪問的脚曾,那么這種策略很合適
在 api-config.js 中加入下列代碼:
let backendHost;
const apiVersion = 'v1';
const hostname = window && window.location && window.location.hostname;
if(hostname === 'realsite.com') {
backendHost = 'https://api.realsite.com';
} else if(hostname === 'staging.realsite.com') {
backendHost = 'https://staging.api.realsite.com';
} else if(/^qa/.test(hostname)) {
backendHost = `https://api.${hostname}`;
} else {
backendHost = process.env.REACT_APP_BACKEND_HOST || 'http://localhost:8080';
}
export const API_ROOT = `${backendHost}/api/${apiVersion}`;
然后在 API 文件中(比如东且,api.js),你可以導入 API URL
import { API_ROOT } from './api-config';
function getUsers() {
return fetch(`${API_ROOT}/users`)
.then(res => res.json)
.then(json => json.data.users);
}
編譯時配置
如果你想在編譯時進行配置本讥,也是可以的:
如果你使用 Create React App珊泳,你將會獲得一個全局變量 process.env
,通過這個變量應用可以訪問環(huán)境變量拷沸,同時應用構建后色查,process.env.NODE_ENV
會被設置為 “production"
另外,Create React App 工具只會訪問以 “REACT_APP_” 開頭的環(huán)境變量撞芍,所以秧了,同樣是環(huán)境變量 REACT_APP_SKITTLE_FLAVOR 可以被訪問到,而 SKITTLE_FLAVOR 就不行
下面我們來看一下如何在構建時添加環(huán)境變量:
-
Linux 系統(tǒng)
$ REACT_APP_API_HOST=example.com yarn run build
在應用中就可以訪問到如下變量
- process.env.REACT_APP_API_HOST === "example.com"
- process.env.NODE_ENV === "production"
-
Windows 系統(tǒng)
:\> set REACT_APP_API_HOST=example.com :\> yarn run build
在構建時配置功能開關
環(huán)境變量可以被設置為任意值勤庐,一個潛在的用途是在不通的環(huán)境中打開或者關閉特定的功能示惊。在構建時你可以進行這樣的操作:
$ REACT_APP_SPECIAL_FEATURE=true yarn run build
你將獲得如下變量:
# process.env.REACT_APP_SPECIAL_FEATURE === "true"
# process.env.NODE_ENV === "production"
然后你可以在代碼的任意位置檢查這些變量:
function HomePage() {
if(process.env.REACT_APP_SPECIAL_FEATURE === "true") {
return <SpecialHomePage/>;
} else {
return <PlainOldBoringHomePage/>;
}
}
.env Files
Create React App 支持通 .env
文件將環(huán)境變量持久保存。
你可以創(chuàng)建一個 .env 文件愉镰,然后將環(huán)境變量添加到里面:
REACT_APP_SPECIAL_FEATURE=true
REACT_APP_API_HOST=default-host.com
這些變量在不通的環(huán)境中都會加載米罚,如果你想定義一些某個環(huán)境特定的變量,則可以創(chuàng)建名為.env.development
, .env.test
, 或者 .env.production
的 env 文件丈探。
.env 文件的類型
- .env: 默認.
- .env.local: 本地覆蓋(overrides)录择。這個文件將會在除了測試環(huán)境之外的所有環(huán)境加載。
- .env.development, .env.test, .env.production: 環(huán)境特定設置。
- .env.development.local, .env.test.local, .env.production.local: 針對不通環(huán)境的覆蓋配置隘竭。
.env 文件的優(yōu)先級
左邊的優(yōu)先級高于右邊
- npm start: .env.development.local, .env.development, .env.local, .env
- npm run build: .env.production.local, .env.production, .env.local, .env
- npm test: .env.test.local, .env.test, .env (note .env.local is missing)
Variables are Baked In
At the risk of stating the obvious: the “environment variables” will be baked in at build time. Once you build a JS bundle, its process.env.NODE_ENV and all the other variables will remain the same, no matter where the file resides and no matter what server serves it. After all, a React app does not run until it hits a browser. And browsers don’t know about environment variables.
Unit Testing
Once you’ve got all these variables multiplying your code paths, you probably want to test that they work. Probably with unit tests. Probably with Jest (that’s what I’m showing here anyway).
If the variables are determined at runtime, like in the first example above, a regular import './api-config' won’t cut it – Jest will cache the module after the first import, so you won’t be able to tweak the variables and see different results.
These tests will make use of two things: the require() function for importing the module inside tests, and the jest.resetModules() function to clear the cache.
// (this could also go in afterEach())
beforeEach(() => {
// Clear the Jest module cache
jest.resetModules();
// Clean up the environment
delete process.env.REACT_APP_BACKEND_HOST;
});
it('points to production', () => {
const config = setupTest('realsite.com');
expect(config.API_ROOT).toEqual('https://api.realsite.com/api/v1');
});
it('points to staging', () => {
const config = setupTest('staging.realsite.com');
expect(config.API_ROOT).toEqual('https://staging.api.realsite.com/api/v1');
});
it('points to QA', () => {
const config = setupTest('qa5.company.com');
expect(config.API_ROOT).toEqual('https://api.qa5.company.com/api/v1');
});
it('points to dev (default)', () => {
const config = setupTest('localhost');
expect(config.API_ROOT).toEqual('http://localhost:8080/api/v1');
});
it('points to dev (custom)', () => {
process.env.REACT_APP_BACKEND_HOST = 'custom';
const config = setupTest('localhost');
expect(config.API_ROOT).toEqual('custom/api/v1');
});
function setupTest(hostname) {
setHostname(hostname);
return require('./api-config');
}
// Set the global "hostname" property
// A simple "window.location.hostname = ..." won't work
function setHostname(hostname) {
Object.defineProperty(window.location, 'hostname', {
writable: true,
value: hostname
});
}