If you are here you may have heard about the Gleam programming language.
If not you can check my previous post 👉 What is gleam language used for ❓.
Gleam has as targets Erlang & JavaScript, in this article we will cover how to integrate JavaScript in a Gleam codebase and the inverse (always in the context of targeting JavaScript with Gleam).
First we will need in our Gleam project to add this line to the gleam.toml:
target = "javascript"
Javascript inside Gleam
If we have a Gleam codebase and we need to do some bings or access a third-party module (for example: express) from Gleam that is from JS.
The way to do this type of interop is as follows:
@external(javascript, "<path_to_js_file>", "<exported_function_name>")
fn <exported_function_name>(<parameters>) -> <return_type>
now lets see an example from a project I am building, electron-gleam-quick-start is a template for electron prepared to be used with Gleam.
@external(javascript, "./js_wrapper/electron.js", "onWindowAllClosed")
fn on_window_all_closed(callback: fn() -> Nil) -> Nil
in this example we are going to select in the file "./js_wrapper/electron.js" the function onWindowAllClosed that receives a callback function and doesn't return anything.
and the JS function is defined in the electron.js file as
/**
* App on window all closed
* @param {Function} callback - Callback function
* @returns {void}
*/
export function onWindowAllClosed(callback) {
if (!app) return console.error("Error: Electron app is not defined");
app.on("window-all-closed", function () {
callback();
if (process.platform !== "darwin") app.quit();
});
}
Gleam in JavaScript
To import our Gleam code from JavaScript is very easy, when you build using gleam build -t javascript
the necesarry files will be located in \build\dev\javascript<package_name> you only need to import it like this example:
// JS File
import { renderer } from "./src_gleam/build/dev/javascript/main/renderer.mjs";
renderer()
// Gleam FIle: /src_gleam/src/renderer.gleam
import gleam/io
pub fn renderer() {
io.print("Hello from renderer")
}
I hope you like this little tutorial about using the FFI capabilities of Gleam to integrate it with JS in a bidirectional way.
If you have any question leave it in the comments. I will answer as fast as I can ♥.
Top comments (0)