Перейти к основному содержанию

8 постов с тегом "Экосистема"

'Blog posts about Electron's package ecosystem'

Показать все теги

Ecosystem 2023 Recap

· 5 мин. прочитано

Reflecting on the improvements and changes in Electron's developer ecosystem in 2023.


In the past few months, we've been cooking up some changes across the Electron ecosystem to supercharge the developer experience for Electron apps! Here’s a swift rundown of the latest additions straight from Electron HQ.

Electron Forge 7 and beyond

Electron Forge 7 — the newest major version of our all-in-one tool for packaging and distributing Electron applications — is now available.

While Forge 6 was a complete rewrite from v5, v7 is smaller in scope but still contains a few breaking changes. Going forward, we will continue to publish major versions of Forge as breaking changes need to be made.

For more details, see the full Forge v7.0.0 changelog on GitHub.

Важные изменения

  • Switched to notarytool for macOS notarization: As of 2023-11-01, Apple sunset the legacy altool for macOS notarization, and this release removes it from Electron Forge entirely.
  • Minimum Node.js increased to v16.4.0: With this release, we’ve set the minimum required Node.js version to 16.4.0.
  • Dropped support for electron-prebuilt and electron-prebuilt-compile: electron-prebuilt was the original name for Electron’s npm module, but was replaced by electron in v1.3.1. electron-prebuilt-compile was an alternative to that binary that came with enhanced DX features, but was eventually abandoned as a project.

Highlights

  • Google Cloud Storage publisher: As part of our push to better support static auto updating, Electron Forge now supports publishing directly to Google Cloud Storage!
  • ESM forge.config.js support: Electron Forge now supports ESM forge.config.js files. (P.S. Look forward to ESM entrypoint support in Electron 28.)
  • Makers now run in parallel: In Electron Forge 6, Makers ran sequentially for ✨ legacy ✨ reasons. Since then, we’ve tested out parallelization for the Make step with no adverse side effects, so you should see a speed-up when building multiple targets for the same platform!
Thank you!

🙇 Big thanks to mahnunchik for the contributions for both the GCS Publisher and ESM support in Forge configurations!

Better static storage auto updates

Squirrel.Windows and Squirrel.Mac are platform-specific updater technologies that back Electron’s built-in autoUpdater module. Both projects support auto updates via two methods:

  • A Squirrel-compatible update server
  • A manifest URL hosted on a static storage provider (e.g. AWS, Google Cloud Platform, Microsoft Azure, etc.)

The update server method has traditionally been the recommended approach for Electron apps (and provides additional customization of update logic), but it has a major downside—it requires apps to maintain their own server instance if they are closed-source.

On the other hand, the static storage method has always been possible, but was undocumented within Electron and poorly supported across Electron tooling packages.

With some great work from @MarshallOfSound, the update story for serverless automatic app updates has been drastically streamlined:

  • Electron Forge’s Zip and Squirrel.Windows makers can now be configured to output autoUpdater-compatible update manifests.
  • A new major version of update-electron-app (v2.0.0) can now read these generated manifests as an alternative to the update.electronjs.org server.

Once your Makers and Publishers are configured to upload update manifests to cloud file storage, you can enable auto updates with only a few lines of configuration:

const { updateElectronApp, UpdateSourceType } = require('update-electron-app');

updateElectronApp({
updateSource: {
type: UpdateSourceType.StaticStorage,
baseUrl: `https://my-manifest.url/${process.platform}/${process.arch}`,
},
});
Дополнительная литература

📦 Want to learn more? For a detailed guide, see Forge’s auto update documentation.

The @electron/ extended universe

When Electron first started, the community published many packages to enhance the experience of developing, packaging, and distributing Electron apps. Over time, many of these packages were incorporated into Electron’s GitHub organization, with the core team taking on the maintenance burden.

