How to import Electron in angular 2 using angular cli

喜欢而已 提交于 2019-12-06 00:46:02
chaouechi souhail

Run the command npm install electron @types/electron Then import it normally using

import { ipcRenderer } from 'electron'.

If you run into any problems, try to run npm eject, a webpack.config.js will be generated, add "target": "electron-renderer" at the top of module.exports

Set this in index.html

<script>
var electron=require("electron");
</script>

Add this line in typings.d.ts file

declare var electron: any;

Use inside the component like this example:

const {ipcRenderer, clipboard} = electron;
clipboard.writeText('Electron is ready!!');

I tried to work with angular-cli and Electron and was not able to make them to work together. It's the reason why I started the following project: https://github.com/osechet/angular-tour-of-heroes-webpack It integrates Angular 2 with webpack and Electron. It's based on the Angular 2 tutorial (with unit tests). When running Electron in dev mode (npm run start.desktop), it livereloads the sources.

To complete the answer given by chaouechi souhail.

As I understand his answer aims to solve the situation where the angular app is directly embedded in the electron app. If for some reason you are using two separate projects whereof one is the electron app which embeds the other as a web app using one of electron's webview components you might find the following approach helpful aswell.

  1. In your electron app you'll have something like

<webview id="webview" src="http://localhost:4200/" nodeintegration></webview>

  1. In your angular project you

    1. install the electron nodejs module, ie npm install electron . The types module mentioned by chaouechi might suffice, I do not know.
    2. you eject the webpack config through ng eject
    3. in webpack's config (webpack.config.js) you define electron as an external module such that webpack does not attempt to build it into the ng app, extend the exports as below

    module.exports = { //... externals: { electron: "require('electron')", // tell's webpack how to import the electron module within your angular app after being packed //... }, //... }

    1. Now, in your ng components, it should be possible to include electron classes as follows: import { remote } from "electron";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!