How to load a JSON content inside a js module with Webpack
Hello all,
At first Webpack can give you an hard time but after that, it’s all sugar!
Imagine you need to include a JSON file used for configuration in your `example.js` file:
1. Install the loader module json-loader
:
npm install json-loader --save-dev
2. Add the loader to your webpack.config.js
file:
loaders: [
{ test: /\.json$/, loader: 'json' },
// other loaders
]
3. Add in your `example.js` file the following line:
import config from '../config.json';
…and your JSON is ready to be used in your code, already parsed into a sweet object.
Cool, isn’t it?
What Webpack does being the scenes is converting the JSON file into a JS module and adding it to your build result:
/* some-webpack-require-number */
/***/ function(module, exports) {
module.exports = {
// your json content
}
}
var config = __webpack_require__(some-webpack-require-number);
Thank you, Good job 🙂
Is the reverse of the above scenario possible i.e I have a Js module which exports JSON data. As the application has already been developed, so I can’t replace the module (can’t change the module to json). So what I want is whatever is being exported from my js module, I need that to be written to a JSON file.
Any suggestion or links would be helpful.
Thanks in Advance.