Svelte is a new way to build Web applications. It hasn’t been a big hit since its launch. It hasn’t followed Angular, React, and VUE as the fourth largest framework, but it hasn’t lost any traction either. One reason this is important is that Svelte’s core idea is that it can be developed like React and VUE, but without the virtual DOM. Svelte can compile code into small, framework-independent JS code.

It seems to be full of advantages, but because it is too flexible to write highly consistent business code, these advantages are not reflected in actual large projects.

Svelte’s framework isn’t perfect, but it didn’t die in the cut-throat market because it has a special secret book of features that make it an irreplaceable member of other frameworks.

For Svelte, the secret is simply called Web Components.

In large multi-team projects, teams may use different versions of the framework, or even different frameworks, making it difficult to reuse components from project to project.” “Write one, run anywhere” is just empty talk. In this case, Svelte becomes a bridge to bridge the framework gap. The frame-free Web Components developed with Svelte can be reused across frameworks. At the same time, Svelte development is not as tedious as writing Pure JS.

Using SpreadJS integration as an example, here is how to develop a Spread-Sheets Web Component using Svelte for reuse by other pages.

  1. Create the Svelte Template project.

Svelte officially provides the Template project, just clone or download the project.

Github.com/sveltejs/co…

npx degit sveltejs/component-template my-new-component
cd my-new-component
npm install # or yarn

Copy the code
  1. Modify rollup.config.js to add the customElement: true configuration and output it as a Web Component.

The added rollup.config.js is as follows.

import svelte from 'rollup-plugin-svelte';
import resolve from '@rollup/plugin-node-resolve';
import pkg from './package.json';

const name = pkg.name
        .replace(/^(@\S+\/)?(svelte-)?(\S+)/, '$3')
        .replace(/^\w/, m => m.toUpperCase())
        .replace(/-\w/g, m => m[1].toUpperCase());

export default {
        input: 'src/index.js',
        output: [
                { file: pkg.module, 'format': 'es' },
                { file: pkg.main, 'format': 'umd', name }
        ],
        plugins: [
                svelte({
                        customElement: true,
                }),
                resolve()
        ],
};

Copy the code
  1. Update SRC/component. svelte to create a spread-sheets Component.
<svelte:options tag="spread-sheets" />
<script>
    import { createEventDispatcher, onMount } from 'svelte';
    // Event handling
    const dispatch = createEventDispatcher();
    export let value ="";
    $: valueChanged(value);
    function valueChanged(newValue) {
      console.log("value changed", newValue);
      if(spread){
        let sheet = spread.getActiveSheet();
        sheet.setValue(0, 0, value);
      }
    }

    let spreadHost;
    let spread;
    function dispatchEvent(name, e) {
      // dispatch(name, e);
      const event = new CustomEvent(name, {
        detail: e,
        bubbles: true,
        cancelable: true,
        composed: true, // this line allows the event to leave the Shadow DOM
      });
      // console.log(event)
      spreadHost.dispatchEvent(event);
    }
      onMount(() => {
          spread = new GC.Spread.Sheets.Workbook(spreadHost);
          let sheet = spread.getActiveSheet();
          sheet.setValue(0, 0, value);
          spread.bind(GC.Spread.Sheets.Events.ValueChanged, function(s, e){
            e.evnetName = "ValueChanged";
            dispatchEvent("changed", e);
          });
          spread.bind(GC.Spread.Sheets.Events.RangeChanged, function(s, e){
            e.evnetName = "RangeChanged";
            dispatchEvent("changed", e);
          });
      });



  </script>
  <style>
      
  </style>
  <div bind:this={ spreadHost} style="width: 100%; height:100%"></div>

Copy the code

Now that our custom component is created, we just need to call NPM run Build to compile the spread-Sheets component.

  1. Reference components on the page.

Create an index.html page and reference the compiled JS file. Also introduce Spreadjs-related resources. Add SpreadJS directly using the spread-sheets TAB.

<! doctype html> <html lang="en"> <head> <meta name="spreadjs culture" content="zh-cn" /> <meta charset="utf-8" /> <title>My Counter</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="https://demo.grapecity.com.cn/spreadjs/SpreadJSTutorial/zh/purejs/node_modules/@grapecity/spread-sheets/styles/gc. spread.sheets.excel2013white.css"> </head> <body> <! -- <spread-sheets-designer></spread-sheets-designer> --> <button onclick="getJSON()">GetJSON</button> <spread-sheets value="123" style="display:block; width: 80%; height: 400px;" ></spread-sheets> <script SRC = "https://demo.grapecity.com.cn/SpreadJS/WebDesigner/lib/spreadjs/scripts/gc.spread.sheets.all.14.1.3.min.js" type="text/javascript"></script> <script type="text/javascript" src="/dist/index.js"></script> <script type="text/javascript"> document.querySelector("spread-sheets").addEventListener("changed", function(){ console.log(arguments) }) window.onload = function(){ document.querySelector("spread-sheets").setAttribute("value", "234"); } </script> </body> </html>Copy the code

The effect after addition is shown below.

conclusion

Although Web Components seem to solve the problem of reuse between components perfectly, Web Components developed with Svelte have some limitations: for example, they can only pass string attributes; Attribute binding is one-way binding. To obtain internal updated values of components, bind events to obtain them.

If you have more interest in Svelte, please leave a comment