RescriptReactRouter with a Base URL

Hey folks,

I’m curious if there is a way to use ReScriptReactRouter in such a way that the base URL varies from production to development. My use case is that I’m deploying to GitHub Pages, so my url is https://user.github.io/project but in development it’s obviously http://localhost:3000/. This breaks when I use the push method of the router with ‘/blah/bleh’ as it loses the project name on GitHub Pages.

Is there a way to detect and/or otherwise handle the change to the base URL so that RescriptReactRouter.push prepends the project name, but only when deployed to GitHub Pages?

Thanks in advance,

Wil

You want to do something like this?

let baseUrl = if NODE_ENV == "production" { "/project" } else { "" }
...
RescriptReacterRouter.push(baseUrl ++ "/blah/bleh")

It’s possible, but a little convoluted. The ReScript compiler supports conditional compilation using the value of an environment variable, but only using OCaml syntax, not ReScript syntax. But luckily, you can define the baseUrl variable in OCaml syntax and use it from a ReScript file, e.g.

Define:

(* config.ml *)

let baseUrl =
#if defined NODE_ENV && NODE_ENV = "production" then
  "/project"
#else
  ""
#end

Use:

// Component.res

RescriptReacterRouter.push(Config.baseUrl ++ "/blah/bleh")

Now all you need to do for a production build is run:

NODE_ENV=production rescript
1 Like

Here’s what I generally do: rescript-react-starter-kit/Router.res at main · bloodyowl/rescript-react-starter-kit · GitHub

Why? If you are using a bundler, you can just do this, or am I mistaken?

@val external process: 'a = "process"

let baseUrl = if (process["env"]["NODE_ENV"] === "production") {
  "/project"
}
else {
  ""
}

I’m not sure. Do bundlers fetch the value of process.env.NODE_ENV and resolve the condition at bundling time? If they have some special logic that does that, then it is simple. Otherwise it looks like this code will execute at runtime and fail because in the browser there is no process.env?