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