简体   繁体   中英

Electron, Webpack, React. When using clipboard; 'fs' is not defined

So I'm running electron via export ELECTRON_START_URL=http://localhost:8080 && electron. In a react / webpack / electron desktop app. I'm trying to read from the system clipboard upon paste key combination (ctrl + v).

So electron works, I DO NOT have a Copy & Paste shortcut enabled in my menu definitions (I don't plan on having a menu).

I'm trying to read a key combination on one component within the react app...similar to:

import React, { useState, useCallback, useEffect, useRef } from "react";

import {clipboard} from 'electron';

const Thing = (props) {

  const keyboardHandler = (e) => {
    if (e.keyCode === 86 && e.ctrlKey) {
      let pasted = clipboard.readText();
      console.log(pasted);
    }
  }

  useEffect(() => {
    window.addEventListener('keydown', keyboardHandler);
    // Remove event listeners on cleanup
    return () => {
      window.removeEventListener('keydown', keyboardHandler);
    };
  }, []);
 
  return <SomeComp onKeyDown={ (e) => keyBoardHandler(e)}/>

}

export default Thing;

I'm getting the error:

external_"electron":1 Uncaught ReferenceError: require is not defined
    at eval (external_"electron":1)
    at Object.electron (bundle.js:1167)

EDIT: this is my main.js (electron) code:

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

const path = require('path');
const url = require('url');
let mainWindow;

function createWindow () {
  const startUrl = process.env.ELECTRON_START_URL || url.format({
    pathname: path.join(__dirname, '../index.html'),
    protocol: 'file:',
    slashes: true,
  });
  mainWindow = new BrowserWindow({ width: 700, height: 210, frame: true, transprent: true, hasShadow: true });
  mainWindow.loadURL(startUrl);
  mainWindow.on('closed', function () {
    mainWindow = null;
  });
}

app.commandLine.appendSwitch("enable-transparent-visuals");
app.on('ready', createWindow);
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
app.on('activate', function () {
  if (mainWindow === null) {
    createWindow();
  }
});

add "window." to the require node function as following:

window.require('electron');

That works for me, hope with you too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM