javascriptnode.jstypescriptelectron

How to provide the package.json version to an electron app? (tsc options?)


I would like to access the version of my application defined in package.json while running an electron application.

I am building my application this way:

I tried the "usual" way of accessing process.env.npm_package_version, that works when I am running locally because it's run by npm, but if I run the actual electron build, this variable is undefined. Likewise, I found things like const { version } = require('./package.json'); but I think package.json is not even included in the electron build.

So basically, what I need is, at the npm run build step, to access process.env.npm_package_version at that time and store it so that it is going to be available in electron.

I have another project where I use vite and I was able to accomplish something like that with the following code in vite.config.mts:

    define: {
      APP_VERSION: JSON.stringify(process.env.npm_package_version),
    },

Can I do something similar with the Typescript compiler? Am I overcomplexifying things?


Solution

  • In the main process, you can get the version from package.json with app.getVersion():

    const { app } = require('electron');
    const version = app.getVersion();
    

    This may give you an unexpected result (the version of the Electron binary) when running your app in local development mode. (See GitHub issue #7085.)