Skip to content

Latest commit

 

History

History
78 lines (55 loc) · 2.26 KB

inlining-constants.mdx

File metadata and controls

78 lines (55 loc) · 2.26 KB
titledescriptioncanonical
Inlining Constants
Inlining constants
/docs/manual/latest/inlining-constants

Inlining Constants

Sometime, in the JavaScript output, you might want a certain value to be forcefully inlined. For example:

if(process.env.mode==='development'){console.log("Dev-only code here!")}

The reason is that your JavaScript bundler (e.g. Webpack) might turn that into:

if('production'==='development'){console.log("Dev-only code here!")}

Then your subsequent Uglifyjs optimization would remove that entire if block. This is how projects like ReactJS provide a development mode code with plenty of dev warnings, while ensuring that the uglified (minified) production code is free of those expensive blocks.

So, in ReScript, producing that example if (process.env.mode === 'development') output is important. This first try doesn't work:

<CodeTab labels={["ReScript", "JS Output"]}>

@valexternalprocess: 'a="process"letmode="development"if (process["env"]["mode"] ===mode) { Js.log("Dev-only code here!") }
varmode="development";if(process.env.mode===mode){console.log("Dev-only code here!");}

The JS output shows if (process.env.mode === mode), which isn't what we wanted. To inline mode's value, use @inline:

<CodeTab labels={["ReScript", "JS Output"]}>

@valexternalprocess: 'a="process" @inlineletmode="development"if (process["env"]["mode"] ===mode) { Js.log("Dev-only code here!") }
if(process.env.mode==="development"){console.log("Dev-only code here!");}

Now your resulting JS code can pass through Webpack and Uglifyjs like the rest of your JavaScript code, and that whole console.log can be removed.

The inlining currently only works for string, float and boolean.

Tips & Tricks

This is not an optimization. This is an edge-case feature for folks who absolutely need particular values inlined for a JavaScript post-processing step, like conditional compilation. Beside the difference in code that the conditional compilation might end up outputting, there's no performance difference between inlining and not inlining simple values in the eyes of a JavaScript engine.

close