DEV Community

Shriji
Shriji

Posted on

Svelte: change API URLs during Development and Build

This is a frequent question that is asked how to detect whether the environment is either development or production also this is significantly helpful when apps are being frequently published and the client-side app needs API that may be different URL for local/development and during production builds.

Solution

Svelte's most adopted bundler is Rollup and the default rollup plugin config looks like this


    plugins: [
        svelte({
            dev: !production,
            css: css => {
                css.write('bundle.css');
            },
            preprocess: sveltePreprocess(),
        }),
        resolve({
            browser: true,
            dedupe: ['svelte']
        }),
        commonjs(),
        typescript({
            sourceMap: !production,
            inlineSources: !production
        }),
        !production && serve(),
        !production && livereload('public'),
        production && terser()
    ],
Enter fullscreen mode Exit fullscreen mode
I have stripped out the comments

We need to add @rollup/plugin-replace as a dev dependency.

npm i -D @rollup/plugin-replace
Enter fullscreen mode Exit fullscreen mode

General usage and more info check out the github

Now, this plugin is going to look for occurrence(s) of MYURL and destructively replace it. So consider having an unique string to be replaced.

For easier explanation here is a quick example.

import replace from 'rollup-plugin-replace';

export default {
    // ...
    plugins: [
        replace({
        'MYURL':production?'http://myhost:3000':'http://localhost:3000'
        })
    ]
};
Enter fullscreen mode Exit fullscreen mode

Example App.svelte


<script>
  let url = "MYURL";
  let api = "/myendpoint";
  url += api;

//your normal fetch logic.

/* async function fetchData() {
        const response = await fetch(url)
        result = await response.json()
        return result
}
*/
</script>

<!--
check URL using your template to verify 
when your svelte app is run in dev mode your URL will be http://localhost:3000/myendpoint
when your svelte app is served after the build (production) your URL will be http://myhost:3000/myendpoint
-->


<p> {url} <p> 

<!-- template logic
{#await fetchData()}
   ...
{/await}
-->

Enter fullscreen mode Exit fullscreen mode

Advantage of letting rollup replace the URLs.

Good news, we are not exposing the dev and prod API endpoints on the client-side app. We are leveraging the capabilities of rollup during the build process this makes sure that you not only have the URLs securely in your .env and has only one file you need to change the base URLs. Take a look here how to identify dev or prod the article also achieves using rollup-plugin-replace

Top comments (2)

Collapse
 
pavelloz profile image
Paweł Kowalski

Nice :)
That is one of those things that you just need to know if you are serious :)

Do you found a method of pulling dynamically url to CDN during runtime? Similar to webpack-require-from?

Collapse
 
shriji profile image
Shriji

Ah, this is very neat. Thank you for pointing me this and reading my article :)

For the answer, if there is a method to dynamically pull URL can be handled by async-script-loader using a small logic. But this isn't a clear equivalent of webpack-require-from.