在我的Electron应用程序中,我有一个大文件constants.js
,该文件已导出,并且在整个渲染过程(Web,ESM模块)中都可用。我也想将此文件导入应用程序的 Main Process (节点,CJS模块)中。
即使使用最新版本的Electron / Node中提供的新实验模块,也需要将文件扩展名从constants.js
更改为constants.mjs
。由于此文件在整个应用程序中都是大量引用,因此更改文件扩展名是不可行的。
是否可以在渲染和主进程之间共享我的constants.js
文件?
项目结构:
root
│
├── build (main process)
│ ├── mainElectron.js
│ └── package.json
│
├── source (render process)
│ └── js
│ └── index.js
│ └── support
│ └── constants.js
│
└── package.json
constants.js
export {
Location,
People,
};
const Location = {
COUNTRY: "Canada",
CITY: "Montreal"
};
const People = {
OWNER: "Mr. Owner",
MANAGER: "Mrs. Manager",
DEVELOPER: "Mr. Developer",
};
index.js (渲染过程,Web ESM)
import * as C from "../support/constants.js";
console.log(`${C.People.DEVELOPER} lives in ${C.Location.CITY}`);
mainElectron.js (主进程,Node CJS)
const electron = require("electron");
const app = electron.app;
app.on("ready", () => {
//How to access constants.js file here?
});
答案 0 :(得分:0)
对于以后可能遇到相同问题的任何人,我使用以下方法解决了该问题:
ESM: Tomorrow's ECMAScript modules today! 。
此外,我重构了代码,以使我在 Main Process 和 Renderer Process 之间共享的常量文件现在位于我的./build
文件夹中主流程文件。
项目结构:
root
│
├── build (main process)
│ ├── js
│ │ ├── main
│ │ │ ├── mainElectronESM.js
│ │ │ └── mainElectron.js
│ │ └── support
│ │ └── constants.js
│ └── package.json
│
├── source (render process)
│ └── js
│ └── index.js
│
└── package.json
constants.js
export {
Location,
People,
};
const Location = {
COUNTRY: "Canada",
CITY: "Montreal"
};
const People = {
OWNER: "Mr. Owner",
MANAGER: "Mrs. Manager",
DEVELOPER: "Mr. Developer",
};
mainElectronESM.js (主流程,节点CJS)
require = require("esm")(module);
module.exports = require("./mainElectron.js");
mainElectron.js (主进程,节点ESM)
import { app } from "electron";
import * as C from "../support/constants.js";
app.on("ready", () => {
console.log(`${C.People.DEVELOPER} lives in ${C.Location.CITY}`);
});
index.js (渲染过程,Web ESM)
import * as C from "../../build/js/support/constants.js";
console.log(`${C.People.DEVELOPER} lives in ${C.Location.CITY}`);
答案 1 :(得分:0)
就像TheDarkin1978一样,我在constants.js
和main
进程之间共享一个renderer
文件,不需要ESM。
仅供参考,这是一个使用create-react-app的React应用程序。
应用程序布局:
root
├── src
│ ├─ main/
│ ├─ renderer/
│ ├─ constants.js
│ ├─ electron.js (electron main entry point)
│ └─ index.tsx (webpack / renderer entry point)
└── package.json
constants.js
const WindowEvent = {
close: "app-close",
maximise: "win-maximise",
minimise: "win-minimise"
}
const WindowQuery = {
isMaximised: "is-maximised"
}
module.exports = { WindowEvent, WindowQuery }
main/index.js
const { WindowEvent } = require("../constants")
renderer/ipc/window.js
const { WindowQuery } = require("../../constants")