在学习和使用 Fable + Elmish 一段时间以后,对 Elm 架构有了更具体的了解, 和预料中的同样,Redux 这种来自 Elm 的风格果真仍是和强类型的 Meta Language 语言更搭,只有一个字: 爽。 可是呢,Fable 毕竟是一个小众语言,使用的 F# 语法并且仍是来自“万恶”的微软,开发环境还须要依赖 dotnet, 就这几点恐怕在公司的一些正式项目中推行恐怕有些难度。react
恰好最近须要作一个答题小游戏的应用,不想再上 React + Redux 全家桶了,一是体积太大,二是不管配置仍是写起来都太繁琐。突然发现 hyperapp 让我眼前一亮,简洁的架构,elm 风格, 1kb 的体积,丰富的生态,简直小应用神器! 可是呢,在实际使用中就发现,hyperapp 破坏性更新太多,致使不少第三方库,好比 persist, Redux Devtools, hmr 都不能用了,虽然这些库实现都不复杂,可是一个个改太麻烦了,又不想要老版本,干脆了本身从新造了个轮子 -- Hydux.git
Hydux 的语法和 hyperapp 差很少,抽离了 view 层,特色是 内置了 热更新,logger, Redux Devtools 和 persist,依然是 1kb大小 (gzip, 不包括开发环境),真正的一站式解决方案!github
view 层内置了 1kb 的 picodom, 同时也有官方支持的 React 扩展 使用 React 来渲染.redux
说了这么多,仍是上点代码: 首先咱们有一个 counter 模块,代码和 Elm 的组织方式很相似,不须要想 Redux 在 Actions/Reducers/ActionTypes 中跳来跳去的promise
1 // Counter.js 2 export default { 3 init: () => ({ count: 1 }), // 初始化状态 4 actions: { // actions 改变状态 5 down: () => state => ({ count: state.count - 1 }), 6 up: () => state => ({ count: state.count + 1 }) 7 }, 8 view: (state: State) => (actions: Actions) => // view 9 <div> 10 <h1>{state.count}</h1> 11 <button onclick={actions.down}>–</button> 12 <button onclick={actions.up}>+</button> 13 </div> 14 }
而后呢,咱们能够像 Elm 同样 复用 模块, 之前在用 Redux 时老是会面临不知道怎么复用才好的问题,而实际上 Elm 的复用是超级简单和方便的。架构
1 import _app from 'hydux' 2 import withPersist from 'hydux/lib/enhancers/persist' 3 import withPicodom, { h, React } from 'hydux/lib/enhancers/picodom-render' 4 import Counter from './counter' 5 6 // let app = withPersist<State, Actions>({ 7 // key: 'my-counter-app/v1' 8 // })(_app) 9 10 // use built-in 1kb picodom to render the view. 11 let app = withPicodom()(_app) 12 13 if (process.env.NODE_ENV === 'development') { 14 // built-in dev tools, without pain. 15 const devTools = require('hydux/lib/enhancers/devtools').default 16 const logger = require('hydux/lib/enhancers/logger').default 17 const hmr = require('hydux/lib/enhancers/hmr').default 18 app = logger()(app) // 内置的 logger 19 app = devTools()(app) // 内置的 Redux Devtools 扩展支持 20 app = hmr()(app) // 内置的热更新模块 21 } 22 23 const actions = { 24 counter1: Counter.actions, 25 counter2: Counter.actions, 26 } 27 28 const state = { 29 counter1: Counter.init(), 30 counter2: Counter.init(), 31 } 32 33 const view = (state: State) => (actions: Actions) => 34 <main> 35 <h1>Counter1:</h1> 36 {Counter.view(state.counter1)(actions.counter1)} 37 <h1>Counter2:</h1> 38 {Counter.view(state.counter2)(actions.counter2)} 39 </main> 40 41 export default app({ 42 init: () => state, 43 actions, 44 view, 45 })
而后就能够了!简单,可控,无痛的开发环境和代码组织。app
在线 demodom
异步使用的是相似 Elm 的反作用管理器风格, actions 能够是彻底纯的函数,也能够是直接返回一个 promise: https://github.com/hydux/hydux#actions-with-cmd异步
官网: https://github.com/hydux/hydux 函数
官方支持的 React 扩展: https://github.com/hydux/hydux-react