GithubHelp home page GithubHelp logo

sindresorhus / electron-util Goto Github PK

View Code? Open in Web Editor NEW
1.3K 12.0 63.0 231 KB

Useful utilities for Electron apps and modules

License: MIT License

JavaScript 9.90% TypeScript 87.35% HTML 2.75%
electron electron-module nodejs npm-package

electron-util's Introduction

electron-util

Useful utilities for Electron apps and modules

You can use this package directly in both the main and renderer process.

There are three parts of this package, “shared”, “main”, and “node”. The “shared” part works in both the main or rendered process. The “main” part works only in the main process. The “node” part is for Node.js-only APIs (not Electron).

To use features from the “main” part in the renderer process, you will need to set up IPC channels.

Install

npm install electron-util

Note

Requires Electron 28 or later.

Usage

The “shared” API you can access directly:

import {is} from 'electron-util';

console.log(is.macos && is.main);
//=> true

For the “main” API, use the /main sub-export:

import {isDev} from 'electron-util/main';

console.log(isDev);
//=> false

API

Documentation (The service is broken)

Look at the types for now.

Related

electron-util's People

Contributors

acheronfail avatar albinekb avatar alex-cory avatar benoitf avatar codebytere avatar coolhome avatar cvx avatar dusansimic avatar jake avatar joecohens avatar kaatt avatar karaggeorge avatar lacymorrow avatar mansarde avatar marshallofsound avatar mquevill avatar ntamas avatar qazbnm456 avatar richienb avatar sindresorhus avatar xpirt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

electron-util's Issues

Adding stuff to Electron core

This module has some pretty handy tricks that would be generally useful for all Electron apps.

@sindresorhus did you attempt to land any of this stuff in Electron core?

If so, why didn't it work out? If not, why not?

Build error with Electron 10.1.2 and Angular 8.3.20

Implement Electron app with Angular, Typescript, built project and got error import "AllElectron"
ERROR in node_modules/electron-util/index.d.ts:4:9 - error TS2305: Module '"electron"' has no exported member 'AllElectron'.

4 import {AllElectron, Remote, BrowserWindow, Size, Rectangle, Session, MenuItemConstructorOptions, MenuItem} from 'electron';

Please help me to fix this issue. Thanks.

It seems that not work on >= v14 electron's version

Hi, I use this library on Electron v18.
It not work because 'electron-is-dev' version is low, it is not compatible with this version.

image

electron.remote was deprecated on Electron v14.

I think this issue will resolved if upgrade 'electron-is-dev' version to v2.0.0.

Has any way to solve or avoid this issue?

Icon not working on linux

const aboutData = {
    icon: path.join(__dirname, 'build/icons/icon.png');,
    title: packageJson.productName,
    copyright: `Copyright ${year} ${packageJson.author.name}`,
    website: packageJson.author.url,
    text: packageJson.description,
}

click() {
    showAboutWindow(aboutData);
}

This exact code works on windows and mac but not on linux:

AppImage ( ubuntu / pop_os ) and dep package
electron 5.0.7
electron-builder 21.1.3

remmina-141057 722727
Screenshot from 2019-09-27 15-41-10
Screenshot from 2019-09-27 16-28-44

Electron v7.0.0: `app.getName()` is deprecated

Applies to

  • @sindresorhus/electron-unhandled
  • @sindresorhus/electron-updater

and probably others.

app.getName() has been deprecated in favor of app.name

(electron) 'getName function' is deprecated and will be removed. Please use 'name property' instead.

`electron-react-boilerplate` build fails with `[email protected]`

Electron 27:
No problem with v0.17.0, not sure what the issue is.

You can reproduce by:

> cross-env NODE_ENV=development TS_NODE_TRANSPILE_ONLY=true webpack --config ./.erb/configs/webpack.config.renderer.dev.dll.ts

ERROR in dll renderer renderer[26]
Module not found: Error: Exports field key should be relative path and start with "." (key: "main")

Use in Production?

You make fantastic libraries. Would you recommend this one for use in a production node app, or would you use this only for development?

I only ask because of the line in your readme:

Useful utilities for developing Electron apps...

Cheers!

Does not work with node -c "code that uses fixPathForAsarUnpack"

Aperture is using fixPathForAsarUnpack, but when running aperture inside node -p or -c you will get the following error:

❯ node -p "const recorder = require('aperture')(); recorder.startRecording().then(() => { console.log('started'); setTimeout(() => recorder.stopRecording().then(console.log), 5000) })"
/private/tmp/node_modules/aperture/index.js:16
const isUsingAsar = process.mainModule.filename.includes('app.asar');

TypeError: Cannot read property 'filename' of undefined
    at Object.<anonymous> (/private/tmp/node_modules/aperture/index.js:16:40)

Should we add a check that it's run in a file as well?

Can't import in renderer process

I'm not sure why but this is not found in renderer process. I'm using 0.14.2 with electron 11.3.0 and node 14.5.4. I've tried it with a fresh project too and no joy.
I get the usual Uncaught TypeError: fs.existsSync is not a function with const {is} = require('electron-util').
Is this mismatched versions or an issue with my use.