In 2022, we began unifying all these first-party tools under the @electron/ namespace on npm. This change means that packages that used to be electron-foo are now @electron/foo on npm, and repositories that used to be named electron/electron-foo are now electron/foo on GitHub. These changes help clearly delineate first-party projects from userland projects. This includes many commonly used packages, such as:

  • @electron/asar
  • @electron/fuses
  • @electron/get
  • @electron/notarize
  • @electron/osx-sign
  • @electron/packager
  • @electron/rebuild
  • @electron/remote
  • @electron/symbolicate-mac
  • @electron/universal

Going forward, all first-party packages we release will also be in the @electron/ namespace. There are two exceptions to this rule:

  • Electron core will continue to be published under the electron package.
  • Electron Forge will continue to publish all of its monorepo packages under the @electron-forge/ namespace.
Star seeking

⭐ During this process, we also accidentally took the electron/packager repository private, which has the unfortunate side effect of erasing our GitHub star count (over 9000 before the erasure). If you are an active user of Packager, we’d appreciate a ⭐ Star ⭐!

Introducing @electron/windows-sign

Starting on 2023-06-01, industry standards began requiring keys for Windows code signing certificates to be stored on FIPS-compliant hardware.

In practice, this meant that code signing became a lot harder for apps that build and sign in CI environments, since many Electron tools take in a certificate file and password as config parameters and attempt to sign from there using hardcoded logic.

This situation has been a common pain point for Electron developers, which is why we have been working on a better solution that isolates Windows code signing into its own standalone step, similar to what @electron/osx-sign does on macOS.

In the future, we plan on fully integrating this package into the Electron Forge toolchain, but it currently lives on its own. The package is currently available for installation at npm install --save-dev @electron/windows-sign and can used programmatically or via CLI.

Please try it out and give us your feedback in the repo’s issue tracker!

What's next?

We'll be entering our annual December quiet period next month. While we do, we'll be thinking about how we can make the Electron development experience even better in 2024.

Is there anything you'd like to see us work on next? Дайте нам знать!

Представляем Electron Forge 6

· 6 мин. прочитано

Мы рады сообщить, что вышел Electron Forge v6.0.0! This release marks the first major release of Forge since 2018 and moves the project from electron-userland into the main electron organization on Github.

Продолжайте чт��ние, чтобы узнать о новинках и как ваше приложение может внедрить Electron Forge!

Что такое Electron Forge?

Electron Forge is a tool for packaging and distributing Electron applications. It unifies Electron's build tooling ecosystem into a single extensible interface so that anyone can jump right into making Electron apps.

Highlight features include:

  • 📦 Application packaging and code signing
  • 🚚 Customizable installers on Windows, macOS, and Linux (DMG, deb, MSI, PKG, AppX, etc.)
  • ☁️ Automated publishing flow for cloud providers (GitHub, S3, Bitbucket, etc.)
  • ⚡️ Easy-to-use boilerplate templates for webpack and TypeScript
  • ⚙️ Native Node.js module support
  • 🔌 Extensible JavaScript plugin API
Дальнейшее изучение

Visit the Why Electron Forge explainer document to learn more about Forge's philosophy and architecture.

What's new in v6?

Completely rewritten

From v1 to v5, Electron Forge was based on the now-discontinued electron-compile project. Forge 6 is a complete rewrite of the project with a new modular architecture that can be extended to meet any Electron application's needs.

In the past few years, Forge v6.0.0-beta has achieved feature parity with v5 and code churn has slowed down dramatically, making the tool ready for general adoption.

Don't install the wrong package

For versions 5 and below, Electron Forge was published to the electron-forge package on npm. Starting with the v6 rewrite, Forge is instead structured as a monorepo project with many smaller projects.

Officially supported

Historically, Electron maintainers have been unopinionated about build tooling, leaving the task to various community packages. However, with Electron maturing as a project, it has become harder for new Electron developers to understand which tools they need to build and distribute their apps.

To help guide Electron developers in the distribution process, we have have decided to make Forge the official batteries-included build pipeline for Electron.

