首页 > 解决方案 > 内联 html 中的 module.export

问题描述

当我尝试在我的 HTML 文件中导出一个变量并在我的 main.js 文件中导入它时,它会抛出一个错误: SyntaxError: Unexpected token '<' 它指的<!DOCTYPE html>是我的 index.html 开头的,我不知道为什么require不抓取脚本带有模块标签?我只希望变量显示在 main.js

我试过了,global.foo但也没有用

索引.html:

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Minecraft Launcher</title>
  <link href="https://fonts.googleapis.com/css2?family=Open Sans" rel="stylesheet">

  <style>
    body {
      background-color: rgb(0, 0, 0);
      background-position: center;
      color: white;
      font-family: 'Open Sans', sans-serif;
    }
  </style>
</head>

<body>
  <input type="button" value="Try me" id="startbutton">
  <input type="text" name="input" id="input">
  <script>
    require('./renderer.js')

  </script>
  <script type="module">
    module.exports.foo = 5;
  </script>

</body>

</html>

主.js:

const { app, BrowserWindow } = require('electron')

// Variables
let startbutton;

app.on('ready', () => {
  createWindow();
})

function startvariables() {
  console.log("jup")
  startbutton = window.document.getElementById("input")
  console.log(startbutton.value)
}

function createWindow() {
  var mainWindow = new BrowserWindow({
    width: 950,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })
  mainWindow.loadFile('./index.html')
  mainWindow.webContents.openDevTools()
}


setInterval(() => {
  var foo1 = require('./index.html')
  console.log(foo1)
}, 200)

标签: javascriptnode.jselectronexport

解决方案


这绝对行不通:node 和 electron 的require期望一个 JS 文件的实现,无论是来自主进程还是渲染器进程。它无法提取<script>HTML 文件中标记的内容。

看起来你可能正试图将一些数据从你的渲染器传递到你的主进程:电子为此提供了IPC 系统。


推荐阅读