Provide what is essentially an explicitly set of frozen global variables which can then be required by any module that needs them.
This can be preferable to having to pass any configuration all the way through your node application, or put your configuration inside state of component. This method is usually better than setting global variables.
$ npm install react-global-configuration
set( configuration [, options] )
import config from 'react-global-configuration';
config.set({ foo: 'bar' });
- configuration whatever you want to be made available when subsequently importing / requiring get function
react-global-configuration
. - options object optionally containing the following
get( [key] )
import config from 'react-global-configuration';
config.get('foo');
- key key to the setting you want to recover. If you do not put this key you recover all settings
reset()
import reset from 'react-global-configuration/reset';
reset();
This is a testing utility that removes the existing configuration from the require cache. By calling this, calling config.set(configuration)
and then re-requiring any target file, that target file will then be returned from require with the new configuration
applied.
server.js (initiation of server side process)
import config from 'react-global-configuration';
import MyApplication from './app';
config.set({ foo: 'bar' });
new MyApplication();
client.js (initiation of client side js, assume compiled via browserify / webpack / similar)
import React from 'react';
import config from 'react-global-configuration';
import App from './app';
(function clientJS() {
config.set(window.__INITIAL_CONFIG__);
React.render(<App/>, document);
}());
component.js (somewhere inside the client side app)
import React from 'react';
import config from 'react-global-configuration';
class Component extends React.Component {
render() {
return (
<div>{ config.get('foo') }</div>
);
}
});
export default Component;
gulp/test.js
import gulp from 'gulp';
import mocha from 'gulp-mocha';
import config from 'react-global-configuration';
config.set({ foo: 'baz' }, { freeze: false });
gulp.task('test', function gulpTest() {
return (
gulp
.src([ 'app/**.test.*' ], { read: false })
.pipe(mocha())
);
});
appLogic.test.js
import reset from 'react-global-configuration/reset';
import assert from 'assert';
describe('appLogic', () => {
it('should return foo from configuration', () => {
import config from 'react-global-configuration';
const foos = [ 'alpha', 'beta', 'gamma' ];
foos.forEach((foo) => {
// This only works because `freeze: false` was set the first time set was called (in gulp/test.js).
config.set({ foo: foo });
const appLogic = require('./appLogic');
assert(appLogic() === foo);
});
});
afterEach(() => {
reset();
});
});
React global configuration was initially inspired by global-configuration. Many thanks to Josh-a-e.