Skip to content

Instantly share code, notes, and snippets.

@tybro0103
Last active March 25, 2016 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tybro0103/aeb0be2cb76b2c2ae431 to your computer and use it in GitHub Desktop.
Save tybro0103/aeb0be2cb76b2c2ae431 to your computer and use it in GitHub Desktop.
Universal JavaScript Config Vars
// /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