Home > Net >  Webpack, build one JSON file from multiple JSON files at build time
Webpack, build one JSON file from multiple JSON files at build time

Time:10-11

I have to build a landing page which when visited will check your User Agent and determine which device you are using and if you are using a device that is supported it will show some information for that device. The information that is shown does not matter that's done, checking User Agent is also done.

What is not done is this because I am stuck. I have directory structure like this:

-devices
 -nintendo
  config.json
 -xbox
  config.json
 -ps5
  config.json

and so on. So since I need to access these configs at runtime since I will not know which device the user is using until they land on the page, this cannot be determined at build time. So my thoughts are have a JS file that will loop through all of these folders and take each config and build one big config that will be a module in web pack that I can import in my main.js file so I can than just import it and access the properties using dot notation.

Can I do all of this with web pack and skip the JS file that will combine all of the config, or is there a better approach to this?

CodePudding user response:

You don't really need anything extra to achieve this. Assuming you have following directory structure:

- main.js
- devices
  - nintendo
    - config.json
  - xbox
    - config.json
  - ps5
    - config.json

All you have to do is to import individual JSONs in your main.js file:

import nintendo from './devices/nintendo/config.json';
import xbox from './devices/xbox/config.json';
import ps5 from './devices/ps5/config.json';


function main() {

  // Read `someDevice` at runtime

  if (someDevice === 'nintendo') {
    console.log(nintendo);
  }

}

If your json files are big and bundle size becomes a concern, then you can use dynamic imports along with async-await and Webpack will automatically split the bundle for you:

async function main() {

  if (someDevice === 'nintendo') {
    const nintendo = await import('./devices/nintendo/config.json');
  } else if (someDevice === 'xbox') {
    const xbox = await import('./devices/nintendo/config.json');
  } else {
    const ps5 = await import('./devices/ps5/config.json');
    
  }
}
  • Related