GithubHelp home page GithubHelp logo

electron-is-dev's Introduction

electron-is-dev

Check if Electron is running in development

Useful for enabling debug features only during development.

This package must be used from the Electron main process.

Install

npm install electron-is-dev

Requires Electron 28 or later.

Usage

import isDev from 'electron-is-dev';

if (isDev) {
	console.log('Running in development');
} else {
	console.log('Running in production');
}

You can force development mode by setting the ELECTRON_IS_DEV environment variable to 1.

FAQ

How is this different than app.isPackaged?

This package existed long before that property. The benefit of this package is that you can override the value using an environment variable.

How do I use this in the renderer process?

You can use contextBridge in the preload script to manually expose the variable:

import {contextBridge} from 'electron';
import isDev from 'electron-is-dev';

contextBridge.exposeInMainWorld('isDev', isDev);

You can then access it in globalThis from the renderer process:

console.log(globalThis.isDev);

Related

electron-is-dev's People

Contributors

bendingbender avatar kevva avatar popod avatar richienb avatar sindresorhus avatar slapbox avatar zeke 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

electron-is-dev's Issues

This module may break soon

A kind soul (@logicalparadox) has allowed us to take over the electron package name on npm, and we are beginning the process of publishing electron-prebuilt and electron in tandem for a while.

If a user installs the new electron, this package in its current form will not be able to detect that, because it's looking for -prebuilt in the path name:

module.exports = process.defaultApp || /[\\/]electron-prebuilt[\\/]/.test(process.execPath);

Context: electron-userland/electron-prebuilt#160

Should not be dev, but after packing isDev returns true

electron-packager . --productName='My app' --out=dist --prune --overwrite --app-version=0.0.1 --protocol=myprotocol --protocol-name='My App' --version=1.6.2 --platform=darwin --icon=assets/icons/my-icon.icns

After packing my app and, isDev returns true, because all my (isDev) ? : ifs are returning true.

Am I doing something wrong?

Examples in the code:

const SETTINGS = {
  protocol: (isDev) ? 'devmyprotocol' : 'myprotocol',
  baseURL: (isDev) ? 'https://local.myapp/' : 'https://production/'
};

After packing, all settings continue to isDev === true.

Cannot read property 'app' of undefined

The error is the same as seen in here, but I am getting this when running unit tests using jest.

I have written a small unit test on a file which includes the below line.

const isDev = require('electron-is-dev');

I get the error below:

TypeError: Cannot read property 'app' of undefined

Any feedback is much appreciated. thanks.

electron-is-dev can only be default-imported using the 'esModuleInterop' flag

Preflight Checklist

Electron Version

12.0.6

What operating system are you using?

macOS

Operating System Version

10.13

What arch are you using?

arm64 (including Apple Silicon)

Last Known Working Electron version

No response

Expected Behavior

Launching the application

Actual Behavior

Invoking these errors:
[1] src/electron/main.ts(6,8): error TS1259: Module '"/Users/alaeddine/node_modules/electron-is-dev/index"' can only be default-imported using the 'esModuleInterop'

Testcase Gist URL

No response

Additional Information

main.ts

import electron from "electron";
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;

import { join } from "path";
import isDev from "electron-is-dev"; // Error is here

let mainWindow: Electron.BrowserWindow, childWindow: Electron.BrowserWindow;

import { ipcMain } from "electron";

ipcMain.on("asynchronous-message", (event, arg) => {
  mainWindow.webContents.openDevTools();
});

const createWindow = () => {
  mainWindow = new BrowserWindow({
    width: 480,
    height: 320,
    show: false,
    backgroundColor: "red",
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
  });
  childWindow = new BrowserWindow({
    width: 480,
    height: 320,
    show: false,
    parent: mainWindow,
    modal: true,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
    },
  });
  const appUrl = isDev
    ? "http://localhost:3000"
    : `file://${join(__dirname, "../build/index.html")}`;
  mainWindow.loadURL(appUrl);
  childWindow.loadURL(appUrl);
  mainWindow.maximize();
  mainWindow.on("ready-to-show", () => mainWindow.show());
  mainWindow.on("closed", () => mainWindow.destroy());
};
app.on("ready", createWindow);
app.on("window-all-closed", () => {
  // Follow OS convention on whether to quit app when
  // all windows are closed.
  if (process.platform !== "darwin") {
    app.quit();
  }
});
app.on("activate", () => {
  // If the app is still open, but no windows are open,
  // create one when the app comes into focus.
  if (mainWindow === null) {
    createWindow();
  }
});