Over the past year, we have been slowly integrating Forge into the official Electron documentation, and we have recently moved Forge over from its old home in electron-userland/electron-forge to the electron/forge repo. Now, we are finally ready to release Electron Forge to a general audience!

Начало работы

Initializing a new Forge project

Scaffolding a new Electron Forge project can be done using the create-electron-app CLI script.

yarn create electron-app my-app --template=webpack
cd my-app
yarn start

The script will create an Electron project in the my-app folder with completely JavaScript bundling and a preconfigured build pipeline.

For more info, see the Getting Started guide in the Forge docs.

First-class webpack support

The above snippet uses Forge's Webpack Template, which we recommend as a starting point for new Electron projects. This template is built around the @electron-forge/plugin-webpack plugin, which integrates webpack with Electron Forge in a few ways, including:

  • enhancing local dev flow with webpack-dev-server, including support for HMR in the renderer;
  • handling build logic for webpack bundles before application packaging; and
  • adding support for Native Node modules in the webpack bundling process.

Если вам нужна поддержка TypeScript, попробуйте вместо этого использовать Webpack + TypeScript Template.

Importing an existing project

The Electron Forge CLI also contains an import command for existing Electron projects.

cd my-app
yarn add --dev @electron-forge/cli
yarn electron-forge import

When you use the import command, Electron Forge will add a few core dependencies and create a new forge.config.js configuration. If you have any existing build tooling (e.g. Electron Packager, Electron Builder, or Forge 5), it will try to migrate as many settings as possible. Some of your existing configuration may need to be migrated manually.

Manual migration details can be found in the Forge import documentation. If you need help, please stop by our Discord server!

Why switch to Forge?

If you already have tooling for packaging and publishing your Electron app, the benefits associated with adopting Electron Forge can still outweigh the initial switching cost.

We believe there are two main benefits to using Forge:

  1. Forge receives new features for application building as soon as they are supported in Electron. In this case, you won't need to wire in new tooling support yourself, or wait for that support to be eventually implemented by other packages before upgrading. For recent examples, see macOS universal binaries and ASAR integrity checking.

  2. Forge's multi-package architecture makes it easy to understand and extend. Since Forge is made up of many smaller packages with clear responsibilities, it is easier to follow code flow. In addition, Forge's extensible API design means that you can write your own additional build logic separate from the provided configuration options for advanced use cases. For more details on writing custom Forge plugins, makers, and publishers, see the Extending Electron Forge section of the docs.

Важные изменения

Forge 6 has spent a long time in the beta phase, and its release cadence has gradually slowed down. However, we have accelerated development in the second half of 2022 and used the last few releases to push some final breaking changes before the v6.0.0 stable release.

If you are an Electron Forge 6 beta user, see the v6.0.0 GitHub release notes for a list of breaking changes made in recent betas (>=6.0.0-beta.65).

A complete list of changes and commits can be found in the repo's CHANGELOG.md.

Submit your feedback!

Tell us what you need! The Electron Forge team is always looking to build the project to better suit its users.

You can help us improve Electron Forge by submitting feature requests, posting issues, or just letting us know your feedback! You can also join us in the official Electron Discord server, where there is a dedicated channel for Electron Forge discussion.

If you want to give any feedback on the Forge docs at https://electronforge.io, we have a GitBook instance synced to the electron-forge/electron-forge-docs repo.

Spectron Deprecation Notice

· 2 мин. прочитано

Spectron will be deprecated on February 1st, 2022.


Beginning in February 2022, Spectron will be officially deprecated by the Electron team.

Why Deprecate Spectron?

While Spectron has consistently put out new releases for each new version of Electron, the project has had very little maintenance and improvements for well over a year, and currently has no full-time maintainers. With the remote module moving outside of Electron core and into an external module in Electron 14, Spectron will require a major rewrite to continue working reliably.

After reviewing several available options for Spectron's continued maintenance, the Electron team has decided to deprecate Spectron in 2022.

Deprecation Timeline

