Svelte is a new method of building web applications. It has been tepid since its launch. It has not become the fourth largest framework after Angular, React and VUE, but it has not lost its popularity and no one cares about it. One of the important reasons for this situation is that Svelte's core idea is [to reduce the amount of code at runtime through static compilation]. It can be developed like React and VUE, but it does not have a virtual DOM. , So that Svelte can compile the code into small, framework-independent JS code.
It seems to be full of advantages, but because it is too flexible, everyone cannot write highly consistent business codes. The above advantages have not been well reflected in actual large projects.
Svelte framework is not perfect, but it did not die in the cruel market competition because it has a special secret book and some features that make it a member that other frameworks cannot replace. .
For Svelte , the name of this cheat is called-Web Components.
In a large project completed by multiple teams, each team may use different framework versions, or even different frameworks, which makes it difficult to reuse components between different projects. "write one, run anywhere" is just empty talk. In this case, Svelte has become a bridge to communicate across the framework gap. Web Components developed by Svelte without framework dependencies can be reused among various frameworks. At the same time, Svelte's development method is not as cumbersome as writing pure js.
Let's take SpreadJS integration as an example to introduce how to use Svelte to develop a spread-sheets Web Component for other pages to reuse.
- Create a Svelte template project.
Svelte officially provides a template project, just clone or download the project.
https://github.com/sveltejs/component-template
npx degit sveltejs/component-template my-new-component
cd my-new-component
npm install # or yarn
- Modify rollup.config.js, add customElement: true configuration, and output as 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()
],
};
- 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>
In this way, our custom component is created. Just call npm run build to compile the spread-sheets component.
- Reference components on the page.
Create an index.html page and reference the compiled js file. At the same time introduce spreadjs related resources.
Add SpreadJS directly using the spread-sheets tag.
<!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>
The effect after adding is as shown in the figure below.
Summarize
Although it seems that Web Component perfectly solves the reuse problem between components, the Web Component developed with Svelte also has some limitations: for example, only string attributes can be passed; the bound attribute is one-way binding, and you want to get the component The internal update value needs to be obtained by binding event.
If you are more interested in Svelte, welcome to leave a message~
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。