Electron js react typescript

Start a new Electron app with React and Typescript.

Electron is a framework for creating native applications. It’s open-source and cross-platform. If you already know Javascript, HTML, and CSS you can build an application with electron. In this tutorial, I’ll show you how to start an electron project from scratch using webpack, react, and Typescript.

Start with Electron.

mkdir electron-react-ts cd electron-react-ts npm init -y 
npm install --save-dev electron \ webpack webpack-cli webpack-dev-server \ babel-loader @babel/core @babel/preset-env \ @babel/preset-react @babel/preset-typescript 

Create a tsconfig.json file. This allows you to specify the configuration for the typescript compiler.

 "compilerOptions":  "target": "es5", "module": "commonjs", "lib": [ "dom", "es2015", "es2016", "es2017" ], "allowJs": true, "jsx": "react", "sourceMap": true, "outDir": "./dist", "strict": true, "esModuleInterop": true, > > 
module.exports =  presets: [ '@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript' ] > 
 lang="en">  charset="UTF-8">  name="viewport" content="width=device-width, initial-scale=1.0"> New Electron App   

Let’s create a new file called webpack.electron.config.js on the root of our app. This webpack file will compile our electron app into a dist folder.

const path = require('path'); module.exports =  resolve:  extensions: ['.tsx', '.ts', '.js'], >, devtool: 'source-map', entry: './electron/main.ts', target: 'electron-main', module:  rules: [  test: /\.(js|ts|tsx)$/, exclude: /node_modules/, use:  loader: 'babel-loader', >, >, ], >, output:  path: path.resolve(__dirname, './dist'), filename: '[name].js', >, >; 

This looks like a normal webpack configuration for typescript, except for the target. The target is the specific environment that webpack will compile for. In this case it’s electron-main . Create an electron folder, then inside a main.ts file with the following code.
This file should create windows and handle the systems events for your app.

import  app, BrowserWindow > from 'electron'; import * as path from 'path'; import * as url from 'url'; let mainWindow: Electron.BrowserWindow | null; function createWindow()  mainWindow = new BrowserWindow( width: 800, height: 600, webPreferences:  nodeIntegration: true, >, >); if (process.env.NODE_ENV === 'development')  mainWindow.loadURL(`http://localhost:4000`); > else  mainWindow.loadURL( url.format( pathname: path.join(__dirname, '../index.html'), protocol: 'file:', slashes: true >) ); > mainWindow.on('closed', () =>  mainWindow = null; >); > app.on('ready', createWindow); app.allowRendererProcessReuse = true; 

The BrowserWindow module will create a new window and render our react app. Now let’s add a script in the package.json file in order to run electron. Also, we have to change the main field for the path that has our electron app compiled.

 "main": "./dist/main.js", "scripts":  "dev:electron": "NODE_ENV=development webpack --config webpack.electron.config.js --mode development && electron ." >, > 

Now run npm run dev:electron in the console. Note: If you are using Windows, chances are you’ll face an error, this is because NODE_ENV is not recognized as a command. You have to install crossenv and place the command before NODE_ENV .

Add a React app.

Now that we have our electron app running, let’s set up a react app to run within this electron context. We need to install a few dependencies.

npm install react react-dom @types/react @types/react-dom npm install --save-dev html-webpack-plugin 
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports =  resolve:  extensions: ['.tsx', '.ts', '.js'], mainFields: ['main', 'module', 'browser'], >, entry: './src/app.tsx', target: 'electron-renderer', devtool: 'source-map', module:  rules: [  test: /\.(js|ts|tsx)$/, exclude: /node_modules/, use:  loader: 'babel-loader', >, >, ], >, devServer:  contentBase: path.join(__dirname, '../dist/renderer'), historyApiFallback: true, compress: true, hot: true, port: 4000, publicPath: '/', >, output:  path: path.resolve(__dirname, '../dist/renderer'), filename: 'js/[name].js', publicPath: './', >, plugins: [ new HtmlWebpackPlugin(), ], >; 
 "main": "./dist/main.js", "scripts":  "dev:electron": "NODE_ENV=development webpack --config webpack.electron.config.js --mode development && electron .", "dev:react": "NODE_ENV=development webpack-dev-server --config webpack.react.config.js --mode development" >, > 
import React from 'react'; import ReactDom from 'react-dom'; const mainElement = document.createElement('div'); document.body.appendChild(mainElement); const App = () =>  return ( h1> Hi from a react app h1> ) > ReactDom.render(App />, mainElement); 

Electron app

Now we are ready.
Run npm run dev:react in one console, and npm run dev: electron on other one. Check this repo for the code.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Electron boilerplate with React, Redux, and TypeScript

License

Robinfr/electron-react-typescript

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A Boilerplate for an Easy Start with TypeScript, React, and Electron.

React Webpack TypeScript Electron Redux Jest

Electron application boilerplate based on React, Redux, and Webpack for rapid application development using TypeScript.

Clone the repository with Git:

git clone --depth=1 git@github.com:Robinfr/electron-react-typescript.git your-project-name>

And then install the dependencies:

cd your-project-name> npm install

Both processes have to be started simultaneously in different console tabs:

npm run start-renderer-dev npm run start-main-dev

This will start the application with hot-reload so you can instantly start developing your application.

You can also run do the following to start both in a single process:

We use Electron builder to build and package the application. By default you can run the following to package for your current platform:

This will create a installer for your platform in the releases folder.

You can make builds for specific platforms (or multiple platforms) by using the options found here. E.g. building for all platforms (Windows, Mac, Linux):

This project comes with both Husky and Prettier setup to ensure a consistent code style.

To change the code style, you can change the configuration in .prettierrc .