// Integrate Hot Reload feature
try {
  require("electron-reloader")(module);
} catch (_) {}

tsconfig.json

{
  "compilerOptions": {
    "module": "esnext",
    "target": "es2016",
    "jsx": "react-jsx",
    "strictFunctionTypes": true,
    "sourceMap": true,
    "outDir": "./build",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "esModuleInterop": true
  },
  "exclude": ["node_modules", "**/node_modules/*"],
  "include": ["src", "electron/renderer.ts"]
}

Incorrect result if app is executed under a folder with name `electron`

The dev environment check returns true if the packaged app is executed from a path that contains /electron/.

The electron-reload is one of my dev dependencies, which is required within a isDev check.

By the way, an official approach for such use cases is being discussed (electron/electron#7714), looks like they are very close to draw a conclusion, but don't know when the feature will be shipped.

Allow usage in renderer process

Feature request: Allow usage in renderer process, or add info to README.md how to achieve it.

It could be really useful feature over the default isPackaged we have nowadays.

I imagine it could be implemented by detecting whenever index.js of the module is running in the renderer process and if so, using IPC to get the information.

I ended up using this:

const isDev = window.location.hostname == 'localhost' && window.location.protocol.startsWith('http');

isDev is always true

My npm script looks as follows:

"start:prod": "cross-env NODE_ENV=production && electron dist/main.js"

main.js:

import isDev from 'electron-is-dev';

app.on('ready', () => {
  console.log('isDev', isDev);
  if (!isDev) {
    const {session} = require('electron');
    session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
      callback({responseHeaders: `default-src http: ws:`})
    })
  }
  const win = createWindow();
  createMenu(win);
});

The console outputs:

isDev true

I have some trouble understanding the use of this npm package which seems to be used a lot.
When setting NODE_ENV, I expect just being able to use process.env.NODE_ENV in my code as I'm used to, and it does seem to work.
Why do we need another environment variable (?).

My bundle is packaged with webpack, not sure if this may have anything to do with it, but I wouldn't expect it to.

const path = require('path');

module.exports = {
  entry: "./src/server/main.js",
  output: {
    filename: "main.js",
    path: path.resolve(__dirname, '../../dist')
  },
  mode: 'production',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: "babel-loader"
      }
    ]
  },
  node: {
    __dirname: false,
    __filename: false
  },
  target: "electron-main"
};

Deprecate `electron-is-dev`

Electron.js now has a built-in solution called app.isPackaged.
Run:

npm deprecate electron-is-dev "Use 'app.isPackaged' from electron.js instead of electron-is-dev"

Not working in renderer process

import {app} from 'electron' only works in renderer process.. So electron-is-dev do not works anymore in renderer process :(

The error: Cannot read property 'isPackaged' of undefined

No more working for Electron versions < 3 !

This package works great with older versions of Election (2.x.x).. Why not getting this support for some more times ?

I cannot switch to Electron 3.x.x because of some npm dependencies that I use and that doesn't support the version 3 for now..

Thanks

Does not work in forked process.

I run one of my modules in a forked process so as to not lag the main UI. Electron is not defined in that process, so the module fails.

TypeError: Cannot read property 'app' of undefined

I could add a work around to my code, but it would be much cleaner for this module to support forked processes as it did in 0.3.0.

electron.remote module deprecation warning

In a browser window without enableRemoteModule:true,
this line warns about the usage of deprecated remote module with electron 9.1.0.

const app = electron.app || electron.remote.app;

Would it be a good thing to get rid of remote usage?

Error [ERR_REQUIRE_ESM]: require() ..... index.js not supported

while using this code getting following issue
App threw an error during load
Error [ERR_REQUIRE_ESM]: require() of ES Module D:\project\node_modules\electron-is-dev\index.js from D:\ecosail\index.js not supported

here is my code of electron index.js
const { app, BrowserWindow, Menu } = require('electron');
const path = require('path');
const isDev = require('electron-is-dev');

function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true, // Consider using contextIsolation and preload instead
webSecurity: false // to disable web security (consider enabling for production)
}
});

