sindresorhus/electron-util

electron-util does not work with esm loader

ntamas opened this issue · 1 comments

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!

Sure, PR welcome.