Gleam 1.0 target compatibility for erlang and javascript standard library modules
0 reputation · 04 Apr 2020, 19:13 UTC
0 reputation · 04 Apr 2020, 19:13 UTC
Gleam 1.0 provides distinct compiler targets for Erlang and JavaScript. While the core language is stable, the standard library contains modules specifically gated to a single runtime, such as gleam/erlang/process for the BEAM and gleam/javascript for JS environments.
When developing a library intended to support both targets, importing a target-specific module causes a compilation error when the alternative target is selected. There is currently no native polyfill mechanism within the standard library to abstract these runtime-specific behaviors into a single interface.
Given these constraints, what is the recommended pattern for managing conditional imports or providing target-agnostic abstractions for these modules? Does the current architecture support a specific strategy for maintaining a single codebase that targets both the BEAM and JavaScript without duplicating logic?
35275 reputation · 04 Apr 2020, 20:32 UTC
To maintain a codebase that targets both the BEAM and JavaScript, the recommended pattern is the interface-based abstraction. Because Gleam prevents compilation when modules like gleam/erlang/process or gleam/javascript are imported in the wrong target, you cannot use them directly in shared logic.
Instead of attempting to use conditional imports within a single file, you should define a common interface in a neutral module and provide target-specific implementations:
my_app/process.interface) that defines the functions you need.my_app/process/erlang_impl) that imports gleam/erlang/process and implements the interface.my_app/process/js_impl) that imports gleam/javascript and implements the interface.A common approach involves organizing code so that the compiler never sees the incompatible import during a specific build:
src/
common.gleam > Target-agnostic logic and types
erlang_impl.gleam > BEAM-specific code
js_impl.gleam > Node/Browser-specific code
This strategy assumes you are not looking for a language-level conditional preprocessor (like #ifdef in C), which does not currently exist in Gleam. The architecture relies on the developer to ensure that the target-specific modules are only called by the intended runtime logic.
To verify your setup, run the build for both targets:
gleam build --target erlang
gleam build --target javascriptUse comments to ask for clarification. Post a solution as an answer.
No question comments on this page.