### Set up a New ReScript Project Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/installation.mdx Clones the ReScript project template, installs dependencies, and builds the project using npm scripts. This is the recommended way to start a new ReScript project. ```bash git clone https://github.com/rescript-lang/rescript-project-template cd rescript-project-template npm install npm run res:build node src/Demo.bs.js ``` -------------------------------- ### Set Up New ReScript Project Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/installation.mdx Clones the ReScript project template, installs dependencies, builds the project, and runs the compiled JavaScript output. This is a common starting point for new ReScript projects. ```shell git clone https://github.com/rescript-lang/rescript-project-template cd rescript-project-template npm install npm run build node src/Demo.bs.js ``` -------------------------------- ### Add ReScript npm Scripts Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v9.0.0/installation.mdx Adds convenience npm scripts to package.json for building ReScript projects and starting a development watcher. ```json "scripts": { "re:build": "bsb -make-world -clean-world", "re:start": "bsb -make-world -clean-world -w" } ``` -------------------------------- ### ReScript Build Configuration (rescript.json) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v12.0.0/installation.mdx Example of a ReScript build configuration file. This JSON file specifies project settings like source directories, module formats, and file suffixes for compiled JavaScript. ```json { "name": "your-project-name", "sources": [ { "dir": "src", // update this to wherever you're putting ReScript files "subdirs": true } ], "package-specs": [ { "module": "esmodule", "in-source": true } ], "suffix": ".res.js" } ``` -------------------------------- ### Start ReScript Watcher Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v12.0.0/installation.mdx Starts ReScript in development mode with a watcher that automatically recompiles ReScript files upon detecting changes. This streamlines the development workflow. ```shell npm run res:dev ``` -------------------------------- ### Start ReScript Project Watcher Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/installation.mdx Starts a development watcher for a ReScript project. This command automatically recompiles ReScript files whenever changes are detected, streamlining the development process. ```shell npm run start ``` -------------------------------- ### Create a basic ReScript React component Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/react/latest/installation.mdx A simple ReScript component that renders 'Hello World' using React. This code is used to test the installation and setup. ```rescript // src/Test.res @react.component let make = () => {
{React.string("Hello World")}
} ``` -------------------------------- ### Install ReScript Globally Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/installation.mdx Installs the ReScript compiler ('bs-platform') globally on your system using npm. This makes the ReScript command-line tools available from any directory. ```shell npm install -g bs-platform ``` -------------------------------- ### Add ReScript npm Scripts Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/installation.mdx Adds convenience scripts to the package.json file for building and watching ReScript files during development. `res:build` compiles the project, while `res:dev` starts a watcher for automatic recompilation. ```json { "scripts": { "res:build": "rescript", "res:dev": "rescript build -w" } } ``` -------------------------------- ### Blog Post Frontmatter Example Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/blogpost-guide.mdx Provides a complete example of the frontmatter required for a blog post, including author, date, title, and description. Frontmatter is essential for the blog post to be displayed correctly. ```yaml --- author: hongbo co-authors: - chenglou - ryyppy date: "2017-10-01" previewImg: badge: release title: Bloomberg announces BuckleScript 1.0 description: | some multiline description --- ``` -------------------------------- ### Install ReScript Locally (npm, yarn, pnpm, bun, deno) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v12.0.0/installation.mdx Installs ReScript as a local dependency within a JavaScript project. This is the first step in manually integrating ReScript into an existing project. ```shell npm install rescript ``` ```shell yarn add rescript ``` ```shell pnpm install rescript ``` ```shell bun install rescript ``` ```shell // you will need deno configured to have a node_modules folder deno install npm:rescript --allow-scripts ``` -------------------------------- ### Create New ReScript Project (npm) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v11.0.0/installation.mdx Initiates a new ReScript project using the create-rescript-app generator with npm. This is the fastest way to start a new project. ```shell npm create rescript-app@latest ``` -------------------------------- ### Setup and Build Commands for ReScript Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/README.md Commands to set up the ReScript project, install dependencies, perform initial builds, and run the development server. Also includes instructions for running ReScript in watch mode. ```shell # For first time clone / build (install dependencies) npm i # Initial build npx rescript # Build the index data. Only needed for initial clone (or content H2 changes) npm run update-index # In a new tab npm run dev open localhost:3000 # In case you want to run ReScript in watchmode: npx rescript -w ``` -------------------------------- ### Install ReScript Locally (bun) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v11.0.0/installation.mdx Installs ReScript and its core library as local dependencies in a project using bun. This is part of the manual setup for integrating ReScript into an existing project. ```shell bun install rescript @rescript/core ``` -------------------------------- ### Install ReScript Locally for Existing JS Project Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/installation.mdx Installs the ReScript compiler ('bs-platform') as a development dependency in an existing JavaScript project. This allows you to use ReScript within your current project structure. ```shell npm install --save-dev bs-platform ``` -------------------------------- ### Create New ReScript Project (npx) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v11.0.0/installation.mdx Initiates a new ReScript project using the create-rescript-app generator with npx. This is an alternative method to start a new project. ```shell npx create-rescript-app ``` -------------------------------- ### Create New ReScript Project (npm, npx, yarn, pnpm, bun) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v12.0.0/installation.mdx Initiates a new ReScript project using the create-rescript-app generator. This command is compatible with various package managers and sets up a project with frameworks like Next.js or Vite, along with React and Tailwind CSS. ```shell npm create rescript-app@latest ``` ```shell npx create-rescript-app ``` ```shell yarn create rescript-app ``` ```shell pnpm create rescript-app ``` ```shell bun create rescript-app ``` -------------------------------- ### Install ReScript Locally in Existing JS Project Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/installation.mdx Installs the ReScript package as a local dependency in an existing JavaScript project using npm. ```bash npm install rescript ``` -------------------------------- ### ReScript Build Configuration (rescript.json) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v11.0.0/installation.mdx Example ReScript build configuration file (rescript.json). It defines project settings like sources, module format, output suffix, and dependencies. ```json { "name": "your-project-name", "sources": [ { "dir": "src", "subdirs": true } ], "package-specs": [ { "module": "esmodule", "in-source": true } ], "suffix": ".res.js", "bs-dependencies": ["@rescript/core"], "bsc-flags": ["-open RescriptCore"] } ``` -------------------------------- ### Install ReScript Locally (pnpm) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v11.0.0/installation.mdx Installs ReScript and its core library as local dependencies in a project using pnpm. This is part of the manual setup for integrating ReScript into an existing project. ```shell pnpm install rescript @rescript/core ``` -------------------------------- ### ReScript Build Configuration (bsconfig.json) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/installation.mdx Defines the build settings for ReScript projects, including source directories, output module format, and file suffixes. This JSON file configures how ReScript is compiled. ```json { "name": "your-project-name", "sources": [ { "dir": "src", "subdirs": true } ], "package-specs": [ { "module": "es6", "in-source": true } ], "suffix": ".bs.js", "bs-dependencies": [] } ``` -------------------------------- ### Install ReScript Locally (yarn) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v11.0.0/installation.mdx Installs ReScript and its core library as local dependencies in a project using yarn. This is part of the manual setup for integrating ReScript into an existing project. ```shell yarn add rescript @rescript/core ``` -------------------------------- ### Install ReScript Locally (npm) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v11.0.0/installation.mdx Installs ReScript and its core library as local dependencies in a project using npm. This is part of the manual setup for integrating ReScript into an existing project. ```shell npm install rescript @rescript/core ``` -------------------------------- ### Add npm Scripts to package.json Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v12.0.0/installation.mdx Defines convenience scripts in a project's `package.json` file for common ReScript build and development tasks. These scripts abstract the underlying ReScript commands. ```json "scripts": { "res:build": "rescript", "res:dev": "rescript -w" } ``` -------------------------------- ### ReScript Codeblock (Default) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/markdown-guide.mdx A standard ReScript codeblock example without any specific line highlighting. ```res let a = "This is a Reason codeblock" ``` -------------------------------- ### Create New Blog Post File Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/blogpost-guide.mdx Demonstrates how to create a new markdown file for a blog post using the 'touch' command. The filename must start with the date in YYYY-MM-DD format. ```shell touch _blogposts/2020-01-30-my-new-blog-post.mdx ``` -------------------------------- ### Install ReScript Core Package Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v11.0.0/migrate-to-v11.mdx Installs the ReScript Core package using npm. This package is a new standard library for ReScript and needs to be manually installed in ReScript 11. ```console $ npm install @rescript/core ``` -------------------------------- ### Install @rescript/react using npm Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/react/latest/installation.mdx Installs the @rescript/react package using npm. This is a fundamental step for integrating ReScript with React projects. ```shell npm install @rescript/react ``` -------------------------------- ### Initialize ReScript Project Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/build-overview.mdx Initializes a new ReScript project in a specified directory using the 'bsb -init' command. This sets up the basic project structure and configuration. ```sh bsb -init my-directory-name ``` -------------------------------- ### ReScript CLI Help Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v11.0.0/build-overview.mdx Displays the usage instructions and available subcommands for the ReScript command-line interface. It lists options like version and help, and subcommands such as build, clean, format, convert, dump, and help. ```sh ❯ rescript help Usage: rescript `rescript` is equivalent to `rescript build` Options: -v, -version display version number -h, -help display help Subcommands: build clean format convert dump help Run `rescript -h` for subcommand help. Examples: rescript build -h rescript format -h ``` -------------------------------- ### Install bs-platform and @rescript/std Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v9.0.0/build-external-stdlib.mdx Installs the necessary ReScript platform and the standalone standard library package for external use. Ensure versions match. ```shell npm install bs-platform@9.0.0 --save-dev npm install @rescript/std@9.0.0 --save ``` -------------------------------- ### Example: Find First Binding Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/api/belt/map-string.mdx An example demonstrating the use of `findFirstBy` to find a key-value pair in a map. ```rescript let s0 = Belt.Map.String.fromArray([("4", 4), ("1", 1), ("2", 2), ("3", 3)]) Belt.Map.String.findFirstBy(s0, (k, _) => k == "4") == Some(("4", 4)) ``` -------------------------------- ### Install ReScript 10.0 Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/_blogposts/2022-08-25-release-10-0-0.mdx Command to install the latest ReScript version using npm. This is a foundational step for using the new features. ```bash npm install rescript@10 ``` -------------------------------- ### View Available ReScript Templates Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/build-overview.mdx Displays all available project templates for the ReScript build system using the 'bsb -themes' command. This helps users choose a starting point for their projects. ```sh bsb -themes ``` -------------------------------- ### ReScript Intro Component Usage Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/markdown-guide.mdx Demonstrates the ReScript Intro component, used for introductory text or chapter heroes, providing a quick overview of a document's topic. ```re Your hero text ``` -------------------------------- ### Install ReScript 9.0.1 Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/_blogposts/2021-02-09-release-9-0.mdx Command to install the specified version of ReScript using npm. This is a basic installation command with no specific dependencies or inputs beyond having npm installed. ```sh npm install bs-platform@9.0.1 ``` -------------------------------- ### View ReScript Build System Help Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/build-overview.mdx Displays all available options and commands for the ReScript build system (bsb). This is a general help command for understanding the tool's capabilities. ```sh bsb -help ``` -------------------------------- ### Get List Length Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v9.0.0/api/belt/list.mdx Returns the number of elements in a list. Example shows getting the length of a list containing integers. ```rescript let length: t<'a> => int Belt.List.length(list{1, 2, 3}) // 3 ``` -------------------------------- ### Create ReScript Records for JavaScript Objects Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/newcomer-examples.mdx Demonstrates creating JavaScript objects using ReScript record syntax, which provides type safety and structure. The example defines a `payload` type and then creates a `student1` object, showing the ReScript, ML, and resulting JavaScript code. ```re type payload = { name: string, age: int, }; let student1 = { name: "John", age: 30, }; ``` ```ml type payload = { name: string; age: int; } let student1 = { name = "John"; age = 30; } ``` ```js var student1 = { name: "John", age: 30, }; ``` -------------------------------- ### Rescript substringToEnd: Get substring from start to end Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/api/js/string.mdx The substringToEnd function extracts a substring starting from a given position to the end of the string. It returns the entire string if the start position is zero or negative, and an empty string if the start position is beyond the string's length. ```rescript let substringToEnd: (~from: int, t) => t ``` ```rescript Js.String.substringToEnd(~from=4, "playground") == "ground" Js.String.substringToEnd(~from=-3, "playground") == "playground" Js.String.substringToEnd(~from=12, "playground") == "" ``` -------------------------------- ### Example: Find First Entry Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/api/belt/map-dict.mdx An example demonstrating how to use findFirstBy to retrieve a specific key-value pair from a MapDict. ```rescript module IntCmp = Belt.Id.MakeComparable({ type t = int; let cmp = Pervasives.compare; }); let s0 = Belt.Map.Dict.fromArray([|(4, "4"), (1, "1"), (2, "2"), (3, "3")|], ~cmp=IntCmp.cmp); Belt.Map.Dict.findFirstBy(s0, (k, _) => k == 4) == Some((4, "4")); ``` -------------------------------- ### Add Element to Beginning of Array Example Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/api/js/array.mdx Shows an example of using `unshift` to add an element to the start of an array and observes the change in array length and content. ```rescript let arr = ["b", "c", "d"] Js.Array.unshift("a", arr) == 4 arr == ["a", "b", "c", "d"] ``` -------------------------------- ### substr - Get Substring Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/api/js/string-2.mdx Retrieves a portion of a string from a specified starting position to the end. Handles negative start positions and positions beyond string length. ```APIDOC ## substr ### Description Returns the substring of `str` from position `n` to the end of the string. If `n` is negative, the start position is calculated from the end of the string. If `n` exceeds the string length, an empty string is returned. ### Method N/A (This is a function signature, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example ```res Js.String2.substr("abcdefghij", ~from=3) == "defghij" Js.String2.substr("abcdefghij", ~from=-3) == "hij" Js.String2.substr("abcdefghij", ~from=12) == "" ``` ``` -------------------------------- ### Example: Get Map Keys as Array (ReScript) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/api/belt/map.mdx Demonstrates extracting keys from a map into a sorted array using `Belt.Map.keysToArray`. The example uses `Belt.Map.fromArray` to initialize the map. ```res module IntCmp = Belt.Id.MakeComparable({ type t = int let cmp = (a, b) => Pervasives.compare(a, b) }) Belt.Map.keysToArray(Belt.Map.fromArray([(2, "2"), (1, "1"), (3, "3")], ~id=module(IntCmp))) == [ 1, 2, 3, ] ``` -------------------------------- ### Basic Let Binding Syntax Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/let-binding.mdx Demonstrates the fundamental 'let' binding syntax in ReScript and its ML-like predecessor, showing how values are assigned to names and the resulting JavaScript output. Illustrates simple variable declaration and reassignment. ```re let greeting = "hello!"; let score = 10; let newScore = 10 + score; ``` ```ml let greeting = "hello!" let score = 10 let newScore = 10 + score ``` ```js var greeting = "hello!"; var score = 10; var newScore = 20; ``` -------------------------------- ### Re.lastIndex Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/api/js/re.mdx Gets the index where the next match will start searching. ```APIDOC ## Re.lastIndex ### Description Returns the index where the next match will start its search. This property will be modified when the RegExp object is used, if the global ("g") flag is set. ### Method `Re.lastIndex ### Endpoint N/A (Function within a module) ### Parameters - **t** (RegExp object) - The RegExp object. ### Request Example ```re let re = [%re "/ab*/g"]; let str = "abbcdefabh"; let break = ref(false); while (! break^) { switch (Js.Re.exec_(re, str)) { | Some(result) => Js.Nullable.iter( Js.Re.captures(result)[0], [@bs] match => { let next = Belt.Int.toString(Js.Re.lastIndex(re)); Js.log("Found " ++ match ++ ". Next match starts at " ++ next); }, ) | None => break := true }; }; ``` ### Response - **int**: The index for the next search. ``` -------------------------------- ### substringToEnd - Get Substring to End Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/api/js/string-2.mdx Retrieves the portion of a string from a specified starting position to the end. Handles zero or negative start positions, and positions beyond the string length. ```APIDOC ## substringToEnd ### Description Returns the substring of `str` from position `start` to the end. If `start` is zero or negative, the entire string is returned. If `start` is greater than or equal to the string length, an empty string is returned. ### Method N/A (This is a function signature, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example ```res Js.String2.substringToEnd("playground", ~from=4) == "ground" Js.String2.substringToEnd("playground", ~from=-3) == "playground" Js.String2.substringToEnd("playground", ~from=12) == "" ``` ``` -------------------------------- ### substrAtMost - Get Substring with Length Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/api/js/string-2.mdx Extracts a substring of a specified length starting from a given position. Supports negative start positions and handles invalid length or position inputs. ```APIDOC ## substrAtMost ### Description Returns the substring of `str` of length `n` starting at position `pos`. Handles negative `pos` values and cases where `pos` or `n` are out of bounds, returning an empty string as appropriate. ### Method N/A (This is a function signature, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example ```res Js.String2.substrAtMost("abcdefghij", ~from=3, ~length=4) == "defg" Js.String2.substrAtMost("abcdefghij", ~from=-3, ~length=4) == "hij" Js.String2.substrAtMost("abcdefghij", ~from=12, ~length=2) == "" ``` ``` -------------------------------- ### Basic Source Directory Configuration Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v11.0.0/build-configuration.mdx Specifies directories to include as source files for the ReScript build. The 'src' and 'examples' directories are explicitly included. ```json { "sources": ["src", "examples"] } ``` -------------------------------- ### Create New ReScript Project (bun) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v11.0.0/installation.mdx Initiates a new ReScript project using the create-rescript-app generator with bun. This option is for developers using the bun runtime. ```shell bun create rescript-app ``` -------------------------------- ### Install ReScript Compiler using npm Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/_blogposts/2024-01-11-release-11-0-0.mdx Command to install the ReScript compiler version 11.0 using npm. This is the recommended way to get the latest version for your project. ```sh npm install rescript@11 ``` -------------------------------- ### Simplify Module Access with 'open' Keyword Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/module.mdx Demonstrates how to use the 'open' keyword in ReScript to bring module contents into the current scope, avoiding repetitive module name prepending. Shows examples before and after using 'open', including ML and JS outputs. ```rescript let p = School.getProfession(School.person1); ``` ```ml let p = School.getProfession School.person1 ``` ```javascript var p = School.getProfession(School.person1); ``` -------------------------------- ### Install ReScript 8.3 Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/_blogposts/2020-09-25-release-8-3.mdx Command to install the specific version of ReScript's compiler package (bs-platform) using npm. ```bash npm i bs-platform@8.3.0 ``` -------------------------------- ### Get Value from HashMap Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/api/belt/hash-map.mdx Retrieves the value associated with a given key from the hash map. Returns Some(value) if the key exists, otherwise returns None. The example shows getting an existing and a non-existent key. ```rescript let get: (t('key, 'value, 'id), 'key) => option('value); ``` ```rescript module IntHash = Belt.Id.MakeHashable({ type t = int; let hash = a => a; let eq = (a, b) => a == b; }); let s0 = Belt.HashMap.make(~hintSize=10, ~id=(module IntHash)); Belt.HashMap.set(s0, 1, "value1"); Belt.HashMap.get(s0, 1) == Some("value1"); Belt.HashMap.get(s0, 2) == None; ``` -------------------------------- ### Rescript substrAtMost: Get substring of specific length Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/api/js/string.mdx The substrAtMost function extracts a substring of a given length starting from a specified position. It adjusts negative start positions based on string length and returns an empty string for out-of-bounds start positions or non-positive lengths. Similar to `substr`, `substring` is preferred. ```rescript let substrAtMost: (~from: int, ~length: int, t) => t ``` ```rescript Js.String.substrAtMost(~from=3, ~length=4, "abcdefghij") == "defg" Js.String.substrAtMost(~from=-3, ~length=4, "abcdefghij") == "hij" Js.String.substrAtMost(~from=12, ~length=2, "abcdefghij") == "" ``` -------------------------------- ### Build ReScript Project Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/build-overview.mdx Builds the entire ReScript project. The '-make-world' flag triggers a full build of all project targets. Adding '-w' enables a watcher that automatically rebuilds on file changes. ```sh bsb -make-world ``` ```sh bsb -make-world -w ``` -------------------------------- ### Create JavaScript Objects in ReScript Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/newcomer-examples.mdx Shows two methods for creating JavaScript objects in ReScript: directly using object literal syntax and using ReScript records which are then compiled to JS objects. Both methods are demonstrated with ReScript, ML, and JS output. ```re let student1 = { "name": "John", "age": 30, }; ``` ```ml let student1 = [%bs.obj { name = "John"; age = 30 }] ``` ```js var student1 = { name: "John", age: 30, }; ``` -------------------------------- ### Install and Run ReScript Language Server Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/_blogposts/2024-01-11-release-11-0-0.mdx Installs the ReScript Language Server globally and provides the command to run it for standard input/output communication, enabling editor tooling integration. ```sh npm install -g @rescript/language-server npx rescript-language-server --stdio ``` -------------------------------- ### Get Element by Index (Exception) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v9.0.0/api/belt/list.mdx Retrieves the element at a specific index, similar to `get`, but raises an exception if the index is out of bounds. Use with caution. Examples show successful access and an out-of-bounds access that would raise an error. ```rescript let getExn: (t<'a>, int) => 'a let abc = list{"A", "B", "C"} abc->Belt.List.getExn(1) // "B" abc->Belt.List.getExn(4) // Raises an Error ``` -------------------------------- ### ReScript Tagged Variant Example Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/_blogposts/2023-04-17-improving-interop.mdx Demonstrates a basic ReScript tagged variant and its JavaScript runtime representation. This example shows the default behavior before customization. ```rescript type entity = User({"name": string}) | Group({"workingName": string}) let user = User({"name": "Hello"}) ``` ```javascript var user = { TAG: /* User */ 0, name: "Hello" }; ``` -------------------------------- ### Counter Example with useReducer - ReScript/JS Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/react/latest/hooks-reducer.mdx An example demonstrating a counter component using `React.useReducer`. It defines actions (Inc, Dec), state structure, and a reducer function to handle state transitions, along with React component setup. ```rescript // Counter.res type action = Inc | Dec type state = {count: int} let reducer = (state, action) => { switch action { | Inc => {count: state.count + 1} | Dec => {count: state.count - 1} } } @react.component let make = () => { let (state, dispatch) = React.useReducer(reducer, {count: 0}) <> {React.string("Count:" ++ Belt.Int.toString(state.count))} } ``` ```javascript function reducer(state, action) { if (action) { return { count: (state.count - 1) | 0, }; } else { return { count: (state.count + 1) | 0, }; } } function Counter(Props) { var match = React.useReducer(reducer, { count: 0, }); var dispatch = match[1]; return React.createElement( React.Fragment, undefined, "Count:" + String(match[0].count), React.createElement( "button", { onClick: function (param) { return Curry._1(dispatch, /* Dec */ 1); }, }, "-", ), React.createElement( "button", { onClick: function (param) { return Curry._1(dispatch, /* Inc */ 0); }, }, "+", ), ); } ``` -------------------------------- ### ReScript Codeblock (Default Language) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/markdown-guide.mdx An example of a codeblock using the default language ('text'), which does not provide syntax highlighting. ```text The default language is set to `text` and will not provide any syntax highlighting ``` -------------------------------- ### Install and Use ReScript Documentation Tool Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/_blogposts/2024-01-11-release-11-0-0.mdx Installs the experimental ReScript documentation generation tool globally and demonstrates its usage to extract documentation from ReScript files into a JSON format. ```sh npm install --save-dev @rescript/tools npx rescript-tools doc src/MyFile.res > doc.json ``` -------------------------------- ### Copy Within Array with Start Index in ReScript Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/api/js/array.mdx Copies a section of an array to another location within the same array starting from a specified index using `Js.Array.copyWithinFrom` in ReScript. This operation modifies the original array. The example copies from index 2 to index 0. ```rescript let arr = [100, 101, 102, 103, 104] Js.Array.copyWithinFrom(~from=2, ~to_=0, arr) == [102, 103, 104, 103, 104] arr == [102, 103, 104, 103, 104] ``` -------------------------------- ### Get List Head Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v9.0.0/api/belt/list.mdx Retrieves the first element of a list, returning Some(value) if the list is not empty, and None if it is. Examples demonstrate both cases. ```rescript let head: t<'a> => option<'a> Belt.List.head(list{}) // None Belt.List.head(list{1, 2, 3}) // Some(1) ``` -------------------------------- ### Example: Get Map Values as Array (ReScript) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/api/belt/map.mdx Shows how to retrieve all values from a map as an array in key-sorted order using `Belt.Map.valuesToArray`. ```res module IntCmp = Belt.Id.MakeComparable({ type t = int let cmp = (a, b) => Pervasives.compare(a, b) }) Belt.Map.valuesToArray( Belt.Map.fromArray([(2, "2"), (1, "1"), (3, "3")], ~id=module(IntCmp)), ) == ["1", "2", "3"] ``` -------------------------------- ### Simplified Module Access with `open` in ReScript Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v11.0.0/module.mdx Shows the effect of using `open School` in ReScript to access `getProfession` and `person1` directly, contrasting with the previous example. Includes the JavaScript output. ```rescript open School let p = getProfession(person1) ``` ```javascript var p = School.getProfession(School.person1); ``` -------------------------------- ### Extend Module with 'include' (ReScript, ML, JS) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/module.mdx Demonstrates extending a BaseComponent module with ActualComponent using 'include'. The 'include' keyword copies the BaseComponent's content into ActualComponent, allowing for overrides and new definitions. Examples are provided in ReScript, ML, and the resulting JavaScript output. ```rescript module BaseComponent = { let defaultGreeting = "Hello"; let getAudience = (~excited) => excited ? "world!" : "world"; }; module ActualComponent = { /* the content is copied over */ include BaseComponent; /* overrides BaseComponent.defaultGreeting */ let defaultGreeting = "Hey"; let render = () => defaultGreeting ++ " " ++ getAudience(~excited=true); }; ``` ```ml module BaseComponent = struct let defaultGreeting = "Hello" let getAudience ~excited = if excited then "world!" else "world" end module ActualComponent = struct (* the content is copied over *) include BaseComponent (* overrides BaseComponent.defaultGreeting *) let defaultGreeting = "Hey" let render () = defaultGreeting ^ " " ^ (getAudience ~excited:true) end ``` ```javascript function getAudience(excited) { if (excited) { return "world!"; } else { return "world"; } } var BaseComponent = { defaultGreeting: "Hello", getAudience: getAudience, }; var defaultGreeting = "Hey"; function render(param) { return "Hey world!"; } var ActualComponent = { getAudience: getAudience, defaultGreeting: defaultGreeting, render: render, }; ``` -------------------------------- ### ReScript Code Example Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v12.0.0/build-external-stdlib.mdx A simple ReScript code snippet demonstrating the usage of `Array.forEach` and `Console.log`. ```rescript Array.forEach([1, 2, 3], num => Console.log(num)) ``` -------------------------------- ### Get Byte Offset of Uint16Array Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/api/js/typed-array-2_uint-16-array.mdx Retrieves the byte offset of the Uint16Array within its underlying ArrayBuffer. This indicates the starting position of the array's data. ```res let byteOffset: t => int ``` -------------------------------- ### Create New ReScript Project (yarn) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v11.0.0/installation.mdx Initiates a new ReScript project using the create-rescript-app generator with yarn. This method is suitable for projects using yarn as their package manager. ```shell yarn create rescript-app ``` -------------------------------- ### Rescript substr: Get substring from position to end Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/api/js/string.mdx The substr function returns a portion of a string starting from a specified position to the end. It handles negative positions by calculating from the string's length and returns an empty string if the start position is out of bounds. It is a legacy function, with `substring` recommended for modern use. ```rescript let substr: (~from: int, t) => t ``` ```rescript Js.String.substr(~from=3, "abcdefghij") == "defghij" Js.String.substr(~from=-3, "abcdefghij") == "hij" Js.String.substr(~from=12, "abcdefghij") == "" ``` -------------------------------- ### Create New ReScript Project (pnpm) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v11.0.0/installation.mdx Initiates a new ReScript project using the create-rescript-app generator with pnpm. This is for users who prefer pnpm for package management. ```shell pnpm create rescript-app ``` -------------------------------- ### Remove Elements From Position to End In-Place Example Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/api/js/array.mdx Shows how to use `removeFromInPlace` to remove elements from an array starting at a given index until the end, modifying the array. ```rescript let arr = ["a", "b", "c", "d", "e", "f"] Js.Array.removeFromInPlace(~pos=4, arr) == ["e", "f"] arr == ["a", "b", "c", "d"] ``` -------------------------------- ### Build ReScript project with dependencies Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/_blogposts/2021-05-07-release-9-1.mdx Shows how to explicitly build a ReScript project with all its dependencies using the `rescript build -with-deps` command, replacing the old `bsb -make-world` command. However, the example also clarifies that this is often unnecessary as `rescript build` now handles this automatically. ```sh rescript build -with-deps ``` -------------------------------- ### ReScript CLI Usage Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/_blogposts/2021-05-07-release-9-1.mdx Demonstrates the usage of the unified `rescript` command-line interface, replacing the separate `bsc` and `bsb` commands. This includes examples of formatting files, building projects, and watching for changes. ```sh ❯ rescript -help Available flags -v, -version display version number -h, -help display help Subcommands: build clean format convert help Run rescript subcommand -h for more details, For example: rescript build -h rescript format -h The default `rescript` is equivalent to `rescript build` subcommand ``` -------------------------------- ### substring - Get Substring Between Positions Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/api/js/string-2.mdx Extracts characters from a string between two specified positions (start inclusive, end exclusive). Handles inverted or out-of-bounds positions. ```APIDOC ## substring ### Description Returns characters from `str` starting at `start` up to, but not including, `finish`. If `start` is negative, it's treated as 0. If `finish` is zero or negative, an empty string is returned. If `start` is greater than `finish`, the positions are swapped. ### Method N/A (This is a function signature, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example ```res Js.String2.substring("playground", ~from=3, ~to_=6) == "ygr" Js.String2.substring("playground", ~from=6, ~to_=3) == "ygr" Js.String2.substring("playground", ~from=4, ~to_=12) == "ground" ``` ``` -------------------------------- ### Example: Get Value by Key (ReScript) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/api/belt/map.mdx Illustrates retrieving a value associated with a specific key from a map using `Belt.Map.get`. It shows cases where the key exists and where it does not. ```res module IntCmp = Belt.Id.MakeComparable({ type t = int let cmp = (a, b) => Pervasives.compare(a, b) }) Belt.Map.get(Belt.Map.fromArray([(2, "2"), (1, "1"), (3, "3")], ~id=module(IntCmp)), 2) == Some("2") Belt.Map.get(Belt.Map.fromArray([(2, "2"), (1, "1"), (3, "3")], ~id=module(IntCmp)), 2) == None ``` -------------------------------- ### Build ReScript Project Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/build-overview.mdx Initiates the build process for the current ReScript project, including its own source files and any pinned dependencies. This is the primary command for compiling ReScript code. ```shell rescript ``` -------------------------------- ### Define and Use a ReScript Module Signature and Implementation Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/module.mdx Illustrates the relationship between a ReScript implementation file (.res) and its corresponding interface file (.resi). The .res file defines the module's implementation, while the .resi file defines its public signature. Includes example ReScript code and its JavaScript output. ```res /* file React.res (implementation. Compiles to module React) */ type state = int let render = (str) => str ``` ```js function render(str) { return str; } ``` ```res /* file React.resi (interface. Compiles to the signature of React.res) */ type state = int let render: string => string ``` -------------------------------- ### Get Element by Index Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v9.0.0/api/belt/list.mdx Retrieves the element at a specific index in a list, returning Some(value) or None if the index is out of bounds. Examples show accessing an element and an out-of-bounds access. ```rescript let get: (t<'a>, int) => option<'a> let abc = list{"A", "B", "C"} abc->Belt.List.get(1) // Some("B") abc->Belt.List.get(4) // None ``` -------------------------------- ### Create Parametrized Types in ReScript Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/newcomer-examples.mdx Illustrates how to define parametrized types in ReScript, allowing for generic type definitions. This example defines a `universityStudent` record and a `response` type that can hold any student type, showing both ReScript and ML syntaxes. ```re type universityStudent = {gpa: float}; type response('studentType) = { status: int, student: 'studentType, }; ``` ```ml type universityStudent = {gpa: float} type 'studentType response = { status: int; student: 'studentType; } ``` ```js // Empty output ``` -------------------------------- ### Get List Tail Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v9.0.0/api/belt/list.mdx Returns a new list containing all elements except the first. Returns None if the list is empty, otherwise Some(tail). Examples show both scenarios. ```rescript let tail: t<'a> => option> Belt.List.tail(list{1, 2, 3}) // Some(list{2, 3}) Belt.List.tail(list{}) // None ``` -------------------------------- ### ReScript For Loop (Descending) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v9.0.0/control-flow.mdx Demonstrates the ReScript 'for' loop with the 'downto' keyword for iterating in reverse order, from a start value down to an end value, inclusive. Includes a practical example. ```rescript for i in startValueInclusive downto endValueInclusive { Js.log(i) } ``` ```rescript // prints: 3 2 1, one per line for x in 3 downto 1 { Js.log(x) } ``` -------------------------------- ### Basic ReScript Console Output Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/_blogposts/2025-03-05-what-can-i-do-with-rescript.mdx A simple ReScript code snippet that prints 'Hello' to the console. This demonstrates the basic syntax and how to compile and run ReScript code in a Node.js environment. ```rescript // index.res Console.log("Hello") ``` -------------------------------- ### ReScript For Loop (Ascending) Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v9.0.0/control-flow.mdx Illustrates the ReScript 'for' loop for iterating from a start value to an end value, inclusive. It also shows an example of counting upwards and how it translates to JavaScript. ```rescript for i in startValueInclusive to endValueInclusive { Js.log(i) } ``` ```rescript // prints: 1 2 3, one per line for x in 1 to 3 { Js.log(x) } ``` -------------------------------- ### Multi-Syntax CodeTab with Highlighting Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/markdown-guide.mdx Demonstrates the CodeTab component for displaying multiple syntax versions of the same code snippet, including line highlighting support. ```res let a = "Some ReScript code" switch myValue { } ``` ```js var a = "Some JavaScript code"; var highlighted = "Also supports highlighting ranges"; ``` -------------------------------- ### Get a value from HashMap.Int by key Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v8.0.0/api/belt/hash-map-int.mdx Retrieves the value associated with a given key. Returns `Some(value)` if the key exists, otherwise `None`. The example shows retrieving existing and non-existing keys. ```rescript let hMap = Belt.HashMap.Int.make(~hintSize=10); Belt.HashMap.Int.set(hMap, 1, "value1"); Belt.HashMap.Int.get(hMap, 1) == Some("value1"); Belt.HashMap.Int.get(hMap, 2) == None; ``` -------------------------------- ### Use `open` to Simplify Module Access (ReScript) and JS Output Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v12.0.0/module.mdx Demonstrates how to use the `open` keyword in ReScript to make module members directly accessible without prefixing. This example shows the ReScript code and its JavaScript equivalent. ```rescript let p = { open School getProfession(person1) } ``` ```javascript var p = School.getProfession(School.person1); ``` -------------------------------- ### Add Multiple Elements to Beginning of Array Example Source: https://github.com/rescript-lang/rescript-lang.org/blob/master/pages/docs/manual/v10.0.0/api/js/array.mdx Demonstrates adding multiple elements from one array to the start of another using `unshiftMany`, showing the resulting array and its new length. ```rescript let arr = ["d", "e"] Js.Array.unshiftMany(["a", "b", "c"], arr) == 5 arr == ["a", "b", "c", "d", "e"] ```