In the previous part i showed how it is easy to add npm dependencies to the project and suggest a draft of the simple but containing everything necessary webpack.config.js and have your project under the full control.

Now let’s move to the hello world application with the hot reloading. To have the hot reload working is vital for the fast developing but there are many things to be broken, so let’s be careful from the very beginning.

Webpack will bundle js conde in the single big script to be included into the HTML code, but where the HTML code would come from? It is possible to hardcode it manually or generate automatically. In the first case there will be a problem to change src= attribute of the script tag everytime webpack generates new bundle with the new name (it is necessary to avoid caching obsolete code). Autogenerated HTML solves this problem and brings a risk of the unexpected delay if someday we would face a requirement to add something to the html.

Because of that we use semi-automated approach generating the index.html from src/index.ejs template with html-webpack-plugin.

The minimal set of the react project files contains src/index.jsx and src/components/app.jsx.

Starter src/components/app.jsx it trivial:

src/index.jsx seems to be a bit magic due to hot-loading, but nevertheless the most important line is module.hot.accept(()... – pay attention module.hot.accept does not accept any arguments, this enforces re-rendering of the page on any module change. With this hack we avoid unexpected stopping hot-reloading even with the console messages some modules should not/can not be hot reloaded.

Now

will create the directory dist with index.html and js bundle and

will start development web server
listening on the port 8081 and watching for files to change. As soon as any file will be changed the development server will notify react application (via websocket) it should reload either the page or try to do hot-reload.

Categories: Development

Leave a Reply

Your email address will not be published. Required fields are marked *