The following is our planned deprecation timeline:

  • November 2021 - January 2022: The Electron team will continue to accept pull requests from the community.
  • January 2022: A final version of announcement warning about Spectron's deprecation will be released.
  • February 1, 2022: Spectron's repo will be marked as "archived". No more pull requests will be accepted.

Following February 1st, 2022, Electron will continue to leave the Spectron repo up indefinitely, so that others are welcome to fork or use the existing code for their projects. We hope this will help provide a longer transition to any projects that may still depend on Spectron.

Alternatives to Spectron

If you're currently using Spectron in your project and would like to migrate to an alternative testing solution, you can read our guide for automated testing here.

We currently have several other recommended alternatives to Spectron, including Playwright and WebDriverIO. Official tutorials for each option can be found in our Automated Testing documentation.

Что дальше

We here on the Electron team appreciate you using Spectron and Electron. We understand that many of you depend on Spectron for testing your apps, and we want to make this transition as painless for you as possible. Thank you for choosing Electron!

Простое автообновление приложений с открытым исходным кодом

· 3 мин. прочитано

Сегодня мы выпускаем бесплатный хостинг с открытым исходным кодом веб-службу обновлений и сопутствующий пакет npm чтобы обеспечить простые автоматические обновления для приложений Electron с открытым исходным кодом. Это шаг к тому, чтобы разработчики приложений меньше думали о развертывании, и больше - о создании высококачественного опыта для своих пользователей.


Новый модуль обновления в действии

Делаем жизнь проще

В Electron есть API autoUpdater, который дает приложениям возможность использовать метаданные из удалённой конечной точки, чтобы проверять наличие обновлений, скачивать их в фоновом режиме и автоматически устанавливать их.

Enabling these updates has been a cumbersome step in the deployment process for many Electron app developers because it requires a web server to be deployed and maintained just to serve app version history metadata.

Сегодня мы анонсируем новое решение для автоматического обновления приложений. Если ваше приложение Electron находится в публичном репозитории GitHub и вы используете GitHub Releases для публикации сборок, вы можете использовать этот сервис для непрерывной доставки обновлений приложения своим пользователям.

Использование нового модуля

Чтобы свести к минимуму настройки с вашей стороны, мы создали update-electron-app, модуль npm, который интегрируется с новым веб-сервисом update.electronjs.org.

Установить модуль:

npm install update-electron-app

Вызовите его из любого места в главном процессе вашего приложения:

require('update-electron-app')();

Вот и всё! Модуль будет проверять наличие обновлений при запуске приложения, а затем каждые десять минут. При обнаружении обновления, оно будет скачано автоматически в фоновом режиме, когда обновление завершится, появится диалоговое окно.

Перенос существующих приложений

Приложения, уже использующие autoUpdater API Electron, также могут использовать эту службу. Для этого вы можете настроить модуль update-electron-app или интегрировать его напрямую с update.electronjs.org.

Альтернативы

Если вы используете electron-builder для упаковки своего приложения, то можно использовать его встроенный инструмент обновления. Подробности смотрите в electron.build/auto-update.

Если ваше приложение является приватным, то может потребоваться запустить собственный сервер обновлений. Для этого существует ряд инструментов с открытым исходным кодом, в том числе Hazel компании Zeit и Nucleus компании Atlassian. Дополнительные сведения смотрите в руководстве Развертывание сервера обновлений.

Thanks

Благодарим Julian Gruber за помощь в разработке и создании этого простого и масштабируемого веб-сервиса. Благодарим ребят из Zeit за сервис Hazel с открытым исходным кодом, из которого мы черпали вдохновение для дизайна. Благодарим Samuel Attard за рецензии кода. Благодарим сообщество Electron за помощь в тестировании этого сервиса.

🌲 За вечнозеленое будущее приложений Electron!

Announcing TypeScript support in Electron

· 4 мин. прочитано

electron npm package теперь включает в себя файл определения TypeScript, который содержит подробные аннотации всего Electron API. These annotations can improve your Electron development experience even if you're writing vanilla JavaScript. Just npm install electron to get up-to-date Electron typings in your project.


