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?
You have two options.
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>
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}