近年来,冒出大量 MVVM 框架,但它几乎无一例外依赖于 babel, webpack 等编译或手脚架,这让小公司出身的前端们望洋兴叹。因此小城市的前端们,没有高手带着,许多培训班出身,或自学成才转行,如果引用 react, ng2 这类框架无异于自杀。出问题,webpack 配置问 N 个群都没有问题。依赖于编译的框架也很难调试。
而我们公司则出于另一个目的开发这个框架,手机端需要体积更少的框架。学习了 preact, react-lite,我造出了这个类 React 框架。
此外,它还有一个好处,它是面向未来的。它所依赖的高级语法,都是可以通过简单的 pollfill 来修复。而 JSX,则依赖于 babel。anu 将 JSX 改造成字符串,三年后,http2 流行了,不需要打包,没有体积的压力。我们就没有维护一个破旧的 webpack 的压力。因此这是一个很轻量的框架,回复到 jQuery 时代,简单直接用页面引用 JS 主文件就行,其余的交由 es6 modules 来管理。
由于它与 React 极其相似,因此 React 生态圈的东西简单改造一下便能用了。
下面是一个例子,用于三个文件。以后可能会考虑合成一个。
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width">
- <script src='./dist/jsx-parser.js'>
- </script>
- <script src='./dist/evalJSX.js'>
- </script>
- <script src='./dist/anu.js'>
- </script>
- <script>
- class Hello extends anu.Component {
- constructor() {
- super() //Must write, or throw ReferenceError: |this| used uninitialized in Hello class constructor
- this.handleClick = this.handleClick.bind(this)
- }
- componentWillMount() {
- console.log('准备插入DOM树')
- }
- componentDidMount() {
- console.log('已经插入DOM树')
- }
- handleClick() {
- this.setState({
- title: new Date - 0,
- child: new Date - 1
- })
- }
- static className() {
- return 'Point';
- }
- render() {
- return evalJSX(` < div tilte = {
- this.state.title
- }
- onClick = {
- this.handleClick
- } > {
- this.state.child || "点我"
- } < /div>`, {
- this: this
- })
- }
- }
- function main() {
- return evalJSX(`<h2>对象使用anu<br / > <Hello / ></h2>`, {
- Hello: Hello
- })
- }
- window.onload = function() {
- var result = anu.render(main(), document.body)
- console.log(result)
- }
- /
- </script>
- </head>
- <body>
- <div>
- 这个默认会被清掉
- </div>
- </body>
- </html>
目前定义组件时是用 es6 方式,如果你想支持 IE8 等老旧浏览器,也可以用 createClass 来定义类。
目前 anu 是支持 React 的多种定义组件方式,包括 Stateless Component, InPure Component, Pure Component。
如果你想减少改动,继续用 React 命名,可以做以下处理:
- var React = window.anu evalJSX.globalNs = "React"。
- var myComponent = React.createClass({
- getDefaultProps() {
- return {
- children: "xxxx"
- }
- }
- render() {
- return evalJSX("<div>{this.props.children}</div>", {
- this.this
- })
- }
- })
基本上我是朝着 100% 模仿 React 来打造它,但一些过旧的官方不推荐的功能,我也像 React 那样做成插件。
目前没有支持的方法与对象
更多介绍可见它的 GITHUB homepage
欢迎加星星与试用
来源: http://www.tuicool.com/articles/vEBrEra