Electron:使用tyescript在主进程/渲染进程之间共享常量文件

7xzttuei  于 8个月前  发布在  Electron
关注(0)|答案(1)|浏览(107)

Electron w/ Typescript:在主进程和渲染进程之间共享一个constants.ts文件。
文件夹结构:
简体中文

  • 主要
  • main.ts
  • 渲染器
  • renderer.ts
  • 共享
  • constants.ts
//constants.ts

export const constants= {
  foo: '123'
  bar: 'xyz'
}

//main.ts
import { constants} from '../shared/constants'

app.on("ready", async function () {
  console.log(constants)

});

//renderer.ts
import { constants} from '../shared/constants'

console.log(constants)

字符串
IntelliSense正确读取/查看常量。main.ts正确控制台日志常量。然而,renderer.ts抛出错误:Uncaught Error: Cannot find module '../shared/constants'输出js与源代码具有完全相同的结构,(dist/src/(main/shared/renderer))
我使用的是electron typescript quickstart模板:https://github.com/electron/electron-quick-start-typescript
这是我的tsconfig

{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitAny": true,
    "sourceMap": true,
    "outDir": "dist/src",
    "baseUrl": ".",
    "paths": {
      "*": ["node_modules/*"]
    }
  },
  "include": [
    "src/**/*"
  ]
}


有一件事要注意的是,我使用的是旧版本的电子。

// versions
    "@typescript-eslint/eslint-plugin": "^4.33.0",
    "@typescript-eslint/parser": "^4.33.0",
    "electron": "^12.0.0",
    "eslint": "^7.32.0",
    "typescript": "^4.7.2"


我发现这个项目做的正是我想做的,在两个进程之间共享一个常量文件,但无法复制它https://github.com/ci010/electron-vue-next
我只想共享常量,而不是可变的变量/对象。
你知道我哪里做错了吗?

vhmi4jdf

vhmi4jdf1#

我发现了一个简单但不优雅的解决方案(因为在渲染器端,所有常量都被推到全局命名空间中)。请参阅下面的示例(同一文件夹中的所有文件):
const_shared.js

const APP_NAME = "Rocket Launcher";

// exports only if const_shared.js
// is required by 'main' process
if (typeof exports === 'object') {
    exports.APP_NAME = APP_NAME
}

字符串
index.html

<script type="text/javascript" 
 src="const_shared.js"></script>

<script type="text/javascript" 
 src="renderer.js"></script>


renderer.js

// constant APP_NAME is in global
// namespace of 'renderer' process 
// because of 
// <script> with src=const_shared.js
console log(APP_NAME);


main.js

// 'main' process
const { APP_NAME } 
= require("const_shared.js");

console.log(APP_NAME);

相关问题