title | description | canonical |
---|---|---|
Module Functions | Module Functions in ReScript | /docs/manual/v11.0.0/module-functions |
Module functions can be used to create modules based on types, values, or functions from other modules. 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.
This is an advanced part of ReScript and you can generally get by with normal values and functions.
Next.js has a useParams
hook that returns an unknown type, and it's up to the developer in TypeScript to add a type annotation for the parameters returned by the hook.
constparams=useParams<{tag: string;item: string}>()
In ReScript we can create a module function that will return a typed response for the useParams
hook. <CodeTab labels={["ReScript", "JS Output"]}>
moduleNext= { // define our module functionmoduleMakeParams= (Params: { typet }) => { @module("next/navigation") externaluseParams: unit=>Params.t="useParams"/* You can use values from the function parameter, such as Params.t */ } } moduleComponent: { @react.componentletmake: unit=>Jsx.element } = { // Create a module that matches the module type expected by Next.MakeParamsmoduleP= { typet= { tag: string, item: string, } } // Create a new module using the Params module we created and the Next.MakeParams module functionmoduleParams=Next.MakeParams(P) @react.componentletmake= () => { // Use the functions, values, or types created by the module functionletparams=Params.useParams() <div> <p> {React.string("Tag: "++params.tag/* params is fully typed! */)} </p> <p> {React.string("Item: "++params.item)} </p> </div> } }
// Generated by ReScript, PLEASE EDIT WITH CAREimport*as$$Navigationfrom"next/navigation";import*asJsxRuntimefrom"react/jsx-runtime";functionMakeParams(Params){return{};}varNext={MakeParams: MakeParams};functionPlayground$Component(props){varparams=$$Navigation.useParams();returnJsxRuntime.jsxs("div",{children: [JsxRuntime.jsx("p",{children: "Tag: "+params.tag}),JsxRuntime.jsx("p",{children: "Item: "+params.item})]});}varComponent={make: Playground$Component};export{Next,Component,}/* next/navigation Not a pure module */
</ CodeTab>
This becomes incredibly useful when you need to have types that are unique to a project but shared across multiple components. Let's say you want to create a library with a getEnv
function to load in environment variables found in import.meta.env
.
@valexternalenv: 'a="import.meta.env"letgetEnv= () => { env }
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.
typet= {"LOG_LEVEL": string} letvalues: t=getEnv()
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.
We can instead create a module function that can return a module that has contains a getEnv
function that has a typed response.
moduleMakeEnv= ( E: { typet }, ) => { @valexternalenv: E.t="import.meta.env"letgetEnv= () => { env } }
And now consumers of our library can define the types and create a custom version of the hook for their application. Notice that in the JavaScript output that the import.meta.env
is used directly and doesn't require any function calls or runtime overhead.
<CodeTab labels={["ReScript", "JS Output"]}>
moduleEnv=MakeEnv({ typet= {"LOG_LEVEL": string} }) letvalues=Env.getEnv()
varEnv={getEnv: getEnv};varvalues=import.meta.env;
</ CodeTab>
You might want to share functions across modules, like a way to log a value or render it in React. Here's an example of module function that takes in a type and a transform to string function.
moduleMakeDataModule= ( T: { typetlettoString: t=>string }, ) => { typet=T.tletlog=a=>Console.log("The value is "++T.toString(a)) moduleRender= { @react.componentletmake= (~value) =>value->T.toString->React.string } }
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. <CodeTab labels={["ReScript", "JS Output"]}>
modulePerson= { typet= { firstName: string, lastName: string } lettoString=person=>person.firstName++person.lastName } modulePersonData=MakeDataModule(Person)
// Notice that none of the JS output references the MakeDataModule functionfunctiontoString(person){returnperson.firstName+person.lastName;}varPerson={toString: toString};functionlog(a){console.log("The value is "+toString(a));}functionPerson$MakeDataModule$Render(props){returntoString(props.value);}varRender={make: Person$MakeDataModule$Render};varPersonData={log: log,Render: Render};
Now the PersonData
module has the functions from the MakeDataModule
. <CodeTab labels={["ReScript", "JS Output"]}>
@react.componentletmake= (~person) => { lethandleClick=_=>PersonData.log(person) <div> {React.string("Hello ")} <PersonData.Rendervalue=person /> <buttononClick=handleClick> {React.string("Log value to console")} </button> </div> }
functionPerson$1(props){varperson=props.person;varhandleClick=function(param){log(person);};returnJsxRuntime.jsxs("div",{children: ["Hello ",JsxRuntime.jsx(Person$MakeDataModule$Render,{value: person}),JsxRuntime.jsx("button",{children: "Log value to console",onClick: handleClick})]});}
Module functions can be used for dependency injection. Here's an example of injecting in some config values into a set of functions to access a database. <CodeTab labels={["ReScript", "JS Output"]}>
moduletype DbConfig= { lethost: stringletdatabase: stringletusername: stringletpassword: string } moduleMakeDbConnection= (Config: DbConfig) => { typeclient= { write: string=>unit, read: string=>string, } @module("database.js") externalmakeClient: (string, string, string, string) =>client="makeClient"letclient=makeClient(Config.host, Config.database, Config.username, Config.password) } moduleDb=MakeDbConnection({ lethost="localhost"letdatabase="mydb"letusername="root"letpassword="password" }) letupdateDb=Db.client.write("new value")
// Generated by ReScript, PLEASE EDIT WITH CAREimport*asDatabaseJsfrom"database.js";functionMakeDbConnection(Config){varclient=DatabaseJs.makeClient(Config.host,Config.database,Config.username,Config.password);return{client: client};}varclient=DatabaseJs.makeClient("localhost","mydb","root","password");varDb={client: client};varupdateDb=client.write("new value");export{MakeDbConnection,Db,updateDb,}/* client Not a pure module */