在导入“事件”时,带有Webpack的电子锻造获得“未定义要求”

g52tjvyc  于 2022-11-13  发布在  Webpack
关注(0)|答案(2)|浏览(185)

我最近开始了一个新的项目,使用electron forge和webpack模板。我正在创建一个简单的类来进行身份验证,并希望在nodejs中使用事件系统。我正在使用import语法,但收到一个错误消息,说require未定义。我不希望打开nodeIntegration,我认为webpack会自动使用nodejs事件系统的browserfy版本:
如果您的代码在Node.js中运行,事件模块是内置的。如果您的代码在浏览器中运行,browserify或webpack等捆绑包也会包含事件模块。
安装browserify事件模块也不能解决这个问题。我也试着排除node_modules/events文件夹,希望webpack能使用它自己的事件模块,但我没有成功。下面是我的代码:

import { EventEmitter } from 'events';

export default class Auth {
  constructor(socket) {
  }

  setToken(token) {
    this.token = token;
    localStorage.setItem('token', token);
    this.emit('token', token);
  }

  checkToken() {
    if(localStorage.getItem("token") !== null) {
      this.setToken(localStorage.getItem("token"));
    } else {
      this.emit('false', false);
    }
  }

  getToken() {
    return localStorage.getItem("token");
  }

  setAuth(auth) {
    this.emit('auth', auth);
    this.isAuth = auth;
  }
  
}

以下是我的webpack渲染器配置:

const rules = require('./webpack.rules');
const webpack = require('webpack');
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');

rules.push({
  test: /\.css$/,
  use: [{ loader: 'style-loader' }, { loader: 'css-loader' }],
});

const assets = [ 'assets' ];
const copyPlugins = assets.map((asset) => {
  return new CopyWebpackPlugin({
    patterns: [{ from: path.resolve(__dirname, 'src/renderer/', asset), to: asset }],
  });
});

module.exports = {
  // Put your normal webpack config below here
  module: {
    rules,
  },
  plugins: [
      new webpack.ProvidePlugin({
          $: 'jquery',
      }),
      ...copyPlugins
  ],
  resolve: {
    alias: {
      'components': path.resolve(__dirname, './src/renderer/components'),
      'pages': path.resolve(__dirname, './src/renderer/pages'),
      'core': path.resolve(__dirname, './src/renderer/core'),
    },
    extensions: ['.js']
  },
};

下面是我的webpack规则配置:

module.exports = [
  // Add support for native node modules
  {
    test: /\.node$/,
    use: 'node-loader',
  },
  {
    test: /\.(m?js|node)$/,
    parser: { amd: false },
    use: {
      loader: '@marshallofsound/webpack-asset-relocator-loader',
      options: {
        outputAssetBase: 'native_modules',
      },
    },
  },
];

下面是错误:

external "events":
Uncaught ReferenceError: require is not defined
    at Object.events (external "events":1)
    at __webpack_require__ (bootstrap:832)
    at fn (bootstrap:129)
    at Module../src/renderer/core/Auth.js (Auth.js:1)
    at __webpack_require__ (bootstrap:832)
    at fn (bootstrap:129)
    at Module../src/renderer/index.js (index.js:1)
    at __webpack_require__ (bootstrap:832)
    at fn (bootstrap:129)
    at Object.0 (routes.js:40)
mec1mxoz

mec1mxoz1#

在休息了一会儿之后,我意识到解决办法很简单:
我只需要将以下内容添加到我的渲染器配置中:

target: 'web'
yhived7q

yhived7q2#

解决方案是使用来自electronContextBridge API作为电子伪造Webpack模板
preload.js

import { ipcRenderer, contextBridge } from "electron";

contextBridge.exposeInMainWorld("electron", {
  notificationApi: {
    sendNotification(message) {
      ipcRenderer.send("notify", message);
    },
  },
  batteryApi: {},
  fileApi: {},
});

main.js

const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      worldSafeExecuteJavaScript: true,
      preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
    },
 });

ipcMain.on("notify", (_, message) => {
   new Notification({ title: "Notification", body: message }).show();
});

package.json

"plugins": [
    [
      "@electron-forge/plugin-webpack",
      {
        "mainConfig": "./webpack.main.config.js",
        "renderer": {
          "config": "./webpack.renderer.config.js",
          "entryPoints": [
            {
              "html": "./src/index.html",
              "js": "./src/renderer.js",
              "name": "main_window",
              "preload": {
                "js": "./src/preload.js"
              }
            }
          ]
        }
      }
    ]
  ]

则使用以下代码将调用本机通知消息

electron.notificationApi.sendNotification("Finally!");

相关问题