javascript - 如何在 Electron 中使用 import 或 require

标签 javascript node.js electron

我正在尝试构建一个 Electron 应用程序。我想从另一个 js 文件中导入一些函数。但是在使用导入时出现错误显示

cannot use import statement outside a module why this happening


我的代码是 eventsource.js
import { sample } from './eventhandler'
console.log('inside eventsource');
function test(){
console.log('test function')
}
test();
sample();
事件处理程序.js
export function sample(){
console.log('sample')}
原型(prototype).html
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>sample</title>
<script type="module" src="../views/eventsource.js"></script>
</head>
<body class="content">
</body>
</html>

最佳答案

正如错误消息所说,您无法在 Node.js 中使用 ES6 导入。你应该去 requiremodule.exports

const { sample } = require('./eventhandler');
console.log('inside eventsource');
function test() {
  console.log('test function');
}
test();
sample();
function sample() {
  console.log('sample');
}

module.exports.sample = sample
对于 ES6 导出/导入,您需要对该功能的实验性支持。在 Node.Js's site 上阅读更多相关信息.

关于javascript - 如何在 Electron 中使用 import 或 require,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62671803/

相关文章:

javascript - Rails,从下拉菜单中选择不会触发不同的过滤器

javascript - 处理异步 Node redis 函数,同时在两个键上使用 INCR 很尴尬

vue.js - 带有 Vue 和 vue-cli-plugin-electron-builder 的 Electron 应用程序无法与 Tesseract.js 一起使用

javascript - JS Require 语句留下 undefined variable

node.js - 在 Electron react 应用程序中导入 whatsapp-web.js nodejs 模块的问题

javascript - 计算所选文本 javascript/JQuery 的位置?

javascript - Node.JS托管基本网页错误: ENOENT

node.js - 在多个 dynos heroku 应用程序的 express 应用程序上设置 session

javascript - 使用 mongoskin 对 mongodb 进行单个查询或多个查询???

node.js - 使用 req.files 上传文件不适用于 Express 4.x