January 22, 2020
By: Kevin

Google Closure Libary的使用

  1. 介绍
  2. 库的使用
  3. import vs require
  4. 参考文档

介绍

花点时间在cljs上, 很快就知道cljs的编译({:optimizations :advanced }的时候), 有两步

  1. cljs->js(JVM完成)
  2. js->js优化编译(Google Closure)

第二步是由Google Closure完成, 负责整个程序的优化和混淆命名, 除去无用代码, 代码压缩, etc.

此外, Google Closure提供了丰富的函数库, 这些库在cljs的环境中已经包含, 可以自由使用. 其实很多的库都是这个库的简单封装:

|-----------------------+-------------------------------|
| ClojureScript wrapper | Closure Libraries             |
|-----------------------+-------------------------------|
| cljs-time             | goog.date                     |
| cljs-http             | goog.net, goog.uri            |
| cljs-ajax             | goog.net, goog.uri, goog.json |
| cuerdas               | goo--g.string                 |
|-----------------------+-------------------------------|

库的使用

closure libary是google前端的基础库, 功能可以说无所不包(加密, 网络通讯, UI, 矩阵计算...), 支持了google几乎所有的看家产品.

Closure Library is a powerful, low-level JavaScript library designed for building complex and scalable web applications. It is used by many Google web applications, such as Google Search, Gmail, Google Docs, Google+, Google Maps, and others.

这里列举以下我用过的

  1. goog.string.format, 参见的编码规范
  2. goog.math, 用于处理矩阵, 极坐标, 贝塞尔函数等
  3. goog.events, 用户用户事件处理, 可参见链接core.async中的用例

import vs require

EventType是这么引入的: (:import [goog.events EventType]), 觉得有点奇怪.

其实, clojure的namespace管理部分, 特别是ns宏相当混乱, :require :import :as :refer :refer-clojure :exclude :all use load.... 还好绝大多数概念都能很平滑的对应到cljs.

除了import, 在Clojure中是为了引入java的类, 在cljs它有什么用?

  1. 引入js的class, 按照官方文档:

This is only for when you would like to refer directly to a class which is also a namespace, otherwise just use :require in your ns form or use the require REPL helper.

  1. 引入js的Enum, EventType就是这个情况

其他情况都是import

参考文档

Tags: clojurescript