2

I am trying to follow this link about setting up global configuration. And I am unable to make it work. When I run my reactjs component I get an error that Config is undefined.

my webpack.config file looks like this:

module.exports = {
  entry: './src/app.js',
  externals: {
    'Config': JSON.stringify({
      optionsService: 'http://localhost:8080/options'
    })
  },
  output: {
    path: __dirname,
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: { presets: [ 'es2015', 'react' ] }
      }
    ]
  }
};

and I've tried using it like this:

import React from 'react';
import Config from 'Config';

// these also fail
// const Config = require('Config');
// var Config = require('Config');
// let Config = require('Config');


export default class MyComponent extends React.Component {
    render() {
        return (
            <div>
            {Config.optionsService}
            </div>
        );
    }
}

I've also tried the commented out lines, to no available.

What am I doing wrong?

Thank you Matt

atomrc
  • 2,543
  • 1
  • 16
  • 20
tatmanblue
  • 1,176
  • 2
  • 14
  • 30
  • Well I tried your config and it seems to work. Which version of webpack are you using (I am not sure if it changes anything). Also, if you are using the `watch` of webpack, have you killed and relaunched the watcher after adding the config? – atomrc May 25 '17 at 21:20
  • @atomrc So I was using npm as the web server. After I killed npm and restarted the server, it worked for me too. A bit embarassing. I'm guessing npm didnt pull in the webpack changes as I made them. Is that possible? – tatmanblue May 25 '17 at 21:22
  • well, if the npm script you were running is the one that was watching for the changes in your source files and compiling them, I'd say it's highly probable. Webpack is loading the config file only at startup so if you update it, you need to reload the watcher :) – atomrc May 25 '17 at 21:25

1 Answers1

4
$ npm install react-global-configuration

After install:

import config from 'react-global-configuration';

config.set({ foo: 'bar' });

getting your value

import config from 'react-global-configuration';

config.get('foo');
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
  • It such an anti-pattern for react. Instead of values being propagated, components have to query params themselves. It is not useful especially if one needs render components that depend on a particular variable – Turkhan Badalov Apr 27 '21 at 22:45