Libary components, Option to include JSON

Hi, when creating a library component you have the option to bundle any js, css, image files etc into the component; would it possible to have the option to include any JSON files also?

Kind Regards

JSON file already supported, btw :")

or you mean, add json when create custom component?

Hi,

Yes; it would allow you to create interesting custom coded components.

When you add a component to your library, the files you include get renamed to match the name of the component. So if you name your component “my Component” and include data.json, the file inside the component will end up being called my-component-data.json. That means your JavaScript won’t be able to fetch it properly because the name has changed.

That’s why the program doesn’t let you include JSON files when adding a component. Same thing with .mjs files — you can’t import one into another because the names get changed too.

But in your case, instead of trying to include a JSON file, you can just put the data directly into a JavaScript file, like json.js, for example:

window.data = [
  {
    id: 1,
    name: 'A name'
  }
];

No need to fetch the JSON — you can just use it right away.
Just make sure that json.js is loaded before any scripts that use the data, so keep an eye on the order of your JavaScript files!

2 Likes

@kuligaposten thanks for taking the time to explain how it works under the hood, and to provide a nice example! :wink:

1 Like