Bundle JSON as a simple JSON file with Webpack

I have a web application that requires a JSON configuration file that contains endpoints and other required startup parameters.

If I use json-loader, the file is not โ€œreal jsonโ€, it will look something like this:

module.exports = { "name": "foo", "key": true, }; 

What I would like is simple old JSON, which means that it can be parsed and modified as part of the deployment process before being sent to the web server where it will be served.

An alternative is to use a file loader. However, this means that (although this is a trivial task), I have to write the code to upload the file myself. I would like webpack to handle this and be available.

Is there a way that I can require to create a JSON file that is written as a regular JSON file and imported at runtime?

+7
json javascript webpack
source share
2 answers

Is there a way that I can require to create a JSON file that is written as a plain old JSON file and imported at runtime?

Webpack is valid at compile time. This means that when you need a file, it downloads the file, performs the changes indicated by the chain of loaders, and exports the final result from this chain. So you are asking to sound like a bootloader that acts like a file loader but exports an IIFE that returns a promise for the desired file.

In theory, it is possible to have a webpack loader, say, an async-file-loader, which receives input from a file loader, will handle the async request for you. Suppose something like:

 const promisedFile = require('async-file-loader!file-loader!./myJson.json'); promisedFile.then(file => { console.log(JSON.parse(file)); }); 

But then all the logic of request processing will be limited inside this call. An asynchronous file loader will look something like this:

 module.exports = function(source) { return `module.exports = eval("(function(url){ /* define async request func, preform request and return promise in here */ })(${url})")`; } 

Pretty nasty ...

When you want to load a json file at runtime, I will see 2 options:

  • use the loader file and request the json file asynchronously yourself.
  • use the server-side scripting language and paste the configuration into the .html file. If you use nodejs and express, for example, on your side, you can easily insert the configuration using Cheerio before submitting the request.
+1
source share

As ShabbY said above, Webpack is a modular module and compiles your files ahead of time.

It looks like you need to add a configuration file (json) after the build time for access at run time. To do this, the solution would be to upload the file using a regular ajax call, rather than trying to link it to Webpack.

+1
source share

All Articles