React — execute code only during build time (version / timestamp)

Prawira G.
1 min readJun 2, 2020

A method to execute a piece of code only during build time.

PROBLEM

Do you want to include a segment of code that should only be executed during build time of a Create React App (CRA) environment? For instance, version control or even timestamp which the CRA is bundled.

In this article, I will refer to external libraries — preval.macro.

SOLUTION

Install the following node modules.

npm install --save-dev preval.macro

To use the module, the following structure has to be followed.

import preval from 'preval.macro'

const one = preval`module.exports = ANY_JAVASCRIPT_CODE`;

module.exports is the keyword of importing a node js module prior to ES6. Hence, you can write simple / complex code without any restriction.

The following is an example of printing timestamp when the code is bundled so it can be used as version control.

CONCLUSION

This method is extremely useful not only when generating a constant value to be consumed by clients, it is also useful in executing code that are computational heavy (as this is executed in the server during build time). However, note that the value is only generated once and will only be generated the next time CRA is re-bundled.

--

--

Prawira G.

Full Stack TypeScript | Blockchain Enthusiast | OAUTH2.0 & OIDC | Software Engineer.