电子/乏味:未定义require“ events”

问题描述

我对乏味的/ webpack /节点/电子有疑问吗?我不确定。

复制步骤:

  • git clone https://github.com/codesbiome/electron-react-webpack-typescript-2020
  • yarn install
  • yarn add tedious
  • yarn add @types/tedious

然后将以下行添加App.tsx(或其他任何地方,仅此而已):

    const connectToDb = (): Promise<Connection> => {
      return new Promise((resolve,reject) => {
        const config = { // those data doesn't matter much
          authentication: {
            options: {
              userName: "sa",// update me
              password: "" // update me
            },type: "default"
          },server: "test_db@localhost",// update me
          options: {
            database: "test",//update me
            encrypt: true
          }
        };
      
        const connection = new Connection(config) // error is caused by this
        connection.connect()
      })
    }
    
    connectToDb().then(res => {
      console.log('res: ',res);
    }).catch(err => {
      console.log('err: ',err);
    })

并且控制台(View -> Toggle Developer Tools)中发生以下错误

Uncaught ReferenceError: require is not defined
    at Object.events (index.js:140037)
    at __webpack_require__ (index.js:790)
    at fn (index.js:101)
    at Object../node_modules/tedious/lib/bulk-load.js (index.js:99091)
    at __webpack_require__ (index.js:790)
    at fn (index.js:101)
    at Object../node_modules/tedious/lib/tedious.js (index.js:110052)
    at __webpack_require__ (index.js:790)
    at fn (index.js:101)
    at Module.<anonymous> (index.js:139704)

单击堆栈跟踪中的第一个重定向显示module.exports = require("events")中的错误,这正是问题所在的require

我尝试操纵webpack设置也尝试启用nodeIntegration和其他设置,但没有任何结果。有什么想法吗?

解决方法

我知道了。

修复: main.tsx-> BrowserWindow-> webPreferences,将contextIsolation更改为false,也将nodeIntegration更改为true

更改后,要求参考错误消失。