Is it possible to share constants between the main process and the renderer process in electron? I haven't been able to find an elegant solution.
I can share constants between renderer and preload. So far, it seems like exposing the constants through contextBridge is the only way.
Anyone have a cool way of doing this?
If you mean actual constants, like static strings or objects, then yes, it's possible. You can put these constants on a file (or files), and simply import them in both processes.
For ESM, now supported since Electron 28 (see docs), nothing special to do, just use import
/export
:
constants.js
export const myFirstConst = "Hello";
export const mySecondConst = "World";
Renderer & Main
import { myFirstConst, mySecondConst } from "./constants.js";
For CJS, you need to use CJS exports
so it can be required on the main process. If your renderer uses a bundler, you need to make sure it supports CJS exports
when using ES6 import
. For Babel for example, sourceType
has to be set to "unambiguous"
.
constants.js
const myFirstConst = "Hello";
const mySecondConst = "World";
module.exports = { myFirstConst, mySecondConst };
Renderer
import { myFirstConst, mySecondConst } from "./constants";
Main
const { myFirstConst, mySecondConst } = require("./constants.js");
If the constants depend on some renderer code, then you need to use the bridge.