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

3
  • 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? Commented May 25, 2017 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? Commented May 25, 2017 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 :) Commented May 25, 2017 at 21:25

1 Answer 1

5
$ 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');
Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.