How to access local json file via svelte?

Viewed 9228

For now I use onMount async function to access

const dataAPI = './jsfwperf.json';
let data = [];

onMount(async () => {
    const res = await fetch(dataAPI)
    .then(res => res.json())
    .then(data => {
        console.log(data)
    })
    .catch(err => console.error(err));
});

But in terminal it shows that file is missing

bundles src/main.js → public\build\bundle.js...
[!] Error: Unexpected token (Note that you need @rollup/plugin-json to import JSON files)

File location is the same as app.svelte that I used. How can I proper access local json file via svelte?

2 Answers

In command line :

cd yourproject
npm install @rollup/plugin-json --save-dev

Edit the rollup.config.js file:

// add at the beginning of the file :
import json from '@rollup/plugin-json'

//...

// under the plugin line :
plugins: [
  json({
    compact: true
  }),

//...

In your svelte component :

<script>
import * as myjson from './test.json'
</script>

<p>{myjson.mykey}</p>
<script>
    import item from 'path/to/data.json';
</script>
Related