Last active
March 25, 2016 20:46
-
-
Save tybro0103/aeb0be2cb76b2c2ae431 to your computer and use it in GitHub Desktop.
Universal JavaScript Config Vars
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// /app/config.js | |
class Config { | |
constructor() { | |
this.data = {}; | |
} | |
setData(data) { | |
this.data = {...this.data, ...data}; | |
} | |
get(field) { | |
return this.data[field]; | |
} | |
}; | |
export default new Config(); | |
// /server/index.js | |
import appConfig from '../app/config'; | |
appConfig.setData({ | |
cdnBaseUrl: process.env.CDN_BASE_URL | |
}); | |
// /server/components/html.jsx | |
import config from '../../app/config'; | |
const serializedConfig = serialize(config.data); | |
const scriptHtml = `window.CONFIG_DATA=${serializedConfig};`; | |
<script dangerouslySetInnerHTML={{__html: scriptHtml}} /> | |
// /client/index.js | |
import config from '../app/config'; | |
const configData = window.CONFIG_DATA; | |
config.setData(configData); | |
// anywhere/else.js | |
import config from './app/config'; | |
config.get('cdnBaseUrl'); // http://cdn.sm.com/... | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment