Search code examples
javascriptsvelteviteidentifierwebflow

Variables conflicting - my Svelte + Vite + Webflow approach is wrong?


I'm using Vite to build three .js files using Svelte. Then I host the three .js files on different Vercel urls. Then I use all 3 of them on 1 webflow page eg:

<div id="address"></div>
<script src="https://xyz.vercel.app/assets/index-4c8f4240.js"></script>
<div id="signup"></div>
<script src="https://abc.vercel.app/assets/index-d0bf5b05.js"></script>
<div id="button"></div>
<script src="https://def.vercel.app/assets/index-hk98hkh9.js"></script>

eg the script looks for the address div and injects the html. Only the first of my three .js files ever works, whichever one is higher on the page. The subsequent scripts don't inject the html and the console shows an error like this:

software-business-case-guide:571  Uncaught SyntaxError: Identifier 'x' has already been declared (at software-business-case-guide:571:9)
index-4c8f4240.js:1  Uncaught SyntaxError: Identifier 'p' has already been declared (at index-4c8f4240.js:1:1)

It sounds like variables are conflicting? I'm guessing I have to build all 3 svelte scripts into one .js file so it builds something that doesn't conflict? But this sounds like a nightmare as I'll have a seperate script for each combination of things I want on the page.

Is there not a way to get the variable to be contained within their own functions so I can use only the scripts I need on each page?

Thanks in advance, I'm super new at this, and I'm thinking there must be a better way to do this than how I'm doing it!

Edit, here's the vite.config.ts file:

import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [svelte()],
})

Here's some of the scripts: https://cledara-address.vercel.app/assets/index-4c8f4240.js https://cledara-blogsignup2.vercel.app/assets/index-d0bf5b05.js


Solution

  • The scripts are modules, so there are a lot of variables declared at the top level. It may look like everything is wrapped at first glance but that is not the case.

    You can either change the build options to output something like UMD or IIFE, e.g. using library mode, or just reference the scripts as modules:

    <script type="module" src"..."/>
    

    That way the global scope is not modified.