在Node / Electron环境中共享ESM“.js”模块

问题描述 投票:0回答:1

在我的Electron应用程序中,我有一个大文件constants.js,它可以在Render Process(Web,ESM Modules)中导出和使用。我还想在应用程序的主进程(节点,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(主要流程,节点CJS)

const electron = require("electron");
const app = electron.app;

app.on("ready", () => {

    //How to access constants.js file here?
});
javascript node.js module electron
1个回答
0
投票

对于今后可能会遇到同样问题的任何人,我通过使用以下方法解决了这个问题:

ESM: Tomorrow's ECMAScript modules today!

此外,我重新构建了我的代码,以便我在Main Process和Renderer Process之间共享的常量文件现在位于带有Main 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}`);
© www.soinside.com 2019 - 2024. All rights reserved.