svelte - reading json file from local folder

Viewed 2300

My svelte app is required to read json file from the public folder. I followed exactly the rollup setup from this link, then add json to my app.svelte:

import * as port from '/port.json';

port.json is located at the public folder together with index.html. But I keep getting this error:

main.js:11 Uncaught ReferenceError: port is not defined at main.js:11

and I am getting this message from Terminal which I am not sure what it means:

(!) Missing global variable name Use output.globals to specify browser global variable names corresponding to external modules /port.json (guessing 'port')

How can I resolve this?

2 Answers

You have two options.

  1. Move the file to your src/ folder and bundle it with the rest of your application code using Rollup. This is where you need @rollup/plugin-json to bundle json files. You can then import it like so:
<script>
    import json from './port.json';
</script>

<p>{JSON.stringify(json)}</p>
  1. Keep the file in your public/ folder and retrieve it at runtime using fetch.
<script>
    let fetchJson = fetch('port.json').then(res => res.json());
</script>

{#await fetchJson}
    <p>Loading JSON</p>
{:then result}
    <p>{JSON.stringify(result)}</p>
{/await}

Export the object and rename the file from .json to .json.js.

port.json.js

export let myJson = {
    name: "hello world"
}

Component:

<script>
   import json from './port.json';
</script>

    
    <p>{JSON.stringify(json)}</p>
Related