官术网_书友最值得收藏!

Syntactic modules

Let's look at another way of creating modules in Reason: syntactic modules. These are modules that are defined using Reason's module syntax. Here's an example:

/* src/Ch03/Ch03_Domain.re */
module Person = {
type t = {id: int, name: string};
let make(id, name) = {id, name};
};

module Company = {
type t = {id: int, name: string, employees: list(Person.t)};
};

Here we define a Domain file module to contain two nested modules: Person and Company. These nested modules actually contain types similar to the ones we defined in src/Ch02/Ch02_Demo.re, but this time with both types named t.

Let's digress a little into the type name  t. This is a standard naming convention in the Reason ecosystem to mean the main type in the module. Usually, you refer to a module along with its main type, for example,  Person.t or Company.t, so it's quite clear exactly which type you mean.

Syntactic modules have the following form: module Name = {...bindings...}; and all the bindings are then available to outside consumers under the module name, for example, Name.binding1, and so on.

Earlier, we said that modules package types and values together. But in the preceding example, you can see that the Ch03_Domain file module itself contains two modules, Person and Company. I actually oversimplified before. Modules can recursively contain other modules! This is a great code organization and namespacing strategy.

Let's look at the (relevant part of the) JavaScript output to understand what the runtime effect of this domain module is:

// src/Ch03/Ch03_Domain.bs.js
function make(id, name) { return [id, name]; }

var Person = [make];
var Company = [];
exports.Person = Person;
exports.Company = Company;

The Person and Company modules are represented as JavaScript arrays, and their t types are completely erased, leaving the arrays almost empty. The arrays contain only what file-level module JavaScript output would contain: values. In fact, this is almost exactly how Reason represents modules when compiled to bytecode or native binary form.

It is not, however, how you might expect a nested module to look in idiomatic JavaScript. Indeed, the BuckleScript compiler does not always emit completely idiomatic JavaScript output. Some of those cases can be fixed (indeed, some have already been); others are compromises that the compiler needs to make to efficiently convert Reason code into JavaScript.
主站蜘蛛池模板: 安龙县| 淮南市| 绥宁县| 宁明县| 法库县| 晋宁县| 堆龙德庆县| 阜新市| 岑溪市| 郓城县| 芜湖市| 玛纳斯县| 改则县| 镇赉县| 宿迁市| 阿克苏市| 西充县| 金坛市| 共和县| 黑龙江省| 图木舒克市| 都匀市| 嘉义市| 曲阜市| 西城区| 河曲县| 铅山县| 蒲江县| 武汉市| 丹巴县| 南溪县| 定安县| 尼玛县| 大港区| 南开区| 永靖县| 深州市| 九龙城区| 左云县| 东光县| 富源县|