How to setup .env variables to your Svelte JS app
Most of the time writing apps required configuration variables based on environments like local, QA, stage, and production.
In Svelte JS we can use node modules dotenv and @rollup/plugin-replace to get the environment variables on client-side code.
Let see the implementations as step by step
Step 1: Install the following node modules as a dev dependency
npm install --save-dev dotenv @rollup/plugin-replace
Step 2: Add .env file into your project root
Our .env file should look like this
API_URL= https://api-local.yourdomain.com/v1
API_CLIENT_KEY= 2314233453451232
API_REGION= EU
Step 3: Update the rollup.config.js file
import the node modules (dotenv, @rollup/plugin-replace)
Here is the rollup.config.js file
Adding replace() inside plugins. It is used to find the defined properties, and replace them into the value at compile time.
So we parsed the dotenv config() variables as JSON.stringify() object inside replace().
If we don't want to parse all the declared variables in the .env file, we can use required ones like
//replace() for specific variable import__myapp: JSON.stringify({
env: {
isProd: production,
API_URL : process.env.API_URL //only using API_URL
}
})
Step 4: Access the variables inside Svelte components
//App.svelte<script>
const isProd = __myapp.env.isProd
const apiUrl = __myapp.env.API_URL
</script><h4>{isProd} - {apiUrl}</h4>
Now we can access all the environment variable as if it was a global variable inside our Svelte component.
Dev Note: This technique can be only used the application run completely on the client-side. It is not a recommended approach for Sapper or app running in the server with hydratable options.
Check out my other Svelte JS articles if you like.
Conclusion
Consider this way we can add environment-specific client-side variables into our awesome Svelte JS app.