using babel(and webpack) to make ahead of time render decisions for branched components at build time


wow, that title is long, and i’m not even sure if it’s accurate. i read a lot of words and some of them i know, i hope i know the ones i used in the title.
anyway, moving on, as i explored in a previous post, we can use babel as more than just an esnext => espresent? compiler. here we’ll take a look at how we can use babel to make certain decisions for us at build time that would normally be deferred to runtime in order to hopefully speed up our applications.
imagine(or at least please try like really hard) that you have some sort of user permission system in your application that restricts access to some parts of your user interface based on permissions, you might wrap that ui in a component like this that restricts access to only those who can edit and shows some other component or nothing to those who can not.
<RequiredPermissions
required={[“can_edit”]}
permissions={this.props.permissions}
notAllowedElement={<Error />}
>
<textarea onChange={() => {}}>
{this.props.content}
</textarea>
</RequiredPermissions>
a lot of applications will have relatively few variants of these permission sets, you might have administrators, editors, and viewers for example. in cases like these, we can just build three separate bundles at build time that would move these run time decisions to build time decisions by injecting certain permission sets and using babel to replace the RequiredPermissions component with in this case, either children or notAllowedElement by doing something like this:
Then in our .babelrc
this will allow us to set the permissions for a particular permissions set on process.env.PERMISSIONS and than simply choose the branch and put that directly into the final compiled file instead of the RequiredPermissions component which will need to make the decision on whether or not the user can see something every time at run time.
this does force us to put some tooling around our build system and i haven’t come up with a great idea for that just yet but something like this should work:
the next step in the process would be removing the import everywhere where we were actually able to pre choose a branch but i haven’t quite gotten to that point yet. let me know if you have any ideas or other feedback, thanks for reading and i hope it was least semi interesting or informative.