Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack -- include configuration file as external resource

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?

like image 274
Wexoni Avatar asked Mar 17 '16 16:03

Wexoni


People also ask

Where do I put webpack config?

The easiest way to get your webpack. config. js file to work is to place it at the top level of your project's folder structure along with your package. json file.

Is it mandatory to use a configuration file when setting up a webpack project?

Out of the box, webpack won't require you to use a configuration file. However, it will assume the entry point of your project is src/index. js and will output the result in dist/main.

What is externals in webpack config?

Webpack externals tell Webpack to exclude a certain import from the bundle. Often externals are used to exclude imports that will be loaded via CDN. For example, suppose you are implementing server-side rendering with Vue and Express, but your client-side code imports Vue via a CDN.

What is webpack configuration file?

Webpack configs allow you to configure and extend Webpack's basic functionality. A Webpack config is a JavaScript object that configures one of Webpack's options. Most projects define their Webpack config in a top-level webpack. config. js file, although you can also pass the config as a parameter to Webpack's Node.


1 Answers

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'))
},
like image 69
Petr Bela Avatar answered Nov 15 '22 13:11

Petr Bela