0

Here's the deal: with webpack you can provide environment variables (via DefinePlugin or EnvironmentPlugin) so they can be consumed by the code like process.env.MY_VAR. It works that they'll be inlined with real values at the build time.

But I'm having trouble trying to consume them in Reason. Bucklescript has Node.Process module, but when you use Node.Process##env it is transpiled to

var process = require("process")
var myVar = process.env["MY_VAR"]

So it's not gonna be picked up by webpack and inlined. So what can I use to achieve that it will be traspiled to var myVar = process.env.MY_VAR?

Saito
  • 694
  • 7
  • 25

1 Answers1

3

I actually don't think this is a very good use case for %raw, but would rather just use an ordinary external:

[@bs.val] external token : string = "process.env.TOKEN";

This has a couple benefits over %raw:

  • external will check that it is a syntactically valid global identifier. With %raw, anything goes and there's no guarantee it will produce correct JavaScript.
  • externals are inlined. This means it will evaluate where it is used, in case the value changes or is different in different modules for example. It also protects against mutation of an indirect global variable.

None of these matter all that much, probably, but I don't see any benefit of using %raw over external, so might as well do it properly.

glennsl
  • 28,186
  • 12
  • 57
  • 75
  • 1
    This version actually has benefits if you're using `DefinePlugin` together with the optimisations plugins. Webpacks optimisation engine will completely elide or unwrap things such as `if (process.env.NODE_ENV == "production")` if it knows the value of `process.env.NODE_ENV` via `DefinePlugin`. It can only do this if you don't introduce an intermediate variable such as what the `%bs.raw` solution does. – Matthew Scharley Dec 20 '18 at 01:23