electron-userland / electron-webpack

Scripts and configurations to compile Electron applications using webpack
https://webpack.electron.build/
903 stars 170 forks source link

Wrong `getVersion` reported when using `electron-webpack`. #353

Open wdanilo opened 4 years ago

wdanilo commented 4 years ago

When using electron-webpack dev, and running in main process console.log(Electron.app.getVersion()) I get 8.0.2 as a result, which is Electron version. According to https://github.com/electron/electron/issues/7085 , the version reported by getVersion depends on how the electron command was run under the hood:

In development the version returned by app.getVersion() depends on how you launched your app. If you launched it with electron path/to/app/package_dir the version will match the one in your package.json, however, if you launched your app with electron path/to/main.js then you'll get the Electron version. This is because in the latter case Electron will actually read the package.json of the default app, which doesn't specify a version, so it will default to the Electron version. Once you package your app the version will always be read from your package.json.

I believe the current behavior is very confusing and error prone. Can we always report the correct version when using electron-webpack instead?

msemtd commented 4 years ago

I don't think that electron-webpack provides an API as such and I wouldn't want to monkey-patch the electron APIs, so I usually have a little bit of code in each electron app like this...

import { app, remote } from 'electron'
const isDevelopment = process.env.NODE_ENV !== 'production'
const isRenderer = (process && process.type === 'renderer')
const appVer = isDevelopment ? process.env.npm_package_version : (isRenderer ? remote.getVersion() : app.getVersion())
export { appName, appVer, isDevelopment, isRenderer }

In an electron-webpack app this can be in the common dir and thus usable from both main and renderer processes. I appreciate that this is a workaround.

loopmode commented 4 years ago

If I understand correctly, this is about the version defined in the package.json of the electron package itself, right? If that is the case, I would go for something like this:

const { version } = require(path.resolve(require.resolve('electron'), 'package.json')));

Require should work with a json file, path.resolve should give you the actual path of a package, so picking the version from the package.json there should work reliably. (Disclaimer: not tested or verified at all)

Total bogus. Just tried require.resolve('electron') in a different project (not electron-webpack) and it gives me a path ending in node_modules\electron\dist\resources\electron.asar\renderer\api\exports\electron.js - no way to get package.json from there. Sorry :)