如何导出分配给变量的要求?

How to export a require assigned to a variable?

我正在执行以下操作以使 require<app></app>

中可见

index.html:

<script>
  var electron = require('electron')
</script>
<app></app>
<script src="bundle.js"></script>

App.vue:

const ipc = electron.ipcRenderer
console.log(ipc)

但是我在使用 ESLint 时遇到 un-usedun-defined var 错误,所以我决定这样做:

requires.js:

var electron = require('electron')

exports.electron = electron

index.html:

  <script src="requires.js"></script>
</head>

<body>
  <app></app>
  <script src="bundle.js"></script>

但现在我得到这个错误:requires.js:3 Uncaught ReferenceError: exports is not defined

导出和导入电子的正确方法是什么require

注意: 直接在 App.vue 中要求 electron 不起作用。您只能在 index.html

中要求 electron

完整示例: https://github.com/alexcheninfo/vue-electron-simple

您在这里似乎想做的是将 electron 定义为全局变量;为此,您可以在第一个示例中的 index.html 中设置 window.electron = require('electron')。 (它将在您bundle.js中可用)

但是,对于这种不良做法并没有必要使用全局变量。你应该做的,只是在你的代码中使用 require 。你说这不行:之所以不行,可能是你用的是webpack或者类似create bundle.js的东西。此外,您可能 运行 Node 而非 Electron 中的捆绑过程,因此 require('electron') 无法按预期工作。请注意,它适用于您的 index.html,它不属于捆绑包。

如果您想继续使用此设置,您可以重命名 Electron 的 require 以区分捆绑期间解决的 require 和 运行 时解决的 require。换句话说,window.electronRequire = requireindex.html 的脚本标记中,然后在您的代码中使用 electronRequire('electron')

话虽如此,为什么首先要捆绑所有内容? Electron 具有完整的 Node 集成,因此您可以使用常规的 Node 模块;这些文件也不是通过 HTTP 发送的,因此将所有内容捆绑到一个文件中几乎没有什么好处。