TypeScript is an open-source programming language created by Microsoft. It's a superset of JavaScript that extends the language by adding support for static types. The TypeScript community has grown quickly in recent years, and TypeScript was ranked among the most loved programming languages in a recent Stack Overflow developer survey. TypeScript is described as "JavaScript that scales", and teams at GitHub, Slack, and Microsoft are all using it to write scalable Electron apps that are used by millions of people.

TypeScript supports many of the newer language features in JavaScript like classes, object destructuring, and async/await, but its real differentiating feature is type annotations. Объявление типов входных и выходных данных, ожидаемых вашей программой, может уменьшить количество ошибок, помогая вам находить ошибки во время компиляции, а аннотации могут также служить формальным заявлением о том, как ваша программа работает.

When libraries are written in vanilla Javascript, the types are often vaguely defined as an afterthought when writing documentation. Functions can often accept more types than what was documented, or a function can have invisible constraints that are not documented, which can lead to runtime errors.

TypeScript solves this problem with definition files. A TypeScript definition file describes all the functions of a library and its expected input and output types. When library authors bundle a TypeScript definition file with their published library, consumers of that library can explore its API right inside their editor and start using it right away, often without needing to consult the library's documentation.

Many popular projects like Angular, Vue.js, node-github (and now Electron!) compile their own definition file and bundle it with their published npm package. For projects that don't bundle their own definition file, there is DefinitelyTyped, a third-party ecosystem of community-maintained definition files.

Установка

Starting at version 1.6.10, every release of Electron includes its own TypeScript definition file. When you install the electron package from npm, the electron.d.ts file is bundled automatically with the installed package.

The safest way to install Electron is using an exact version number:

npm install electron --save-dev --save-exact

Or if you're using yarn:

yarn add electron --dev --exact

If you were already using third-party definitions like @types/electron and @types/node, you should remove them from your Electron project to prevent any collisions.

The definition file is derived from our structured API documentation, so it will always be consistent with Electron's API documentation. Just install electron and you'll always get TypeScript definitions that are up to date with the version of Electron you're using.

Usage

For a summary of how to install and use Electron's new TypeScript annotations, watch this short demo screencast:

If you're using Visual Studio Code, you've already got TypeScript support built in. There are also community-maintained plugins for Atom, Sublime, vim, and other editors.

Once your editor is configured for TypeScript, you'll start to see more context-aware behavior like autocomplete suggestions, inline method reference, argument checking, and more.

Method autocompletion

Method reference

Argument checking

Getting started with TypeScript

If you're new to TypeScript and want to learn more, this introductory video from Microsoft provides a nice overview of why the language was created, how it works, how to use it, and where it's headed.

There's also a handbook and a playground on the official TypeScript website.

Because TypeScript is a superset of JavaScript, your existing JavaScript code is already valid TypeScript. This means you can gradually transition an existing JavaScript project to TypeScript, sprinkling in new language features as needed.

Thanks

This project would not have been possible without the help of Electron's community of open-source maintainers. Thanks to Samuel Attard, Felix Rieseberg, Birunthan Mohanathas, Milan Burda, Brendan Forster, and many others for their bug fixes, documentation improvements, and technical guidance.

Поддержка

If you encounter any issues using Electron's new TypeScript definition files, please file an issue on the electron-typescript-definitions repository.

Happy TypeScripting!

Electron Userland

· 3 мин. прочитано

We've added a new userland section to the Electron website to help users discover the people, packages, and apps that make up our flourishing open-source ecosystem.


github-contributors

Origins of Userland

Userland is where people in software communities come together to share tools and ideas. The term originated in the Unix community, where it referred to any program that ran outside of the kernel, but today it means something more. When people in today's Javascript community refer to userland, they're usually talking about the npm package registry. This is where the majority of experimentation and innovation happens, while Node and the JavaScript language (like the Unix kernel) retain a relatively small and stable set of core features.

Node and Electron

