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?

Amiga500
  • 5,874
  • 10
  • 64
  • 117
  • I don't think you want to use [`externals`](https://webpack.github.io/docs/configuration.html#externals) here. Maybe [`alias`](https://webpack.github.io/docs/configuration.html#resolve-alias)? – Felix Kling Mar 17 '16 at 16:10
  • Hmmm... I have checked the documentation from the links... would you care to provide an example with alias? :) – Amiga500 Mar 17 '16 at 16:18
  • The config file I am trying to import is just JSON, not the js. And its not located in node_modules :) – Amiga500 Mar 17 '16 at 16:34

1 Answers1

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'))
},
Petr Bela
  • 8,493
  • 2
  • 33
  • 37
  • '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... – Amiga500 Mar 18 '16 at 07:41
  • @wexoni i tried it and still getting the error `Cannot find module 'Config'` – Sagiv b.g Apr 03 '17 at 14:42
  • @Sag1v Did you name the field Config or Configurator? – Petr Bela Apr 03 '17 at 17:36
  • 1
    Config (sorry for not being clear) i followed another post where you mentioned for this post. http://stackoverflow.com/a/30602665/3148807 – Sagiv b.g Apr 03 '17 at 18:44
  • I know this is pretty old, but when I try this the JSON is not parsed. See details here: https://stackoverflow.com/questions/65830412/ – McGuireV10 Jan 21 '21 at 16:49