EDIT: This also happens when using the included electron-is-dev. Using standalone [email protected] works fine so long as electron-util isn't installed. If electron-util is installed then const {isDev} = require('electron-is-dev') defaults to the included [email protected] and produces the same error.

process.mainModule deprecated in Node 14+

is-using-asar uses process.mainModule which is deprecated as of v14 and returns undefined.

This breaks is-using-asar which always returns false

module.exports = isElectron && process.mainModule && process.mainModule.filename.includes('app.asar');

Error reported in renderer process

The 'is.development' variable uses the 'electron-is-dev' package, but this package 'must be used from the Electron main process'.

As a result, I won't be able to use 'electron-util' in my renderer process.

Rename node.js to compile on Windows

It seems that Windows does not like a file being named "node.js". I get the below error when trying to run npm start for the example app on Windows. Simply renaming this file to "nodenew.js" in my testing allowed the example app to be built.

The error from "Windows Script Host":

Script: .\electron-util\node.js
Line:   9
Char:   38
Error:  Syntax error
Code:   800A03EA
Source: Microsoft JScript compilation error

The line in question is a valid line, but the error is thrown at the => operator:

exports.fixPathForAsarUnpack = path => exports.isUsingAsar ? path.replace('app.asar', 'app.asar.unpacked') : path;

electron-util does not work with esm loader

require('electron-util') does not work if the default require function is replaced by the one provided by the esm loader.

More precisely, this launcher script throws an error when invoked as electron launcher.js:

require = require('esm')(module)
const { is } = require('electron-util')

while this one works:

const { is } = require('electron-util')

The error I'm getting in the first case is:

TypeError: Cannot read property '__esModule' of undefined
    at Object.get (/Users/tamas/.../node_modules/electron-util/source/api.js:5:62)

This is because esm is doing some magic behind the scenes that tries to access api.__esModule when ./source/api is require()d, which ends up querying electron.remote.__esModule - but electron.remote is not available in the main process. The fix would be easy with a new api.js:

'use strict';
const electron = require('electron');

module.exports = new Proxy(electron, {
    get: (target, property) => target[property] || (target.remote ? target.remote[property] : undefined)
})

Using the esm loader might not be a common setup; in my particular case, I need it because the preload script of my app imports stuff from a shared codebase that happens to use the ES6 module syntax. Of course it would be possible to transpile it to CommonJS, but I believe that the change required in api.js is so insignificant that it's probably not a stretch to have this fixed in electron-util instead.

Thanks a lot in advance for your consideration!

fs.existsSync

I am getting the Following Error when i import:
import { openSystemPreferences } from 'electron-util';

index.js:7 Uncaught TypeError: fs.existsSync is not a function
    at getElectronPath (index.js:7)
    webPreferences: {
      nodeIntegration: true,
      allowRunningInsecureContent: serve ? true : false,
      contextIsolation: false,
      enableRemoteModule: true,
    },

Can't use with Next.js

Hi.

I can't use this library with Next.js. I see this error:

Module not found: Can't resolve 'fs' in '.../node_modules/electron'

Is there any workaround?
Thanks!

Please, make "showAboutWindow" more useful

Hi, I am using you utils (on Windows) and here are my comments:

  1. Icon is poor quality (I even tried very large PNG file);
  2. Text is not centered, in fact, it does look very different compared to the screenshot on the page of this project;
  3. I am puzzled about how to change title - it seems to use "name" from "package.json", but that is lower cased with the dashes, e.g., it shows "my-app", but, obviously, I want to have "My App".
  4. Why there is limitation about "website"? To me, it seems obvious, that everyone would want to display link to project homepage.

Thanks!

Replace built in `remote` module with `@electron/remote`

From Breaking Changes:

The remote module is deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the @electron/remote module.

This package uses the built in remote module and also exposes it as api.
To be able to use it in the coming electron versions it should be replaced with @electron/remote.

I guess the main problem is that it needs to be initialized in the main process.
So electron-utils also needs to expose a initialize function?

An alternative would be to just not use the remote module anymore, but I guess that would be a big breaking change.

Happy to provide a PR if it is clear how the initialize step should work or if the remote module should be dropped completely.

enforceMacOSAppLocation doesn't work if the old app is currently open

enforceMacOSAppLocation fails in this scenario:

  • Have Foo v1 located in /Applications/Foo.app
  • Open it
  • Have Foo v2, still named Foo.app, located somewhere else
  • Open it
  • It will ask the user to move it into /Applications
  • Instead of doing that, enforceMacOSAppLocation will focus to the currently open Foo v1 window

I suppose the actual moving of the .app file failed silently but this library was stil trying to open the app and the previously opened one gained the focus this way?

I guess in this situation another dialog should be shown asking the user to close the old app and retrying later.

Error with TypeScript (Module '"electron"' has no exported member 'AllElectron')

