用svelte.js开发web components

2,167 阅读2分钟

前言

最近有点闲,看到svelte.js,一个挺好玩的框架,搭配rollup开发相当丝滑,api就我而言,比vue、react那些都好用~

尤大说的比较中肯,它属于小而美的类型,构建复杂项目可能会有压力;

但用来做小项目,活动页,编译可独立分发的 web components等,则很合适。

今天我那它做个组件尝尝味道。

一、web components是什么?

其实这玩意就是自定义html组件,等于你创建了个video标签,并实现了标签内部的功能逻辑,可在多处复用。关于它的文档在这里,还有阮一峰的简单入门示例,可自行查阅。

二、使用步骤

1.起步

svelte.js 搭建项目,其实就装几个包,简单配置一下rollup就完事的了,没啥好说的。
官方也有提供了template工程,懒癌发作就clone或者下载项目即可。

npx degit sveltejs/component-template info-card
// or 直接下载
https://github.com/sveltejs/component-template

2.构建示例

<svelte:options tag="info-card" />
<div id="app" bind:this={self}>
  <h1 class="name">{name}</h1>
  <button on:click={sayMyName}>呼唤我的名字</button>
</div>

<script>
  export let name
  export let self
  function sayMyName() {
    alert(name)
    // 呼唤结束,你还可以自定义事件,冒泡向上层传递信息
    self.dispatchEvent(new CustomEvent('done', {
	  detail: 'anything'
	}))
  }
</script>

<style>
#app .name {
    color: red;
}
</style>

然后npm / yarn build一下,引入打包好的js,你就可以直接使用这个组件啦

// html
<info-card name="MO"><info-card/>
<script>
  // 监听事件
  document.querySelector('info-card').addEventListener('done', () => {
    // Do something
  })
</script>

3. 实际应用

在项目中使用还是很便利的,基本就是引入模块文件,插入自定义标签,通过属性传参即可

4.踩坑小点

用svelte.js开发web components,rollup.config.js配置要里写好customElement的配置。 

然而baidu的结果绝大多数是错的了,这里更正一下,不然打包会报错的。 

还有,rollup的模块机制是ESmodules,不支持require,import第三方插件时,需要用插件转换才能用,记得处理一下

// rollup.config.js
import svelte from 'rollup-plugin-svelte'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import babel from 'rollup-plugin-babel'
import { uglify } from 'rollup-plugin-uglify'
...
export default {
...
  plugins: [
    babel({
      babelrc: false,
      exclude: "node_modules/**",
      presets: [
        [
          '@babel/preset-env'
        ],
      ]
    }),
  	svelte({
	  compilerOptions: {
		customElement: true
	  }
	}),
	//(resolve要放在commonjs之前)
	resolve(),
	commonjs({
	  include: 'node_modules/**'
 	}),
	uglify()
  ]
}

另外,要注意web components的兼容性问题,要确定你的项目可用,再去尝试,不然是会gg的。

(数据来源:caniuse.com

总结

用svelte.js开发web components很般配,省却用原生编写的大量dom操作代码,响应式的框架和大量可选npm库,打包体积远小于用vue等流行框架,做到了轻量且实用的目的,值得一试~