In this post I will demonstrate how to use Webpack to bundle React jsx files into regular JavaScript code.
A great thing about Webpack is that it allows us to seamlessly automate the jsx conversion, but we can also tell it to refresh the browser to reflect component changes on the page immediately.
I will be using the following React component consisting of two jsx files.
MessageComponent.jsx
index.jsx
As you can tell I am using CommonJS to import the message component into the jsx file where the rendering is initiated.
I will be relying on npm to add the necessary dependencies, so to get the general setup you may use the following package.json file:
Package.json defines all dependencies, but it also defines tasks for creating the JavaScript bundle.
Under scripts I have added a start task that allows us to start two simple web servers for development – one for running the test page and a second one for serving/refreshing the JavaScript bundle realtime.
The final configuration step is to create a webpack.config.js file to tell Webpack how to do the jsx conversion.
Lastly we have to add a sample html page to test the component.
As you can tell the script reference to the JavaScript bundle comes in two flavors:
Development
During development the bundle is recreated automatically as you are editing the jsx files. In fact it will even refresh the page to instantly reflect the new JavaScript file.To launch the test page in development mode use: npm run start
Production
Production files will be static and included using traditional script tags (shown commented out in the sample above).To trigger a static build of your bundle use: npm run build