在浏览器中运行反应 - 电子时出错 - 未捕获的引用错误:未定义要求

问题描述 投票:0回答:1

我正在尝试制作一个电子反应应用程序,在运行时我在浏览器的控制台上收到错误。

Uncaught ReferenceError: require is not defined
    at Object.events (bundle.js:265:1)
    at __webpack_require__ (bundle.js:410:32)
    at fn (bundle.js:535:21)
    at ./node_modules/webpack/hot/emitter.js (bundle.js:93:20)
    at __webpack_require__ (bundle.js:410:32)
    at fn (bundle.js:535:21)
    at ./node_modules/webpack/hot/dev-server.js (bundle.js:73:19)
    at __webpack_require__ (bundle.js:410:32)
    at bundle.js:1352:11
    at bundle.js:1355:12

webpack.config.js
文件

import { join } from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import {fileURLToPath} from 'url';
const __filename = fileURLToPath(import.meta.url);
import path from  'node:path';
const __dirname = path.dirname(__filename);

export default {
  //This property defines where the application starts
  entry:'./public/main.js',
    
  //This property defines the file path and the file name which will be used for deploying the bundled file
  output:{
    path: path.join(__dirname, '/dist'),
    filename: 'bundle.js',
  

  },
  mode: "development",

  devtool: 'source-map',
  target: 'electron-main',

  //Setup loaders
  module: {
    rules: [
      {
        test: /\.js$/, 
        exclude: /node_modules/,
       
          loader: 'babel-loader',
          resolve: {
            extensions: [".js", ".jsx", ".json"]
        }

        
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif|ico|json)$/,
        exclude: /node_modules/,
        use: ['file-loader?name=[name].[ext]'] // ?name=[name].[ext] is only necessary to preserve the original file name
      },
      {
        test: /\.?js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ['@babel/preset-env', '@babel/preset-react']
          }
        }
      },
      {
        // loads .html files
        test: /\.(html)$/,
        include: [path.resolve(__dirname, "app/src")],
        use: {
            loader: "html-loader"
        }
        },
        {
          // loads .css files
          test: /\.css$/,
          include: [path.resolve(__dirname, "app/src")],
          use: [                    
              "style-loader",
              "css-loader"
          ]
        }

    ],
    
  },
    
  // Setup plugin to use a HTML file for serving bundled js files
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html',
      filename: './index.html',
      favicon: './public/favicon.ico',
      manifest: './public/manifest.json'

      })
  ]
}

package.json
文件

{
  "name": "app3",
  "version": "0.1.0",
  "private": true,
  "main": "./public/main.js",
  "dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "nodemon": "^3.1.4",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4",
    "webpack": "^5.92.1",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^5.0.4"
  },
  "scripts": {
    "start": "webpack-dev-server --config webpack.config.js --port 3000",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "start-dev": "electron .",
    "start:nodemon": " nodemon --watch main.js --exec npm run start-dev"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.24.7",
    "@babel/preset-env": "^7.24.7",
    "@babel/preset-react": "^7.24.7",
    "babel-loader": "^9.1.3",
    "electron": "^31.0.2",
    "electron-builder": "^24.13.3",
    "electron-is-dev": "^3.0.1",
    "html-loader": "^5.0.0",
    "html-webpack-plugin": "^5.6.0"
  },
  "dist": "electron-builder",
  "build": {
    "appId": "com.example.myapp",
    "productName": "My Electron App",
    "directories": {
      "output": "dist"
    }
  },
  "type": "module",
  "targets": {
    "default": {
      "distDir": "./public"
    }
  }
}


.babaelrc
文件

{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-react"
    ]
}

我使用的是 es6,因此 package.json 中的

"type":"module"

当我运行

npm start
时,我的控制台中也没有出现任何错误


> [email protected] start
> webpack-dev-server --config webpack.config.js --port 3000

<i> [webpack-dev-server] Project is running at:
<i> [webpack-dev-server] Loopback: http://localhost:3000/
<i> [webpack-dev-server] On Your Network (IPv4): http://192.168.0.103:3000/
<i> [webpack-dev-server] Content not from webpack is served from 'C:\electron_projects\app3\public' directory
asset bundle.js 46.4 KiB [emitted] (name: main) 1 related asset
asset favicon.ico 3.78 KiB [emitted]
asset ./index.html 1.75 KiB [emitted]
runtime modules 23.2 KiB 8 modules
built modules 6.9 KiB [built]
  cacheable modules 6.69 KiB
    modules by path ./node_modules/webpack/hot/*.js 5.18 KiB
      ./node_modules/webpack/hot/dev-server.js 1.94 KiB [built] [code generated]
      ./node_modules/webpack/hot/log.js 1.74 KiB [built] [code generated]
      ./node_modules/webpack/hot/log-apply-result.js 1.43 KiB [built] [code generated]
      ./node_modules/webpack/hot/emitter.js 75 bytes [built] [code generated]
    ./public/main.js 1.12 KiB [built] [code generated]
    ./node_modules/electron-is-dev/index.js 406 bytes [built] [code generated]
  external "electron" 42 bytes [built] [code generated]
  external "path" 42 bytes [built] [code generated]
  external "node:path" 42 bytes [built] [code generated]
  external "url" 42 bytes [built] [code generated]
  external "events" 42 bytes [built] [code generated]
webpack 5.92.1 compiled successfully in 1100 ms

电子的main.js

import { app, BrowserWindow } from 'electron';
import { join } from 'path';
import isDev from 'electron-is-dev';
import path from  'node:path';
import {fileURLToPath} from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
import {ipcMain}  from 'electron';

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      preload: path.join(__dirname + 'src/others/preload.js'),
      contextIsolation: true,
      enableRemoteModule: true,
      webSecurity: false,

    },
  });

  const startURL = isDev
    ? 'http://localhost:3000'
    : `file://${join(__dirname, '../build/index.html')}`;

  mainWindow.loadURL(startURL);

  mainWindow.on('closed', () => (mainWindow = null));
}

app.on('ready', createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

ipcMain.handle("get/data", async(event,args)=>{
  return await readFromDb();
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow();
  }
});

我已将 Node.js 集成指定为 true。

这是我的文件夹结构。我们可以忽略

backend
fronted
others
,因为它们现在尚未使用。

enter image description here

我不知道如何处理这个错误,因为这是在bundle.js 中。有人可以指导我吗?任何帮助将不胜感激!!

javascript reactjs node.js webpack electron
1个回答
0
投票

require()
语法存在于您的应用程序中的某个位置,并且与现代 React 不兼容,并且更多地在 Node 或 commonjs 中使用,但 Browserify 允许此语法在您的应用程序中运行。

首先安装browserify

npm install -g browserify

在你的 shell 中调用它

browserify index.js > bundle.js

然后将其添加到您的 html 页面

<script src="bundle.js"></script>

现在它不应再返回该错误。

© www.soinside.com 2019 - 2024. All rights reserved.