How can I use various modules in Javascript based on my YML build file?

I am currently working on a web game, which will also be available as a desktop application via electron . I would just like to not require('electron') if I am creating a web version of the game.

My .yml file that I use with build is as follows:

 cmd: browserify {PROJECT_PATH}/js/main.js > {PROJECT_PATH}/js/bundle.js && {PROJECT_PATH}/index.html name: 'web' targets: electron: cmd: browserify {PROJECT_PATH}/js/main.js > {PROJECT_PATH}/js/bundle.js && electron {PROJECT_PATH} 

If my build command was something like node main.js true , I could just refer to the boolean argument and then use it in Javascript either in require('electron') or not. However, I am not sure how this can be done, given the current situation.

In other words, I would like to pass a boolean argument through my .yml assembly file and use the specified boolean like this:

 if (passedBoolean) { const {app, BrowserWindow} = require('electron'); } 

How should I do it? If this is not possible, then what will be the other solution?

+6
source share
1 answer

There are several ways to solve this problem. The first is to request the platform about its capabilities. For example, Electron sets a variable:

 process.versions.electron 

This will not be installed if you work in a browser, so you can check its existence (and you will find out that you work in Electron). Here's the documentation: Electron: Process .

Testing for an attached property can be a little rude, so a slightly simpler way is to wrap an attempt to access the value in try / catch:

 try { process.versions.electron; } catch (err) { console.log('Not electron', err); } 

You can even wrap it in a nice function:

 function isPlatformElectron() { 'use strict'; try { process.versions.electron; return true; } catch (err) { return false; } } if (isPlatformElectron()) { // Do Electron-specific stuff here } 

Alternatively, you can do something similar with the source code (slightly modified):

 let app, BrowserWindow; try { ({app, BrowserWindow} = require('electron')); } catch (err) { console.log('Not electron'); } if (app && BrowserWindow) { console.log('is electron'); } 

I find this version more difficult to read and prefer the approach to functions suggested above, but I thought it would be useful to set an example using destructuring like your original (although in this case you cannot use const).

+2
source

All Articles