背景・目的
Electronを触る機会があったので、基本的な内容を整理し、簡単に動作を確認してみます。
まとめ
下記に特徴を整理します。
特徴 | 説明 |
---|---|
Electronとは | デスクトップアプリケーションを構築するフレームワーク |
使用されている技術 | ・JavaScript ・HTML ・CSS |
クロスプラットフォーム | 下記で動作可能 ・Windows ・macOS ・Linux |
ライセンス | MITライセンス |
Webテクノロジーが優れている点 | ・Versatility ・Reliability ・Interoperability ・Ubiquity |
Electronが優れている点 | ・Enterprise-grade ・Mature ・Stability, security, performance |
Electronが向かないと思われる点 | ・Resource-Constrained Environments and IoT ・Small Disk Footprint ・Operating System UI Frameworks and Libraries ・Games and Real-Time Graphics ・Embedding Lightweight Websites |
概要
下記のドキュメントを基に整理します。
What is Electron?
Electron は、JavaScript、HTML、CSS によるデスクトップアプリケーションを構築するフレームワークです。 Electron は Chromium と Node.js をバイナリに組み込むことで、単一の JavaScript コードベースを維持しつつ、ネイテイブ開発経験無しでも Windows、macOS、Linux で動作するクロスプラットフォームアプリを作成できます。
- Electronは、デスクトップアプリケーションを構築するフレームワーク
- 下記の技術を使用している
- JavaScript
- HTML
- CSS
- 下記をバイナリに組み込む
- Chromium
- Node.js
- JavaScriptコードベースを維持
- クロスプラットフォームで動作する
- Windows
- macOS
- Linux
Why Electron
Electron is a framework enabling developers to build cross-platform desktop applications for macOS, Windows, and Linux by combining web technologies (HTML, JavaScript, CSS) with Node.js and native code. It is open-source, MIT-licensed, and free for both commercial and personal use. In this document, we’ll explain why companies and developers choose Electron.
- OSS
- MITラインセンス
Why choose web technologies
Web technologies include HTML, CSS, JavaScript, and WebAssembly. They’re the storefront of the modern Internet. Those technologies have emerged as the best choice for building user interfaces — both for consumer applications as well as mission-critical business applications. This is true both for applications that need to run in a browser as well as desktop applications that are not accessible from a browser. Our bold claim here is that this isn’t just true for cross-platform applications that need to run on multiple operating systems but true overall.
As an example, NASA’s actual Mission Control is written with web technologies. The Bloomberg Terminal, the computer system found at every financial institution, is written with web technologies and runs inside Chromium. It costs $25,000 per user, per year. The McDonald’s ordering kiosk, powering the world’s biggest food retailer, is entirely built with Chromium. The SpaceX’s Dragon 2 space capsule uses Chromium to display its interface. You get the point: web technologies are a great tech stack to build user interfaces.
Here are the reasons we, the Electron maintainers, are betting on the web.
- 現代のWebテクノロジーは下記の技術が最良として選択されている
- HTML
- CSS
- JavaScript
- WebAssembly
- 上記はブラウザ、デスクトップに当てはまる
- クロスプラットフォームに限らない
Versatility
Modern versions of HTML and CSS enable your developers and designers to fully express themselves. The web’s showcase includes Google Earth, Netflix, Spotify, Gmail, Facebook, Airbnb, or GitHub. Whatever interface your application needs, you will be able to express it with HTML, CSS, and JavaScript.
If you want to focus on building a great product without figuring out how you can realize your designer’s vision in a specific UI framework, the web is a safe bet.
- アプリケーションに必要なインターフェースは何でも、HTML、CSS、JavaScriptで表現できる
- 優れた製品の構築に集中したい場合は、Web が安全な選択肢
Reliability
Web technologies are the most-used foundation for user interfaces on the planet. The have been hardened accordingly. Modern computers have been optimized from the CPU to the operating system to be good at running web technologies. The manufacturers of your user’s devices—be that an Android phone or the latest MacBook—will ensure that they can visit websites, play videos on YouTube, or display emails. In turn, they’ll also ensure that your app has a stable foundation, even if you have just one user.
If you want to focus on building a great product without debugging a weird quirk that nobody has found before, the web is a safe bet.
- Webテクノロジーは堅牢性が高い
- 優れた製品の開発に集中したいのであれば、Webは確実な選択肢
Interoperability
Whatever provider or customer data you need to interact with, they will have probably thought of an integration path with the web. Depending on your technology choice, embedding a YouTube video either takes 30 seconds or requires you to hire a team devoted to streaming and hardware-accelerated video decoding. In the case of YouTube, using anything other than the provided players is actually against their terms and conditions, so you’ll likely embed a browser frame before you implement your own video streaming decoder.
There will be virtually no platform where your app cannot run if you build it with web technologies. Virtually all devices with a display—be that an ATM, a car infotainment system, a smart TV, a fridge, or a Nintendo Switch—come with means to display web technologies. The web is safe bet if you want to be cross-platform.
- Webテクノロジーを使用してアプリを構築することで、動作しないプラットフォームはほぼない
Ubiquity
It’s easy to find developers with experience building with web technologies. If you’re a developer, it’ll be easy to find answers to your questions on Google, Stack Overflow, GitHub, or a coding AI of your choice. Whatever problem you need to solve, it’s likely that somebody has solved it well before—and that you can find the answer to the puzzle online.
If you want to focus on building a great product with ample access to resources and materials, the web is a safe bet.
- 開発者が多く、ドキュンとなどのリソースが多い
Why choose Electron
Electron combines Chromium, Node.js, and the ability to write custom native code into one framework for building powerful desktop applications. There are three main reasons to use Electron:
- 下記を1つのフレームワークに統合
- Chromium
- Node.js
- カスタムネイティブコードの記述機能
- 強力なデスクトップアプリケーションを構築する
Enterprise-grade
Electron is reliable, secure, stable, and mature. It is the premier choice for companies building their flagship product. We have a list of some of those companies on our homepage, but just among chat apps, Slack, Discord, and Skype are built with Electron. Among AI applications, both OpenAI’s ChatGPT and Anthropic’s Claude use Electron. Visual Studio Code, Loom, Canva, Notion, Docker, and countless other leading developers of software bet on Electron.
- 下記の点で優れている
- 信頼性
- セキュリティ
- 安定性
- 成熟
We did make it a priority to make Electron easy to work with and a delight for developers. That’s likely the main reason why Electron became as popular as it is today — but what keeps Electron alive and thriving is the maintainer’s focus on making Electron as stable, secure, performant, and capable of mission-critical use cases for end users as possible. We’re building an Electron that is ready to be used in scenarios where unfixable bugs, unpatched security holes, and outages of any kind are worst-case scenarios.
- Electronを使いやすく、開発者にとって喜びとなることを最優先事項としてきた
- 下記の状況でも使用できるElectronを構築している
- 修正不可能なバグ
- パッチ未適用のセキュリティホール
- あらゆる種類の機能停止
Mature
Our current estimation is that most desktop computers on the planet run at least one Electron app. Electron has grown by prioritizing talent in its maintainer group, fostering excellent and sustainable engineering practices in managing the ongoing maintenance, and proactively inviting companies betting on Electron to directly contribute to the project. We’re an impact project with the OpenJS foundation, which is itself a part of the Linux foundation. We share resources and expertise with other foundation projects like Node.js, ESLint, Webpack - or the Linux Kernel or Kubernetes.
- Linux Foundationの一部であるOpenJS Foundationの影響力のあるプロジェクト
- Node.js、ESLint、Webpack、そしてLinuxカーネルやKubernetesといった他のFoundationプロジェクトとリソースと専門知識を共有している
What does all of that mean for you, a developer, in practice?
- Reliable release schedule: Electron will release a new major version in lockstep with every second major Chromium release, usually on the same day as Chromium. A lot of work, both in the form of building processes and tools, but also in terms of raw invested hours every week, has to go into making that happen.
- No dictators: Sometimes, betting on a technology also requires you to bet on a single person or company. In turn, it requires you to trust that the person or company never has a breakdown, starts fighting you directly, or does anything else drastic that’ll force you rethink your entire tech stack. Electron is maintained by a diverse set of companies (Microsoft, Slack/Salesforce, Notion, and more) and will continue to welcome more companies interested in ensuring their “seat at the decision-making table”.
- 信頼性の高いリリーススケジュール
- Electron は、Chromium の2回目のメジャーリリースと同期して、通常は Chromium と同日に新しいメジャーバージョンをリリースする
- 独裁者はいない
- Electron は、Microsoft、Slack/Salesforce、Notion など、多様な企業によってメンテナンスされている
Stability, security, performance
Electron delivers the best experience on all target platforms (macOS, Windows, Linux) by bundling the latest version of Chromium, V8, and Node.js directly with the application binary. When it comes to running and rendering web content with upmost stability, security, and performance, we currently believe that stack to be “best in class”.
- Electronは、最新バージョンのChromium、V8、Node.jsをアプリケーションバイナリに直接バンドルする
- ターゲットプラットフォーム(macOS、Windows、Linux)で最高のエクスペリエンスを提供する
- でWebコンテンツを実行・レンダリングする点においてクラス最高(と言っている)
- 最高の安定性
- セキュリティ
- パフォーマンス
Why bundle anything at all
You might wonder why we bundle Chromium’s web stack with our apps when most modern operating systems already ship a browser and some form of web view. Bundling doesn’t just increase the amount of work for Electron maintainers dramatically, it also increases the total disk size of Electron apps (most apps are >100MB). Many Electron maintainers once developed applications that did make use of embedded web views — and have since accepted the increased disk size and maintainer work as a worthy trade-off.
When using an operating system's built-in web view, you're limited by the browser version included in the oldest operating system version you need to support. We have found the following problems with this approach:
-
最近のほとんどのOSが既にブラウザと何らかのウェブビューを同梱している
-
Electronでは、Chromiumのウェブスタックをアプリにバンドルしているか
- バンドルは、Electronメンテナーの作業量を大幅に増やし、Electronアプリのディスクサイズも増加させる
- ほとんどのアプリは100MBを超える
- バンドルは、Electronメンテナーの作業量を大幅に増やし、Electronアプリのディスクサイズも増加させる
-
多くのElectronメンテナーは組み込みウェブビューを活用したアプリケーションを開発していましたが、今では、ディスクサイズの増加とメンテナーの作業負担を、妥当なトレードオフとして受け入れている
-
オペレーティングシステムに組み込まれたウェブビューを使用する場合、サポートが必要な最も古いオペレーティングシステムのバージョンに含まれるブラウザのバージョンに制限される
-
このアプローチには、以下の問題がある
- Stability
- Security
- Performance
Stability: The modern web technology stack is complex, and as a result, you’ll sooner or later encounter bugs. If you use the operating system’s web view, your only recourse will be to ask your customers to upgrade their operating system. If no upgrade is available for that machine (because of no ability to upgrade to the latest macOS or Windows 11), you’ll have to ask them to buy a new computer. If you’re unlucky, you’re now losing a major customer because they will not upgrade their entire fleet of thousands of machines just because one team wanted to try your startup’s app. You have no recourse in this situation. Even the risk of that happening is unacceptable to the companies that employ the Electron maintainers.
- 現代のWebテクノロジースタックは複雑。そのため遅かれ早かれバグに遭遇する
- オペレーティングシステムのWebビューを使用する場合、唯一の解決策は顧客にオペレーティングシステムのアップグレードを依頼すること
- そのマシンでアップグレードが利用できない場合(最新のmacOSまたはWindows 11にアップグレードできないため)、新しいコンピュータの購入を依頼する必要がある
- 運が悪ければ、あるチームがあなたのスタートアップのアプリを試したいという理由だけで、数千台に及ぶマシン群全体をアップグレードしないため、主要顧客を失う
- このような状況では、解決策がない
- Electronのメンテナーを雇用している企業にとって、そのようなリスクさえも受け入れがたい
Security: Similar to how you can fix stability bugs by releasing an app update, you can also release security fixes to your application without asking your customer to upgrade their operating system. Even if operating system providers prioritize updates to their built-in browser, we have not seen them reliably update the built-in web views with similar urgency. Bundling a web renderer gives you, the developer, control.
- アプリのアップデートをリリースすることで安定性に関するバグを修正できるのと同様に、ユーザーにOSのアップグレードを依頼することなく、アプリケーションのセキュリティ修正をリリースすることも可能
- OSプロバイダーは組み込みブラウザのアップデートを優先しているが、組み込みウェブビューを同様の緊急性で確実にアップデートしているとは考えられていない
- ウェブレンダラーをバンドルすることで、開発者は制御できるようになる
Performance: For simple HTML documents, a built-in web view will sometimes use fewer resources than an app with a bundled framework. For bigger apps, it is our experience that we can deliver better performance with the latest version of Chromium than we can with built-in web views. You might think that the built-in view can share a lot of resources with other apps and the operating system— but for security reasons, apps have to run in their own sandboxes, isolated from each other. At that point, the question is whether the OS’ web view is more performant than Chromium. Across many apps, our experience is that bundling Chromium and Node.js enables us to build better and more performant experiences.
- シンプルなHTMLドキュメントの場合、組み込みウェブビューは、バンドルされたフレームワークを備えたアプリよりもリソース使用量が少ない場合がある
- 大規模なアプリの場合、最新バージョンのChromiumを使用した方が、組み込みウェブビューよりも優れたパフォーマンスを実現できる
- 組み込みビューはセキュリティ上の理由から、アプリは互いに分離された独自のサンドボックス内で実行する必要がある
- その場合、OSのウェブビューの方がChromiumよりもパフォーマンスが高いかどうかが問題になる
- 多くのアプリにおいて、経験上、ChromiumとNode.jsをバンドルすることで、より優れたパフォーマンスのエクスペリエンスを構築できる
Why bundle Chromium and Node.js
Electron aims to enable the apps it supports to deliver the best possible user experience, followed by the best possible developer experience. Chromium is currently the best cross-platform rendering stack available. Node.js uses Chromium’s JavaScript engine V8, allowing us to combine the powers of both.
- Chromiumは現在、利用可能な最高のクロスプラットフォームレンダリングスタック
- Node.jsはChromiumのJavaScriptエンジンV8を使用しているため、両方のパワーを組み合わせることができる
- Native code when you want it: Thanks to Node.js’ mature native addon system, you can always write native code. There is no system API out of reach for you. Whatever macOS, Windows, or Linux feature you’ll want to integrate with —as long as you can do it in C, C++, Objective-C, Rust, or another native language, you’ll be able to do it in Electron. Again, this gives you, the developer, maximum control. With Electron, you can use web technologies without choosing only web technologies.
- Node.jsの成熟したネイティブアドオンシステムでいつでもネイティブコードを書くことができる
- 使えないシステムAPIはない
- macOS、Windows、Linuxのどんな機能と連携させたいとしても、C、C++、Objective-C、Rust、その他のネイティブ言語で記述できる限り、Electronで実現できる。これにより開発者は最大限の制御が可能になる
- Electronを使えば、Web技術だけに限定することなく、様々なWeb技術を活用できる
Developer experience
To summarize, we aim to build an Electron that is mature, enterprise-grade, and ready for mission-critical applications. We prioritize reliability, stability, security, and performance. That said, you might also choose Electron for its developer experience:
- 成熟したエンタープライズグレードの、ミッションクリティカルなアプリケーションに対応できるElectronの構築を目指している。信頼性、安定性、セキュリティ、そしてパフォーマンスを最優先に考えてる
- 上記のほか、開発者エクスペリエンスという点でもElectronを選択できる
- Powerful ecosystem: Anything you find on npm will run inside Electron. Any resource available to you about how to work with Node.js also applies to Electron. In addition, Electron itself has a thriving ecosystem — including plenty of choices for installers, updaters, deeper operating system-integration, and more.
- 強力なエコシステム
- npmで見つけたものはすべてElectron内で動作する
- Node.jsの使い方に関するリソースはすべてElectronにも適用できる
- Electron自体にも活気のあるエコシステムがあり、インストーラー、アップデーター、OSとのより緊密な統合など、豊富な選択肢が用意されてる
- Plenty of built-in capabilities: Over the last ten years, Electron’s core has gained plenty of native capabilities that you might need to build your application. Written in C++ and Objective-C, Electron has dozens of easy-to-use APIs for deeper operating-system integration — like advanced window customization for transparent or oddly shaped widgets, receiving push notifications from the Apple Push Notification Network, or handling a custom URL protocol for your app.
- 豊富な組み込み機能
- C++とObjective-Cで記述されたElectronには、オペレーティングシステムとのより深い統合を可能にする、使いやすいAPIが多数用意されている
- 例えば
- 透明ウィジェットや奇妙な形状のウィジェットのための高度なウィンドウカスタマイズ
- Apple Push Notification Networkからのプッシュ通知の受信
- アプリのカスタムURLプロトコルの処理など
- Open source: The entire stack is open source and open to your inspection. This ensures your freedom to add any feature or fix any bug you might encounter in the future.
- OSS
- スタック全体がオープンソースであり、自由に検証できる
- これにより、将来発生する可能性のある機能の追加やバグの修正を自由に行うことができる
- Native code when you need it: It bears repeating that Electron allows you to mix and match web technologies and C++, C, Objective-C, Rust, and other native languages. Whether it be SQLite, a whole LLM, or just the ability to call one specific native API, Electron will make it easy.
- Native code when you need it
- Electronでは、WebテクノロジーとC++、C、Objective-C、Rustなどのネイティブ言語を自由に組み合わせることができる
- SQLite、LLM全体、あるいは特定のネイティブAPIを呼び出す機能など、Electronなら簡単に実現できる
- Electronでは、WebテクノロジーとC++、C、Objective-C、Rustなどのネイティブ言語を自由に組み合わせることができる
Why choose something else
As outlined above, the web is an amazing platform for building interfaces. That doesn’t mean that we, the maintainers, would build everything with HTML and CSS. Here are some notable exceptions:
- Webはインターフェースを構築するための素晴らしいプラットフォーム
- しかし、メンテナーがすべてをHTMLとCSSで構築するわけではない
- いくつか注目すべき例外を挙げる
- Resource-Constrained Environments and IoT: In scenarios with very limited memory or processing power (say, one megabyte of memory and 100MHz of processing power on a low-powered ARM Cortex-M), you will likely need to use a low-level language to directly talk to the display to output basic text and images. Even on slightly higher-powered single-chip devices you might want to consider an embedded UI framework. A classic example is a smart watch.
- Resource-Constrained Environments and IoT
- メモリや処理能力が非常に限られているシナリオ
- (例えば、低消費電力のARM Cortex-Mでメモリ1MB、処理能力100MHzなど)
- ディスプレイに直接接続して基本的なテキストや画像を出力するには、低水準言語を使用する必要がある
- たとえ、やや高性能なシングルチップデバイスであっても、組み込みUIフレームワークの導入を検討する価値があるかもしれない
- 典型的な例としては、スマートウォッチが挙げられる
- メモリや処理能力が非常に限られているシナリオ
- Small Disk Footprint:Zipped Electron apps are usually around 80 to 100 Megabytes. If a smaller disk footprint is a hard requirement, you’ll have to use something else.
- Small Disk Footprint
- 圧縮されたElectronアプリは通常80~100MB程度
- ディスク容量を小さくする必要がある場合は、他の方法を使用する必要がある
- Operating System UI Frameworks and Libraries: By allowing you to write native code, Electron can do anything a native application can do, including the use of the operating system’s UI components, like WinUI, SwiftUI, or AppKit. In practice, most Electron apps make rare use of that ability. If you want the majority of your app to be built with operating system-provided interface components, you’ll likely be better off building fully native apps for each operating system you’d like to target. It’s not that it’s impossible with Electron, it’ll just likely be an overall easier development process.
- Operating System UI Frameworks and Libraries
- Electronはネイティブコードを記述できるため、WinUI、SwiftUI、AppKitといったオペレーティングシステムのUIコンポーネントの使用を含め、ネイティブアプリケーションで可能なあらゆることが可能
- しかし実際には、ほとんどのElectronアプリはこの機能をほとんど使用していない
- アプリの大部分をオペレーティングシステムが提供するインターフェースコンポーネントで構築したい場合は、ターゲットとするオペレーティングシステムごとに完全にネイティブなアプリを構築する方が賢明
- Electronで不可能というわけではありませんが、開発プロセス全体が簡素化される可能性がある
- Electronはネイティブコードを記述できるため、WinUI、SwiftUI、AppKitといったオペレーティングシステムのUIコンポーネントの使用を含め、ネイティブアプリケーションで可能なあらゆることが可能
- Games and Real-Time Graphics: If you're building a high-performance game or application requiring complex real-time 3D graphics, native frameworks like Unity, Unreal Engine, or DirectX/OpenGL will provide better performance and more direct access to graphics hardware. Web fans might point out caveats, like the fact that even Unreal Engine ships with Chromium — or that WebGPU and WebGL are developing rapidly and many game engines, including the ones listed here, can now output their games in a format that runs in a browser. That said, if you asked us to build the next AAA game, we’d likely use something else than just web technologies.
- Games and Real-Time Graphics
- 複雑なリアルタイム3Dグラフィックスを必要とする高性能ゲームやアプリケーションを開発する場合に下記のネイティブフレームワークを利用することで、より優れたパフォーマンスとグラフィックスHWへのより直接的なアクセスが得られる
- Unity
- Unreal Engine
- DirectX/OpenGLなど
- 複雑なリアルタイム3Dグラフィックスを必要とする高性能ゲームやアプリケーションを開発する場合に下記のネイティブフレームワークを利用することで、より優れたパフォーマンスとグラフィックスHWへのより直接的なアクセスが得られる
- Embedding Lightweight Websites: Electron apps typically are mostly web apps with native code sprinkled in where useful. Processing-heavy Electron applications tend to write the UI in HTML/CSS and build the backend in Rust, C++, or another native language. If you’re planning to build a primarily native application that also wants to display a little website in a specific view, you might be better off using the OS-provided web view or something like ultralight.
- Embedding Lightweight Websites
- Electronアプリは一般的に、必要な箇所にネイティブコードを散りばめたWebアプリがほとんど
- 処理負荷の高いElectronアプリは、UIをHTML/CSSで記述し、バックエンドをRust、C++、またはその他のネイティブ言語で構築する傾向がある
- 主にネイティブアプリで、特定のビューに小さなウェブサイトを表示するようなアプリケーションを開発する場合は、OS付属のWebビューやUltralightのようなツールを使用する方がよい
実践
下記を基に試します。
Electron Forgeでパッケージ、ユーザ配布まで試す。
前提
今回、下記の環境を利用しています
- Node.jsが前提
- Cursor
- Mac
準備
- リポジトリを作成します
% gh repo create electron-example --public --clone ✓ Created repository XXXXXX/electron-example on GitHub https://github.com/XXXXXX/electron-example %
- Cursorを開きます
- 上記で作成したフォルダをワークスペースに追加します
初めてのアプリのビルド
プロジェクトのセットアップ
-
npm init
を実行します% cd electron-example % npm init This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. See `npm help init` for definitive documentation on these fields and exactly what they do. Use `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. package name: (electron-example) version: (1.0.0) description: entry point: (index.js) main.js test command: git repository: keywords: author: license: (ISC) About to write to /Users/XXXXX/XXXXX/cursor/electron-example/package.json: { "name": "electron-example", "version": "1.0.0", "main": "main.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "description": "" } Is this OK? (yes) yes npm notice npm notice New major version of npm available! 10.8.2 -> 11.3.0 npm notice Changelog: https://github.com/npm/cli/releases/tag/v11.3.0 npm notice To update run: npm install -g npm@11.3.0 npm notice %
- パッケージを初期化してElectronをインストールします
% npm install electron --save-dev npm warn deprecated boolean@3.2.0: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. added 70 packages, and audited 71 packages in 25s 17 packages are looking for funding run `npm fund` for details found 0 vulnerabilities %
- package.jsonは下記のようになります
{ "name": "electron-example", "version": "1.0.0", "main": "main.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "description": "", "devDependencies": { "electron": "^35.1.5" } }
-
こちらを基に
.gitignore
を追加します
Electronアプリの実行
- main.jsを作成します
console.log("Hello from Electron!");
- package.jsonのscriptsフィールド内にstartコマンドとして、
electron .
を追加します{ "name": "electron-example", "version": "1.0.0", "main": "main.js", "scripts": { "start": "electron .", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "description": "", "devDependencies": { "electron": "^35.1.5" } }
- 実行します
% npm run start > electron-example@1.0.0 start > electron . Hello from Electron!
ウェブページを BrowserWindow で読み込む
Electronでは、各ウィンドウにWebページが表示され、ローカルのHTMLファイルまたは、リモートのウェブから読み込まれる。今回は、ローカルファイルを読み込みます。
-
index.htmlを作成します
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP --> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'" /> <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'" /> <title>Hello from Electron renderer!</title> </head> <body> <h1>Hello from Electron renderer!</h1> <p>👋</p> </body> </html>
-
main.jsファイルの内容を書き換えます
const { app, BrowserWindow } = require('electron') const createWindow = () => { const mainWindow = new BrowserWindow({ width: 800, height: 600 }) mainWindow.loadFile('index.html') } app.whenReady().then(() => { createWindow() })
-
npm run start
を実行します% npm run start > electron-example@1.0.0 start > electron .
コードの解説
モジュールのインポート
const { app, BrowserWindow } = require('electron')
- CommonJSのモジュール構文で2つのElectronモジュールをインポートしている
ウインドウを作成する再使用可能な関数を書く
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
}
- 新しいBrowserWindowインスタンスで読みこむ
アプリの準備ができたら関数を呼び出す
app.whenReady().then(() => {
createWindow()
})
- Electronのコアモジュールの多くは、Node.jsのEventEmitter。Nodeの非同期のイベント駆動型アーキテクチャに準拠している
- appモジュールは、これらのエミッターのうち1つ
- アプリがウィンドウに表示する各ウェブページは、レンダラープロセスという個別のプロセスで実行される
- レンダラープロセスはFEのWeb開発と同じようにJSのAPIへアクセスできる
考察
今回、Electronの基本を整理し、試してみました。
まだまだ、わからない事が多いので次回以降も試してみたいと思います。
参考