I tried to use mac-screen-capture-permissions for my Electron app, and that package internally uses electron-util. When I compile it with TypeScript I get that error:

node_modules/electron-util/index.d.ts:4:9 - error TS2305: Module '"electron"' has no exported member 'AllElectron'.

4 import {AllElectron, Remote, BrowserWindow, Size, Rectangle, Session, MenuItemConstructorOptions, MenuItem} from 'electron';
          ~~~~~~~~~~~

I added node_modules to my exclude in tsconfig, but the error is still here. It seems like in new versions of Electron AllElectron does no longer exist.

TypeError: Cannot create proxy with a non-object as target or handler when running 'yarn test:unit'

using vue-cli and vue-cli-plugin-electron-builder to mange and build my app.
error occurs when running yarn test:unit

# yarn test:unit
yarn run v1.19.0
$ vue-cli-service test:unit
FAIL tests/unit/refUtils.spec.ts
● Test suite failed to run

TypeError: Cannot create proxy with a non-object as target or handler
1 | import WorkbenchTab from '@/components/Workbench/workbenchTab';
2 | import { remote } from 'electron';
> 3 | import { is } from 'electron-util';
| ^
4 |
5 | import { SharedObjectKey } from '@/sharedObjects/sharedObjectKey';
6 |

 at Object.<anonymous> (node_modules/electron-util/source/api.js:4:18)
 at Object.<anonymous> (node_modules/electron-util/index.js:8:13)
 at Object.<anonymous> (src/sharedObjects/sharedObjects.ts:3:1)
 at Object.<anonymous> (src/logger/index.ts:3:1)
 at Object.<anonymous> (src/commons/lang/array.ts:1:1)
 at Object.<anonymous> (src/bindings/types.ts:3:1)
 at Object.<anonymous> (tests/unit/refUtils.spec.ts:1:1)

electron-util: 0.13.0

Publish `enforceMacOSAppLocation` as a standalone module

Can the enforceMacOSAppLocation function be published as a standalone module?

That's the only thing provided by this library that I'm using and I'd like to minimize the amount of extra code that is bundled along with my app.

Typescript Compiler Error in d.ts - Module '"electron"' has no exported member 'AllElectron'

Error when using Typescript
node_modules/electron-util/index.d.ts:4:9 - error TS2305: Module '"electron"' has no exported member 'AllElectron'.

Error from TypeScript CLI

image

Versions

Typescript Version: 4.1.3
Node Version: v14.15.1
Windows: 10.0.19042 Build 19042

TSConfig

{
  "compilerOptions": {
      "module": "commonjs",
      "esModuleInterop": true,
      "target": "es6",
      "noImplicitAny": false,
      "moduleResolution": "node",
      "sourceMap": true,
      "strictNullChecks": false,
      "outDir": "dist",
      "baseUrl": ".",
      "paths": {
          "*": [
              "node_modules/*",
              "src/types/*"
          ]
      },
      "plugins": [],
  },
  "include": [
      "src/**/*"
  ]
}

Package.json

{
  "name": "logviewer.client",
  "productName": "Compact Log Viewer",
  "version": "1.0.6",
  "description": "A cross platform Electron app to view and search logs stored in the Compact log format",
  "homepage": "https://github.com/warrenbuckley/Compact-Log-Format-Viewer#readme",
  "repository": {
    "type": "git",
    "url": "https://github.com/warrenbuckley/Compact-Log-Format-Viewer.git"
  },
  "main": "dist/main/main.js",
  "scripts": {
    "start": "electron .",
    "lint": "eslint -c .eslintrc.js --ext .ts src",
    "tsc": "tsc --diagnostics",
    "watch": "tsc --watch",
    "win": "electron-builder --publish never --win --config ./electron-builder.json",
    "mac": "electron-builder --publish never --mac --config electron-builder.json"
  },
  "author": "Warren Buckley",
  "license": "ISC",
  "private": true,
  "devDependencies": {
    "@types/angular": "^1.8.0",
    "@types/chart.js": "^2.9.29",
    "@types/electron-is-dev": "^1.1.1",
    "@types/request": "^2.48.5",
    "@typescript-eslint/eslint-plugin": "^4.10.0",
    "@typescript-eslint/parser": "^4.10.0",
    "electron": "^11.1.0",
    "electron-builder": "^22.9.1",
    "eslint": "^7.16.0",
    "eslint-plugin-jsdoc": "^30.7.8",
    "eslint-plugin-prefer-arrow": "^1.2.2",
    "tslint": "^6.1.3",
    "typescript": "^4.1.3",
    "typescript-tslint-plugin": "^1.0.1"
  },
  "dependencies": {
    "angular": "^1.8.2",
    "angular-chart.js": "^1.1.1",
    "bootstrap": "^4.5.3",
    "chart.js": "^2.9.4",
    "electron-log": "^4.3.1",
    "electron-util": "^0.14.2",
    "jquery": "^3.5.1",
    "popper.js": "^1.16.1",
    "request": "^2.88.2"
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.