Import values from package.json into electron/nodejs application.

Ganesh Rathinavel
2 min readJan 26, 2019

--

Introduction

I have seen many users importing ‘package.json’ directly into the node.js project. This is a programming disaster as it could leak your sensitive information such as “scripts” or private TOKENS into the bundled js files. There is no single clear-cut solution to get this done inside an electron app. It has to be handled intelligently using algorithms and fallback. This was originally implemented inside OpenMTP — Advanced Android File Transfer Application for macOS.

Implementation

  • Install npm packages
$ npm install electron-root-pathor $ yarn add electron-root-path
  • Add the below code inside your webpack.config.js file (for both production and development)
import { rootPath } from 'electron-root-path';const pkg = require(join(rootPath, 'package.json'));plugins: [
new webpack.DefinePlugin({
PKG_INFO: {
productName: JSON.stringify(pkg.productName),
description: JSON.stringify(pkg.description),
name: JSON.stringify(pkg.name),
author: JSON.stringify(pkg.author),
version: JSON.stringify(pkg.version),
repository: JSON.stringify(pkg.repository),
homepage: JSON.stringify(pkg.homepage)
}
}),
]
  • Create a file ./app/pkginfo.js and add the below code
'use strict';import { join } from 'path';
import { readFileSync } from 'fs';
import { rootPath } from 'electron-root-path';
let _pkginfo = {};// eslint-disable-next-line no-undef
if (typeof PKG_INFO !== 'undefined' && PKG_INFO !== null) {
// eslint-disable-next-line no-undef
_pkginfo = PKG_INFO;
} else {
/* This is a fallback incase the webpack DefinePlugin modules hasn't been initialized yet. */
/* Developement mode only */
_pkginfo = JSON.parse(
readFileSync(join(rootPath, 'package.json'), { encoding: 'utf8' })
);
}
export const pkginfo = _pkginfo;

More repos

License

tutorial-electron-nodejs-import-packageinfo is released under MIT License.

Copyright © 2018-Present Ganesh Rathinavel

--

--