原文:Using React in Multiple Environments
你的 React 應(yīng)用可以在本地運(yùn)行,但是如何讓它能在不同的環(huán)境中也順利運(yùn)行呢?
包括生產(chǎn)環(huán)境,測試環(huán)境,預(yù)覽環(huán)境等等,所有這些環(huán)境都有自己的服務(wù)器、配置文件,甚至在不同的環(huán)境應(yīng)用會打開或者關(guān)閉特定的功能。
那么,如何實(shí)現(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),你可以導(dǎo)入 API URL
import { API_ROOT } from './api-config';
function getUsers() {
return fetch(`${API_ROOT}/users`)
.then(res => res.json)
.then(json => json.data.users);
}
編譯時(shí)配置
如果你想在編譯時(shí)進(jìn)行配置,也是可以的:
如果你使用 Create React App,你將會獲得一個(gè)全局變量 process.env,通過這個(gè)變量應(yīng)用可以訪問環(huán)境變量,同時(shí)應(yīng)用構(gòu)建后,process.env.NODE_ENV 會被設(shè)置為 “production"
另外,Create React App 工具只會訪問以 “REACT_APP_” 開頭的環(huán)境變量,所以,同樣是環(huán)境變量 REACT_APP_SKITTLE_FLAVOR 可以被訪問到,而 SKITTLE_FLAVOR 就不行
下面我們來看一下如何在構(gòu)建時(shí)添加環(huán)境變量:
-
Linux 系統(tǒng)
$ REACT_APP_API_HOST=example.com yarn run build在應(yīng)用中就可以訪問到如下變量
- 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
在構(gòu)建時(shí)配置功能開關(guān)
環(huán)境變量可以被設(shè)置為任意值,一個(gè)潛在的用途是在不通的環(huán)境中打開或者關(guān)閉特定的功能。在構(gòu)建時(shí)你可以進(jì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)建一個(gè) .env 文件,然后將環(huán)境變量添加到里面:
REACT_APP_SPECIAL_FEATURE=true
REACT_APP_API_HOST=default-host.com
這些變量在不通的環(huán)境中都會加載,如果你想定義一些某個(gè)環(huán)境特定的變量,則可以創(chuàng)建名為.env.development, .env.test, 或者 .env.production 的 env 文件。
.env 文件的類型
- .env: 默認(rèn).
- .env.local: 本地覆蓋(overrides)。這個(gè)文件將會在除了測試環(huán)境之外的所有環(huán)境加載。
- .env.development, .env.test, .env.production: 環(huán)境特定設(shè)置。
- .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
});
}