This is something that I needed to do recently and I was surprised by how hard I found it to find information on it. A few hours of doubting my ability as a developer and 20+ browser tabs later I discovered that it actually is relatively straight forward using webpack and babel.

TL;DR — use this github project as a template to bundle the component

The aim:

Friends of mine had created a really cool React component, Chat-Template, a configurable component that simulates instant message conversations. I wanted to make this component easily consumable for non-react websites as well.

Chat-Template in action on http://mrwgame.com

The approach:

One thing that was clear from the start is that in order to make the component consumable, I was going to need to package it up webpack.

Webpack takes modules with dependencies and generates static assets representing those modules

A lot of the examples I seen involved the consumer of the webpacked component including react.js on their webpage, this is something I wanted to avoid. I wanted the consumers of the component to not even need to know what React is! (Maybe they’re living under a rock?)

I wrote a node script to wrap the component. It included the component, React and ReactDom and exported a method to display it on a given dom element

Node script to wrap the component

As this code was to be consumed by browsers, I use babel to ensure the best compatibly. Babel is basically a javascript code compiler that converts EC6 javascript code to the much more widely compatible EC5

I now needed to configure webpack. One thing that was needed was to make the method a global variable, so the showChatTemplate function was available, this was done using the libraryTarget and library configurations. The webpack config looked like this

I now had a single javascript file that included everything the consumer needed and could be easily added to a web page.

Perfect! Except at 1.08MB, the generated file was a little on the large side! After running webpack with the -p flag and adding some configuration to make sure the production version of react was being used, the file size shrunk down to a much more manageable 0.283MB

Conclusion:

That’s how I was able to consume a React component in a non-React website. We’ve now added the generated files to Chat-Template so non-React users have the component available to them.

If you are interested in doing the same, use this github project as a starting point to wrap whatever component you want.

If you have any questions or suggestions I would love to hear them.