2

I'm building a Chrome extension in Svelte using this boilerplate repo but I'm not sure how to render a Svelte component onto a webpage.

So far I've tried importing the Svelte component into the content script

// src/pages/content/index.ts
import PriceCard from 'src/components/PriceCard.svelte'

const root = document.createElement('div')
const anchor = document.querySelector('.game_area_purchase_game_wrapper')
anchor.insertAdjacentElement('beforebegin', root)   

const priceCard = new PriceCard({
     target: root
 })

export default priceCard

But I get this error: Uncaught SyntaxError: Cannot use import statement outside a module

For reference this is the Svelte component

// src/components/PriceCard.svelte
<script lang='ts'>
    let name = 'Joe Bob'
</script>

<main>
     <h1>Welcome {name} !</h1>
</main>

The config files (manifest.json vite.config.ts, etc) were not altered. I'm using whatever the boilerplate came with.

0pH
  • 21
  • 1
  • Either find a way to build the entry as a normal script, not a module, or use a `web_accessible_resources` iframe element, [see the inside of `func` here](https://stackoverflow.com/a/70870192). – wOxxOm Jul 30 '22 at 05:26
  • I got it to work, but now I have a new problem. So I messed around with the `vite.config.ts` and isolated the entry file of the content script. I added `format: 'iife'` to `rollupOptions.output` but now I have to have different output formats for each entry file (background script, options, etc). – 0pH Aug 01 '22 at 03:43
  • @0pH how did you get it to work? Did you figure out how to build as a normal script (without module) or did you take the iframe approach? – freb Oct 19 '22 at 23:47
  • @freb I made two `vite.config.ts` files. One config builds only the content script, and the other builds the rest of the extension (`background`, `options`, etc). While not ideal, I build both configs at the same time in two terminals and work with that. – 0pH Oct 21 '22 at 00:21
  • @0pH, thanks for the response. I ended up opening an issue in the boilerplate repo and the owner responded with a pretty good rollup config if you're interested: https://github.com/NekitCorp/chrome-extension-svelte-typescript-boilerplate/issues/7 – freb Oct 21 '22 at 18:44

0 Answers0