Evaluate code at build time using babel-plugin-preval
We can use babel-plugin-preval
in React.Js apps to perform computations at build time rather than at runtime. For example we can use it to read the contents of a file at build time.
Given below is sample code that is used to get the user that ran the build and display their username.
import React from 'react'
import preval from 'preval.macro'
const whoami = preval`
// this is Node.Js code.
const userInfo = require('os').userInfo()
module.exports = userInfo.username
`
function WhoAmI() {
return (
<div>
<h1>
<pre>whoami: {whoami}</pre>
</h1>
</div>
)
}
The code inside backticks (...
) is pre-evaluated at run time by Node.Js. Also note that all the code inside the backticks should be synchronous.