In case you want to get rid of this, you can removing the following from package.json :

  1. Remove precommit from the scripts section
  2. Remove the lint-staged section
  3. Remove lint-staged , prettier , eslint-config-prettier , and husky from the devDependencies

Also remove all mentions of Prettier from the extends section in .eslintrc.json .

This project was set up from scratch but is heavily influenced by the Electron React Boilerplate project and React Redux TypeScript guide.

Источник

Setting Electron + React with Typescript

We will create a file to setup the webpack configs for electron, for that create webpack.electron.js in the root folder:

const path = require('path'); module.exports =  // Build Mode mode: 'development', // Electron Entrypoint entry: './src/main.ts', target: 'electron-main', resolve:  alias:  ['@']: path.resolve(__dirname, 'src') >, extensions: ['.tsx', '.ts', '.js'], >, module:  rules: [ test: /\.ts$/, include: /src/, use: [ loader: 'ts-loader' >] >] >, output:  path: __dirname + '/dist', filename: 'main.js' > > 

Let me explain what this code does.

resolve:  alias:  ['@']: path.resolve(__dirname, 'src') >, extensions: ['.tsx', '.ts', '.js'], >, 

Now create the webpack.config.js in the root folder, this will consume all necessary configs for our webpack:

const electronConfigs = require('./webpack.electron.js'); module.exports = [ electronConfigs ]; 

From now on don’t need to navigate folder with ‘../../’, we can use ‘@’ as a starting point in the src folder.

// Lets import from ./src/services/service1.ts import Service1 from '../../services/service1'; 
// Lets import from ./src/services/service1.ts import stuff from '@/services/service1'; 

Now update npm script in package.json :

"scripts":  "build": "webpack", "start": "npm run build && electron dist/main.js" > 

React Setup

For our renderer we will install React and all dependencies necessary for typescript.

npm install --save-dev react react-dom @types/react @types/react-dom 

Create the react entrypoint as renderer.ts :

import React from 'react'; import ReactDOM from 'react-dom'; import App from '@/app/app'; ReactDOM.render(App />, document.getElementById('root')); 

As you can see we are importing the App Component, but we don’t have it yet, let code it!

import React from 'react'; const App = () =>  return ( div className="app"> h1>I'm React running in Electron App!!h1> div> ); > export default App; 

Do you remember the tsconfig.json file? 🤔 Let´s add two options to it:

 "compilerOptions":  . "jsx": "react", "baseUrl": "./", "paths":  "@/*": [ "src/*" ] >, > > 

Now setup the Webpack configuration for React, like we did for electron, we need to create a specific config file for react in the root folder:

const HtmlWebpackPlugin = require('html-webpack-plugin'); const path = require('path'); module.exports =  mode: 'development', entry: './src/renderer.tsx', target: 'electron-renderer', devtool: 'source-map', devServer:  contentBase: path.join(__dirname, 'dist/renderer.js'), compress: true, port: 9000 >, resolve:  alias:  ['@']: path.resolve(__dirname, 'src') >, extensions: ['.tsx', '.ts', '.js'], >, module:  rules: [  test: /\.ts(x?)$/, include: /src/, use: [ loader: 'ts-loader' >] >,  test: /\.s[ac]ss$/i, use: [ 'style-loader', 'css-loader', 'sass-loader', ], > ] >, output:  path: __dirname + '/dist', filename: 'renderer.js' >, plugins: [ new HtmlWebpackPlugin( template: './src/index.html' >) ] >; 

And update the webpack.config.js :

const electronConfigs = require('./webpack.electron.js'); const reactConfigs = require('./webpack.react.js'); module.exports = [ electronConfigs, reactConfigs ]; 

Hot Reload Setup (Optional)

To avoid running the build whenever we make any changes we will add Hot Reload, for that we need to install the following packages:

npm install nodemon webpack-dev-server electron-is-dev concurrently --save-dev 

First we will setup the Electron Hot Reload, for that we need to create a nodemon.json file in the root, and add the following settings:

 "watch": [ "src/main.ts", "src/electron/*" ], "exec": "webpack --config ./webpack.electron.js && electron ./dist/main.js", "ext": "ts" > 

Now for React we need to update Webpack Configuration:

. module.exports =  . devServer:  contentBase: path.join(__dirname, 'dist/renderer.js'), compress: true, port: 9000 >, . > 

We should update our package.json :

 . "scripts":  "build": "webpack", "react:dev": "webpack serve --mode=development", "electron:dev": "nodemon", "dev": "concurrently --kill-others \"npm run react:dev\" \"npm run electron:dev\"", "start": "npm run build && electron dist/main.js" >, . 

Last thing we should change our main.js :

import  app, BrowserWindow > from 'electron'; import isDev from 'electron-is-dev'; // New Import const createWindow = (): void =>  let win = new BrowserWindow( width: 800, height: 600, webPreferences:  nodeIntegration: true > >); console.log(isDev); win.loadURL( isDev ? 'http://localhost:9000' : `file://$app.getAppPath()>/index.html`, ); > app.on('ready', createWindow); 

SCSS Setup (Optional)

Install dependecies necessary for it:

npm install sass-loader sass style-loader css-loader --save-dev 

Update React Webpack Configuration:

. rules: [ .  test: /\.s[ac]ss$/i, use: [ 'style-loader', 'css-loader', 'sass-loader', ], > ] 

Create you first SCSS file under src/app folder, and update you app.tsx importing it.

import React from 'react'; import 'app.scss'; // New import!! const App = () =>  return ( div className="app"> h1>I'm React running in Electron App!!h1> div> ); > export default App; 

Conclusion of Part 1

Finally, eveything is ready to start our application.
Let’s run it!!

Источник

Читайте также:  Python float убрать нули
Оцените статью