国产轻量前端框架介绍对比

1,980 阅读1分钟

说到前端框架,最为我们熟知的便是jQuery, Angular, React和Vue。不过近些年也冒出一些新兴国产轻量级前端框架,非常适合在个人小型项目中尝试使用。让我们一起来了解一下这些后起之秀吧

petite-vue

作为Vue官方的新作,petite-vue自然备受瞩目。它的特点有:

  • 6KB
  • 与Vue兼容的模板语法
  • 基于DOM原地修改(无VDOM)
  • 由与Vue相同的@vue/reactivity驱动
  • 无需编译 使用示例:
<script src="https://unpkg.com/petite-vue" defer init></script>

<!-- anywhere on the page -->
<div v-scope="{ count: 0 }">
  {{ count }}
  <button @click="count++">inc</button>
</div>

Lightue

听名字就知道这是一款启发自Vue的轻量前端框架。特点有:

  • <2.5KB
  • 状态驱动DOM自动更新
  • JS函数风格(v1.x,v0.x为对象风格)模板,良好的编辑器原生js支持
  • 有VDOM但无需Diff
  • 无需编译

使用示例:

<script src="https://unpkg.com/lightue@1.0.0-beta-1/dist/lightue.min.js"></script>
<script>
var L = Lightue, S = L.useState({
  count: 0,
}), {div, button} = L

var vm = L(
  div.count(S.$count),
  button.changeCount(
    {onclick: () => S.count++},
    'count++'
  )
)
</script>

Fre

这是一款类React的轻量级框架。特点有:

  • <2.5KB
  • 与React相同的API
  • 并发模式(时间分片)
  • 支持树抖,项目可小至1KB 使用示例:
import { render, useState } from 'fre'

function App() {
  const [count, setCount] = useState(0)
  return <>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>+</button>
    </>
}

render(<App/>, document.body)

Yox

这是一款体积稍大的轻量级框架,但是兼容性最好:

  • <13.5KB(standard), <25.5KB(legacy)
  • 可支持到IE6
  • Mustache语法模板 使用示例:
<script src="https://unpkg.com/yox"></script>
<div id='app'></div>
<script id="template" type="text/plain">
  <div>
    {{count}} <br>
    <button on-click="inc"> count++ </button>
  </div>
</script>
<script>
  new Yox({
    el: '#app',
    template: '#template',
    data: {
      count: 0
    },
    events: {
      inc: function() {
        this.set('count', this.get('count') + 1);
      }
    }
  })
</script>

[Strve.js](Strve.js | A approachable, fast, flexible and lightweight JavaScript library (strvejs.github.io))

Strve.js是一款充分利用了ES6模板字符串的前端框架。特点有:

  • <5KB
  • ES6模板字符串式模板
  • 灵活操纵代码块
  • 无需编译 使用示例:
<div id="app"></div>
<script type="module">
  import {
    h,
    createApp,
    setData,
  } from 'https://unpkg.com/strve-js@5.6.2/dist/strve.full-esm.prod.js';
  const state = {
    count: 0,
  };

  function App() {
    return h`
<h1 $key>${state.count}</h1>
<button onClick=${add}>Add</button>
`;
  }

  function add() {
    setData(() => {
      state.count++;
    });
  }
  const app = createApp(App);
  app.mount('#app');
</script>

总结

可以看出框架虽多,但每款都有自己的特点和适用场景。如果需要一款即插即用无需编译的框架的话,可以选择petite-vue, Lightue或Strve.js,它们分别使用原地更新、js函数、es6模板字符串来生成处理模板。如果喜欢jsx和React写法可以选择Fre。如果追求兼容性,那就选择Yox。