首页 > 解决方案 > “require”没有定义,但是我不能使用import,那我该怎么办?

问题描述

我想用电子申请,我又得到了同样的错误:

Uncaught ReferenceError: require is not defined
    at render.js:8

这是我的render.js文件:

const button = document.getElementById('button');
button.onclick = printlog;

function printlog() {
    console.log('Print')
}

const fs = require('fs');
const folder = './src/';
fs.readdir(testFolder, (err, files) => {
  files.forEach(file => {
    console.log(file);
  });
});

这是我的index.js文件:(主要)

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

// Handle creating/removing shortcuts on Windows when installing/uninstalling.
if (require('electron-squirrel-startup')) { // eslint-disable-line global-require
  app.quit();
}

const createWindow = () => {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1000,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
    }
  });

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'index.html'));

  // Open the DevTools.
  mainWindow.webContents.openDevTools();
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.

最后,这是我的index.html文件:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <link rel="stylesheet" href="index.css">
    <script defer src="render.js"></script>
  </head>
  <body>
    <h1>test</h1>
    <button id="button">Button</button>
  </body>
</html>

我不认识任何懂 js 的人,所以我问了一个不和谐的服务器,他们说我需要在脚本的 index.html 处执行 type="module",但它仍然没有用。如果我将它换成导入,它仍然不想工作,而且我根本不知道如何解决这个问题。请以某种方式帮助我,感觉就像我永远坚持下去。

标签: javascriptnode.jselectron

解决方案


推荐阅读