'How can I address a Netlify function with Svelte?

I have written a vanilla html app to test a Netlify function and it works

I have attempted to write a Svelte application to mimic the same functionality

The two versions have fundamentally the same directory structure, but replace App.svelte with index.html

In the Svelte version I get a 404 error when I try to access hello.js. I assume that I am not giving the correct path to the function in Svelte, but what should it be?

.
├── netlify
│   └── functions
│       └── hello.js
├── netlify.toml
├── package.json
├── package-lock.json
├── public
│   ├── build
│   │   ├── bundle.css
│   │   ├── bundle.js
│   │   └── bundle.js.map
│   ├── favicon.png
│   ├── global.css
│   └── index.html
├── README.md
├── rollup.config.js
├── scripts
│   └── setupTypeScript.js
└── src
    ├── App.svelte
    └── main.js

I have run the following scripts in the base directory

npm install netlify-cli netlify-lambda

and

netlify link

package.json

{
"name": "svelte-app",
"version": "1.0.0",
"private": true,
"scripts": {
    "build": "rollup -c",
    "dev": "rollup -c -w",
    "start": "sirv public --no-clear"
},
"devDependencies": {
    "@rollup/plugin-commonjs": "^17.0.0",
    "@rollup/plugin-node-resolve": "^11.0.0",
    "rollup": "^2.3.4",
    "rollup-plugin-css-only": "^3.1.0",
    "rollup-plugin-livereload": "^2.0.0",
    "rollup-plugin-svelte": "^7.0.0",
    "rollup-plugin-terser": "^7.0.0",
    "svelte": "^3.0.0"
},
"dependencies": {
    "netlify-cli": "^10.3.0",
    "netlify-lambda": "^2.0.15",
    "sirv-cli": "^2.0.0"
}
}

netlify.toml

[dev]
publish = "src"

App.svelte

<main>
    <h1>Netlify/Svelte</h1>

    <p>function result: <span id="function-result"></span></p>
</main>

<script>
    async function callHello() {
        const url = `/.netlify/functions/hello`;

        try {
            const response = await fetch(url);
            const data = await response.json();

            console.log('Data returned by function:', data)
            let display = document.getElementById('function-result')
            display.innerText = data
            return data;
        } catch (err) {
            console.log(err);
        }
    }
    callHello()
</script>

netlify/functions/hello.js

exports.handler = async (event, context) => {
    return {
        statusCode: 200,
        body: JSON.stringify('Hola Mundo')
    }
}


Solution 1:[1]

There seems to be a problem with the version of sirv-cli in my package.json which stops the Netlify server starting correctly

It should read

"dependencies": {
    ...
    "sirv-cli": "^1.0.11"
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Psionman