简体   繁体   中英

How to set up Electron with React and TypeScript?

I'm coding an app with Electron, React (jsx) with Babel. I switched to TypeScript this evening and I can't figure out how to make everything work. Npm packets set up either React or TypeScript, but not both, and not with Electron. (I also have to implement webpack.)

My question is: what is the minimal structure of folders, files and packets to make everything work? I just want to display a hello world on the main window using a React component written in TypeScript. Currently, my packets are Electron, React, ReactDOM, TypeScript.

First of all i followed this tutorial on the official Website of Typescript: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html

If you follow every step you will end up with a dist folder that contains a bundle.js (with the bundled code that Webpack receives from Typescript) and a src folder that containes the .tsx files. Typescript supports React out of the box, just add "jsx": "react" to the tsconfig.json and renane your file .tsx instead of .ts . After that add index.js to the root folder(copied from here: https://github.com/electron/electron-quick-start/blob/master/main.js ).

Install electron locally npm install electron --save-dev or globally npm install -g electron

Run webpack with webpack while in the app folder (to generate the ./dist/bundle.js file)

Run electron with electron . while in the app folder

The important thing to notice is the entry point of webpack: its ./src/index.tsx while electron entry point is ./index.js. Electron load index.js that loads index.html that loads ./dist/bundle.js. We can transtale index.js to index.ts but then we would have to change the entry point of webpack.

I made a boiler plate starter pack which contains many bug fixes that are found when using react with electron and typescript and has auto monitoring of typescript changes to reload the electron app for faster development.

https://github.com/nateshmbhat/electron-react-ts-starter/

It works with create-react-app without need for ejecting anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM