19

As the applicaiton grows, it is time to remove the hard coded things from the code. Time to implement proper configuration file.

I am thinking to use webpack, and to include configuration file, so I can require it in react.js application.

This is what I have done (webpack.config):

var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: [
  './src/app.js'
],
output: {
  path: path.join(__dirname, 'public/js'),
  filename: 'app.built.js'
},
externals: {
  'Configurator':  require('./config/config-dev.json')
},
module: {
  loaders: [
    { test: /\.js$/, exclude: /node_modules/, loader: 'babel?presets[]=es2015&presets[]=react' },
    { test: /\.css$/, loader: "style-loader!css-loader" }
  ]
}
 };

My JSON file:

{
 "product": {
 "getProducts": "/product",
 "updateProduct": "/updateproduct",
 "deleteProduct": "/deleteproduct"
},
 "project": {
 "getProjects": "/project",
 "updateProduct": "/updateproject",
 "deleteProduct": "/deleteproject"    
}  
}

And in one of the components in React components I try this:

var MyFile = require('Configurator');

There is no error, webpack finds the file. In console I see this:

var MyFile = __webpack_require__(412);

But MyFile is undefined.

What I am doing wrong?

3
  • I don't think you want to use externals here. Maybe alias? Commented Mar 17, 2016 at 16:10
  • Hmmm... I have checked the documentation from the links... would you care to provide an example with alias? :) Commented Mar 17, 2016 at 16:18
  • The config file I am trying to import is just JSON, not the js. And its not located in node_modules :) Commented Mar 17, 2016 at 16:34

1 Answer 1

7

require automatically parses the JSON file. externals expects a string to evaluate, so you'll need to stringify the object:

externals: {
  'Configurator': JSON.stringify(require('./config/config-dev.json'))
},
Sign up to request clarification or add additional context in comments.

5 Comments

'Configurator': JSON.stringify(require('./config/config-dev.json')) does not work in one liner. If I require the file at the top of the webpack.config and then stringify it, then it works...
@wexoni i tried it and still getting the error Cannot find module 'Config'
@Sag1v Did you name the field Config or Configurator?
Config (sorry for not being clear) i followed another post where you mentioned for this post. stackoverflow.com/a/30602665/3148807
I know this is pretty old, but when I try this the JSON is not parsed. See details here: stackoverflow.com/questions/65830412

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.