【问题标题】:How to export a require assigned to a variable?如何导出分配给变量的需求?
【发布时间】:2016-07-08 08:00:37
【问题描述】:

我正在执行以下操作以使 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 错误,所以我决定这样做:

需要.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

【问题讨论】:

  • 也许是module.exports 而不是exports

标签: javascript node.js webpack vue.js electron


【解决方案1】:

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

但是,对这种不好的做法使用全局变量并没有必要。你应该做的就是在你的代码中使用require。你说这不起作用:它不起作用的原因可能是你正在使用 webpack 或类似的东西来创建bundle.js。此外,您可能在 Node 中而不是在 Electron 中运行捆绑过程,因此 require('electron') 无法按预期工作。请注意,它适用于您的 index.html,它不是捆绑包的一部分。

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

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

【讨论】:

  • 感谢您的建议。好吧,我正在使用 Vue.js,它使用 .vue 文件。 Webpack 将它们编译成 JavaScript。不过我觉得你说得对,我会考虑不捆绑代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多