Skip to content

Commit 381e430

Browse files
Copy module function guide to v12 docs
1 parent 7ced1f0 commit 381e430

File tree

2 files changed

+337
-0
lines changed

2 files changed

+337
-0
lines changed

data/sidebar_manual_v1200.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
"Advanced Features": [
6262
"extensible-variant",
6363
"scoped-polymorphic-types",
64+
"module-functions",
6465
"generalized-algebraic-data-types"
6566
]
6667
}
Lines changed: 336 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,336 @@
1+
---
2+
title: "Module Functions"
3+
description: "Module Functions in ReScript"
4+
canonical: "/docs/manual/v12.0.0/module-functions"
5+
---
6+
7+
# Module Functions
8+
9+
Module functions can be used to create modules based on types, values, or functions from other modules.
10+
This is a powerful tool that can be used to create abstractions and reusable code that might not be possible with functions, or might have a runtime cost if done with functions.
11+
12+
This is an advanced part of ReScript and you can generally get by with normal values and functions.
13+
14+
## Quick example
15+
16+
Next.js has a `useParams` hook that returns an unknown type,
17+
and it's up to the developer in TypeScript to add a type annotation for the parameters returned by the hook.
18+
19+
```TS
20+
const params = useParams<{ tag: string; item: string }>()
21+
```
22+
23+
In ReScript we can create a module function that will return a typed response for the `useParams` hook.
24+
25+
<CodeTab labels={["ReScript", "JS Output"]}>
26+
```res example
27+
module Next = {
28+
// define our module function
29+
module MakeParams = (Params: { type t }) => {
30+
@module("next/navigation")
31+
external useParams: unit => Params.t = "useParams"
32+
/* You can use values from the function parameter, such as Params.t */
33+
}
34+
}
35+
36+
module Component: {
37+
@react.component
38+
let make: unit => Jsx.element
39+
} = {
40+
// Create a module that matches the module type expected by Next.MakeParams
41+
module P = {
42+
type t = {
43+
tag: string,
44+
item: string,
45+
}
46+
}
47+
48+
// Create a new module using the Params module we created and the Next.MakeParams module function
49+
module Params = Next.MakeParams(P)
50+
51+
@react.component
52+
let make = () => {
53+
// Use the functions, values, or types created by the module function
54+
let params = Params.useParams()
55+
56+
<div>
57+
<p>
58+
{React.string("Tag: " ++ params.tag /_ params is fully typed! _/)}
59+
</p>
60+
<p> {React.string("Item: " ++ params.item)} </p>
61+
</div>
62+
}
63+
}
64+
65+
````
66+
```js
67+
// Generated by ReScript, PLEASE EDIT WITH CARE
68+
69+
import * as $$Navigation from "next/navigation";
70+
import * as JsxRuntime from "react/jsx-runtime";
71+
72+
function MakeParams(Params) {
73+
return {};
74+
}
75+
76+
var Next = {
77+
MakeParams: MakeParams
78+
};
79+
80+
function Playground$Component(props) {
81+
var params = $$Navigation.useParams();
82+
return JsxRuntime.jsxs("div", {
83+
children: [
84+
JsxRuntime.jsx("p", {
85+
children: "Tag: " + params.tag
86+
}),
87+
JsxRuntime.jsx("p", {
88+
children: "Item: " + params.item
89+
})
90+
]
91+
});
92+
}
93+
94+
var Component = {
95+
make: Playground$Component
96+
};
97+
98+
export {
99+
Next ,
100+
Component ,
101+
}
102+
/* next/navigation Not a pure module */
103+
104+
````
105+
106+
</ CodeTab>
107+
108+
## Sharing a type with an external binding
109+
110+
This becomes incredibly useful when you need to have types that are unique to a project but shared across multiple components.
111+
Let's say you want to create a library with a `getEnv` function to load in environment variables found in `import.meta.env`.
112+
113+
```res
114+
@val external env: 'a = "import.meta.env"
115+
116+
let getEnv = () => {
117+
env
118+
}
119+
```
120+
121+
It's not possible to define types for this that will work for every project, so we just set it as 'a and the consumer of our library can define the return type.
122+
123+
```res
124+
type t = {"LOG_LEVEL": string}
125+
126+
let values: t = getEnv()
127+
```
128+
129+
This isn't great and it doesn't take advantage of ReScript's type system and ability to use types without type definitions, and it can't be easily shared across our application.
130+
131+
We can instead create a module function that can return a module that has contains a `getEnv` function that has a typed response.
132+
133+
```res
134+
module MakeEnv = (
135+
E: {
136+
type t
137+
},
138+
) => {
139+
@val external env: E.t = "import.meta.env"
140+
141+
let getEnv = () => {
142+
env
143+
}
144+
}
145+
```
146+
147+
And now consumers of our library can define the types and create a custom version of the hook for their application.
148+
Notice that in the JavaScript output that the `import.meta.env` is used directly and doesn't require any function calls or runtime overhead.
149+
150+
<CodeTab labels={["ReScript", "JS Output"]}>
151+
```res
152+
module Env = MakeEnv({
153+
type t = {"LOG_LEVEL": string}
154+
})
155+
156+
let values = Env.getEnv()
157+
158+
````
159+
```js
160+
var Env = {
161+
getEnv: getEnv
162+
};
163+
164+
var values = import.meta.env;
165+
````
166+
167+
</ CodeTab>
168+
169+
## Shared functions
170+
171+
You might want to share functions across modules, like a way to log a value or render it in React.
172+
Here's an example of module function that takes in a type and a transform to string function.
173+
174+
```res
175+
module MakeDataModule = (
176+
T: {
177+
type t
178+
let toString: t => string
179+
},
180+
) => {
181+
type t = T.t
182+
let log = a => Console.log("The value is " ++ T.toString(a))
183+
184+
module Render = {
185+
@react.component
186+
let make = (~value) => value->T.toString->React.string
187+
}
188+
}
189+
```
190+
191+
You can now take a module with a type of `t` and a `toString` function and create a new module that has the `log` function and the `Render` component.
192+
193+
<CodeTab labels={["ReScript", "JS Output"]}>
194+
```res
195+
module Person = {
196+
type t = { firstName: string, lastName: string }
197+
let toString = person => person.firstName ++ person.lastName
198+
}
199+
200+
module PersonData = MakeDataModule(Person)
201+
202+
````
203+
204+
```js
205+
// Notice that none of the JS output references the MakeDataModule function
206+
207+
function toString(person) {
208+
return person.firstName + person.lastName;
209+
}
210+
211+
var Person = {
212+
toString: toString
213+
};
214+
215+
function log(a) {
216+
console.log("The value is " + toString(a));
217+
}
218+
219+
function Person$MakeDataModule$Render(props) {
220+
return toString(props.value);
221+
}
222+
223+
var Render = {
224+
make: Person$MakeDataModule$Render
225+
};
226+
227+
var PersonData = {
228+
log: log,
229+
Render: Render
230+
};
231+
````
232+
233+
</CodeTab>
234+
235+
Now the `PersonData` module has the functions from the `MakeDataModule`.
236+
237+
<CodeTab labels={["ReScript", "JS Output"]}>
238+
```res
239+
@react.component
240+
let make = (~person) => {
241+
let handleClick = _ => PersonData.log(person)
242+
<div>
243+
{React.string("Hello ")}
244+
<PersonData.Render value=person />
245+
<button onClick=handleClick>
246+
{React.string("Log value to console")}
247+
</button>
248+
</div>
249+
}
250+
```
251+
```js
252+
function Person$1(props) {
253+
var person = props.person;
254+
var handleClick = function (param) {
255+
log(person);
256+
};
257+
return JsxRuntime.jsxs("div", {
258+
children: [
259+
"Hello ",
260+
JsxRuntime.jsx(Person$MakeDataModule$Render, {
261+
value: person
262+
}),
263+
JsxRuntime.jsx("button", {
264+
children: "Log value to console",
265+
onClick: handleClick
266+
})
267+
]
268+
});
269+
}
270+
```
271+
</CodeTab>
272+
273+
## Dependency injection
274+
275+
Module functions can be used for dependency injection.
276+
Here's an example of injecting in some config values into a set of functions to access a database.
277+
278+
<CodeTab labels={["ReScript", "JS Output"]}>
279+
```res
280+
module type DbConfig = {
281+
let host: string
282+
let database: string
283+
let username: string
284+
let password: string
285+
}
286+
287+
module MakeDbConnection = (Config: DbConfig) => {
288+
type client = {
289+
write: string => unit,
290+
read: string => string,
291+
}
292+
@module("database.js")
293+
external makeClient: (string, string, string, string) => client = "makeClient"
294+
295+
let client = makeClient(Config.host, Config.database, Config.username, Config.password)
296+
}
297+
298+
module Db = MakeDbConnection({
299+
let host = "localhost"
300+
let database = "mydb"
301+
let username = "root"
302+
let password = "password"
303+
})
304+
305+
let updateDb = Db.client.write("new value")
306+
307+
````
308+
```js
309+
// Generated by ReScript, PLEASE EDIT WITH CARE
310+
311+
import * as DatabaseJs from "database.js";
312+
313+
function MakeDbConnection(Config) {
314+
var client = DatabaseJs.makeClient(Config.host, Config.database, Config.username, Config.password);
315+
return {
316+
client: client
317+
};
318+
}
319+
320+
var client = DatabaseJs.makeClient("localhost", "mydb", "root", "password");
321+
322+
var Db = {
323+
client: client
324+
};
325+
326+
var updateDb = client.write("new value");
327+
328+
export {
329+
MakeDbConnection ,
330+
Db ,
331+
updateDb ,
332+
}
333+
/* client Not a pure module */
334+
````
335+
336+
</CodeTab>

0 commit comments

Comments
 (0)