if (isDev) {
console.log('Running in development');
} else {
console.log('Running in production');
}
win.loadURL("http://localhost:3000/");
//win.webContents.openDevTools();
}

app.on('ready', () => {
const menu = Menu.buildFromTemplate([]);
Menu.setApplicationMenu(menu);
createWindow();
});

app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});

app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
Screenshot (17)

Change ELECTRON_IS_DEV in package.json

Hello !
I'm kinda new to electron, but so far, everything is work like I want to. I'm buildin a react electron app, and i'm at the process of building it. I'm using electron_builder to do so.
I'm also using this electron-is-dev to simply check if I should set the window frameless or not and open devtools or not.
So far, it is working correctly in development and in production.
Now, I'm asked to be able to build a production version where I can debug it, meaning having a frame window and devtools open.
In the documentation, I saw that we can set the environment variable ELECTRON_IS_DEV to 1 to force the dev mode. But it is not working for me.
I'm calling this script to build with debug:
"electron-build-local-win": "cross-env ELECTRON_IS_DEV=1 electron-builder build --win --publish never --ia32"

And my electron.js(entry point) looks like this (for the interesting part):
`const { app, BrowserWindow, ipcMain } = require('electron');
const { autoUpdater } = require('electron-updater');
const path = require('path');
const isDev = require('electron-is-dev');

let mainWindow;

function createWindow() {
mainWindow = new BrowserWindow({
width: 600,
height: 800,
frame: isDev,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true,
preload: 'src/Electron/AutoUpdater.ts',
},
});
mainWindow.loadURL(isDev ? 'http://localhost:3000' : file://${__dirname}/index.html);
mainWindow.maximize();
if(isDev) {
mainWindow.webContents.openDevTools();
}`

So I was thinking I could just change the environment variable while calling the script, but it is not working so far.
What did I miss ?

Thanks in advance !

TypeError: Cannot read property 'app' of undefined

Trying to get concurrently + electron + create-react-app working nicely together. However, upon launching Electron, I am getting an error that states TypeError: Cannot read property 'app' of undefined from node_modules\electron-is-dev\index.js.

It's pointing to the const app = electron.app || electron.remote.app;.

Here's my package.json:

{
  "name": "ootl",
  "version": "0.1.0",
  "private": true,
  "main": "src/start.js",
  "dependencies": {
    "electron-is-dev": "^1.1.0",
    "react": "^16.11.0",
    "react-dom": "^16.11.0",
    "react-scripts": "3.2.0"
  },
  "homepage": "./",
  "build": {
    "appId": "ootl",
    "directories": {
      "buildResources": "assets"
    }
  },
  "scripts": {
    "dev": "nodemon --watch . --exec \"electron . --debug\"",
    "start": "concurrently \"react-scripts start\" \"nodemon --watch . --exec\" \"electron . --debug\"",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "electron": "^7.1.2",
    "electron-builder": "^22.1.0",
    "nodemon": "^1.19.4"
  }
}

I'm using the start script to run the project.
Here's my start.js files for Electron:

const electron = require("electron");
const app = electron.app;
const path = require("path");
const BrowserWindow = electron.BrowserWindow;
const isDev = require("electron-is-dev");

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  });

  mainWindow.loadURL(
    isDev
      ? "http://localhost:3000"
      : `file://${path.join(__dirname, "../build/index.html")}`
  );

  mainWindow.on("closed", () => {
    mainWindow = null;
  });
}

app.on("ready", createWindow);

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  if (mainWindow === null) {
    createWindow();
  }
});

I have Electron installed locally, and not globally, if it makes a difference. Would love to know why const app = electron.app || electron.remote.app; doesn't resolve.

running with electron-prebuilt in production

I think there are some tools that ship only on npm
And use electron-prebuilt to start even in production.

What do you think about checking an env var, like for example debug module does?

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.