React

Use React Components in Electron App

Electron is a framework based on Node.js and Chromium that is used to write desktop applications using JavaScript, HTML and CSS. If we want to work together with React and Electron then we need to set up React with ‘create-react-app’ and Electron. But my main concern is to use ‘.jsx’ or react component in Electron app without webpack configuration.

When I made desktop application, I was facing issue to integrate ‘.jsx’ file in it without webpack configuration. As we all know, electron is based on Node.js and files required by node with the extensions .es6, .es, .jsx and .js will be transformed by Babel. So I fixed this issue with Babel because the purpose of Babel is to transpile our js current code to an understandable version of js for the given environment, tool, framework we’re using. In the node environment, Babel does not exist as part of its core APIs, so it needs to be added as an npm package first. And because babel is separated to accommodate different tools, we need to add ‘babel-core’ for the core functionality along with ‘babel-preset-env’ which enables transforms for ES2015+. If we want to run babel without a build step like webpack and run files using babel, we need to register babel into node’s runtime. The require hook will bind itself to node’s require and automatically compile files on at runtime. So we’ll also need to add ‘babel-register’.

Now we can use this by require ‘babel-register’ under '<script>' tag in our html file. I have used following two lines under '<script>' tag in my html file :

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Kav Interactive</title>
  </head>
  <body>
    <div id="root"></div>
    <script>
      require('babel-register')
      require('./main')
    </script>
  </body>
</html>
With this, I am able to use react components without ejecting or without webpack configuration.

Author

Harpreet Kaur