Like Node, Electron has a small set of core APIs. These provide the basic features needed for developing multi-platform desktop applications. Такая философия позволяет Electron оставаться гибким инструментом, будучи не предписывая того как им пользоваться.

Userland is the counterpart to "core", enabling users to create and share tools that extend Electron's functionality.

Collecting data

To better understand the trends in our ecosystem, we analyzed metadata from 15,000 public GitHub repositories that depend on electron or electron-prebuilt

We used the GitHub API, the libraries.io API, and the npm registry to gather info about dependencies, development dependencies, dependents, package authors, repo contributors, download counts, fork counts, stargazer counts, etc.

We then used this data to generate the following reports:

Filtering Results

Отчеты, например, о зависимостях приложений и звёздных приложениях, в которых перечислены пакеты, приложения и репозитории, содержат текстовый ввод, который можно использовать для фильтрации результатов.

As you type into this input, the URL of the page is updated dynamically. This allows you to copy a URL representing a particular slice of userland data, then share it with others.

babel

More to come

This first set of reports is just the beginning. We will continue to collect data about how the community is building Electron, and will be adding new reports to the website.

All of the tools used to collect and display this data are open-source:

If you have ideas about how to improve these reports, please let us know opening an issue on the website repository or any of the above-mentioned repos.

Thanks to you, the Electron community, for making userland what it is today!

Специальные возможности

· 2 мин. прочитано

Создание доступных приложений важно и мы рады представить новые функции Devtron и Spectron, что дает разработчикам возможность делать свои приложения лучше для всех.


Проблемы с доступностью в приложениях Electron аналогичны веб-сайтам, поскольку они оба в конечном итоге являются HTML. Однако в приложениях Electron вы не можете использовать онлайн-ресурсы для аудита доступности, потому что ваше приложение не имеет URL-адреса, чтобы указать аудитору.

Эти новые функции приносят эти инструменты аудита в ваше приложение Electron. Эти новые возможности приносят эти инструменты аудита в ваше приложение Electron. Прочитайте сводки инструментов или проверки нашей доступной документации для получения дополнительной информации.

Spectron

В тестовом фреймворке Spectron, вы можете совершить аудит каждого окна и <webview> в вашем приложении. Например:

app.client.auditAccessibility().then(function (audit) {
if (audit.failed) {
console.error(audit.message);
}
});

Вы можете прочитать больше об этой функции в Spectron документации.

Devtron

В Devtron есть новая вкладка доступности, которая позволит вам совершить аудит страницы в вашем приложении, сортировать и фильтровать результаты.

devtron скриншот

Оба эти средства используют Accessibility Developer Tools библиотеки, построенных для Google Chrome. Вы можете узнать больше о доступности правила аудита, которые эта библиотека использует в этих репозиториях wiki.

Если вы знаете другие инструменты доступности для Electron, добавьте их к accessibility documentation pull request'том.

Mac App Store and Windows Auto Updater on Electron

· 2 мин. прочитано

Recently Electron added two exciting features: a Mac App Store compatible build and a built-in Windows auto updater.


Mac App Store Support

As of v0.34.0 each Electron release includes a build compatible with the Mac App Store. Previously an application built on Electron would not comply with Apple's requirements for the Mac App Store. Most of these requirements are related to the use of private APIs. In order to sandbox Electron in such a way that it complies with the requirements two modules needed to be removed:

  • crash-reporter
  • auto-updater

Additionally some behaviors have changed with respect to detecting DNS changes, video capture and accessibility features. You can read more about the changes and submitting your app to the Mac App store in the documentation. The distributions can be found on the Electron releases page, prefixed with mas-.

Related Pull Requests: electron/electron#3108, electron/electron#2920

Windows Auto Updater

In Electron v0.34.1 the auto-updater module was improved in order to work with Squirrel.Windows. This means that Electron ships with easy ways for auto updating your app on both OS X and Windows. You can read more on setting up your app for auto updating on Windows in the documentation.

Related Pull Request: electron/electron#1984