Embed Our Svelte Calculator Component into Your Existing Website

demo page of embedded components

If you have followed the instruction in my previous post, you now have five tabs in Svelte’s REPL labeled App.svelte, Calculator.svelte, Calcbtn.svelte, Display.svelte, and stores.js. (If you do not have these, you can pull them from my Github repository in the svelte-app directory).

Click on the Download icon on the gray bar near the top of the REPL page, and a Zip file will be put in your downloads folder. Unzip this file, and open the src directory. That will contain your five source files plus a main.js file, which you can delete. You can also delete App.svelte. Move the four remaining files into a directory where you will do this embedding project and cd into that directory.

You will need npm to install the software tools needed for this project. If you don’t already have it, or are unsure, instructions for downloading and installing it are found here.

Now we’re ready to start building the .js file for our calculator component that can be imported into conventional web pages. I offer appreciation to Code and Life for the technique used here, also described here.

Rollup is a module bundler used to compile chunks of JavaScript into a library or application. It is used by Svelte to do the build, so you need to install it (if you haven’t already). Do that by entering the following line at your terminal:

npm install --save-dev rollup

This installs it and marks it as a development dependency. Next, enter
npm init

This will ask you several questions, which you can answer or just hit return to accept defaults. This step will generate a package.json file. Next, we’ll install Svelte and two rollup plugins:

npm install --save-dev svelte
npm install --save-dev rollup-plugin-svelte
npm install --save-dev @rollup/plugin-node-resolve

Now we are ready to create a small JavaScript file that will import our Calculator component and inject it into the webpage where we want it to be displayed. We’ll call it embed.js. Here’s the code:

import Calculator from "./Calculator.svelte";

var div = document.createElement("div");
var script = document.currentScript;
script.parentNode.insertBefore(div, script);

const embed = new Calculator({
  target: div,
  props: { calcFontSize: calcFontSize },
});

In order to run rollup, we will give it a config file so it knows what we want it to do. Create a file called rollup.config.js, and enter the following code into it:

import svelte from "rollup-plugin-svelte";
import resolve from "@rollup/plugin-node-resolve";

export default {
  input: "embed.js",
  output: {
    format: "iife",
    file: "calc.js",
    sourcemap: false,
  },
  plugins: [
    svelte({ emitCss: false }),
    resolve({ browser: true, dedupe: ["svelte"] }),
  ],
};

The output file (calc.js) is what we will invoke in our HTML program to produce our component. The output format of “iife” stands for immediately-invoked function expression. You can learn more about Rollup configuration files (and other features) here.

Now we’re ready to run rollup, passing it our configuration file:

rollup -c rollup.config.js

This should give you a message like created calc.js in 465ms.

Next, we’ll create a simple HTML page into which we will import two Calculator instances of different sizes, as a stand-in for your own web page where you want to import a Svelte component. It doesn’t need to be in the same directory as our embed code, but we’ll put it there for convenience right now:

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>Demo page</title>
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <style>
      body {
        margin: 3em;
      }
      p {
        color: green;
      }
    </style>
    </head>
  <body>
    <h1>Svelte Embedding Demo</h1>
    <p>
      Below, we have inserted a <code>script</code> tag that should render a
      Svelte Calculator component upon loading this page. Its font size is set
      to 10px.
    </p>

    <script>
      calcFontSize = "10px";
    </script>
    <script src="calc.js"></script>
    <p>Below this line is a Calculator with font size of 16px.</p>
    <script>
      calcFontSize = "16px";
      </script>
    <script src="calc.js"></script>

    <p>This text will come after the embedded content.</p>
</body>
</html>

As you see, we invoke our component with the line

<script src="calc.js"></script>

and we can set the (global, in this case, for simplicity) variable calcFontSize to be passed through as a prop to the component.

At this point, we’re ready to try it out! Double-click on the file demo.html that you created, and check it out. It should look like the screenshot at the top of this page. Congratulation! You have embedded a Svelte component into a standard HTML page.