electron 如何导入react js文件?

9jyewag0  于 2022-12-08  发布在  Electron
关注(0)|答案(1)|浏览(309)

我正在使用react和electron构建一个电子应用程序。我是react和electron的新手,我遇到了一个关于如何将react index.js中的函数导入electron main.js的问题
为什么我需要将该函数导入main.js文件?因为我需要从main.js传递react应用程序的依赖项,而这些依赖项大多数都是函数依赖项。
下面是index.js中接收依赖项的函数。

mport React from 'react';
import ReactDOM from 'react-dom/client';
import './App.scss'
import './configFile'
import './fonts/NotoSansSC.otf'

import { init as initConfigFile } from './configFile'
import { init as initLanguage } from './international/language'
import App from './App';

export function dependency(config, saveConfigFile, createNewUser) {

}

const root = ReactDOM.createRoot(document.getElementById('root'))
initLanguage()
initConfigFile({
  parentPwd: null,
  qa: {
    'configQuestion1': '123',
    'configQuestion2': '123',
    'configQuestion3': '123'
  },
  timeRangesNotAllowToUseTheComputer: [

  ],
  language: 'en',
  onlyWorkForTheUsers: ['test'],
  usernames: ['onTheRoad', 'test'],
  timeZones: { '中国': 'cn', '英国': 'uk' },
  choosedTimeZone: 'uk'
}, null, null)
root.render(
  <App />
)

下面是main.js文件

const path = require('path');
const { app, BrowserWindow } = require('electron');
const isDev = require('electron-is-dev');

function createWindow() {
  // Create the browser window.
  const win = new BrowserWindow({
    width: 800,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
    },
  });

  // and load the index.html of the app.
  // win.loadFile("index.html");
  win.loadURL(`file://${path.join(__dirname, '../build/index.html')}`);
  // Open the DevTools.
  if (isDev) {
    win.webContents.openDevTools({ mode: 'detach' });
  }
}

// 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.whenReady().then(createWindow);

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bars 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', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

我尝试使用require导入文件

const index = require('./index.js')

当我构建react应用程序时,没有抛出错误,但当我使用electron .启动electron时,出现如下错误:

A JavaScript error occurred in the main process
Uncaught Exception:
/home/zxw/Desktop/bsd/src/index.js:1
import React from 'react';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1040:15)
    at Module._compile (node:internal/modules/cjs/loader:1076:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1175:10)
    at Module.load (node:internal/modules/cjs/loader:988:32)
    at Module._load (node:internal/modules/cjs/loader:829:12)
    at c._load (node:electron/js2c/asar_bundle:5:13339)
    at Module.require (node:internal/modules/cjs/loader:1012:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/home/zxw/Desktop/bsd/public/main.js:4:15)
libva error: vaGetDriverNameByIndex() failed with unknown libva error, driver_name = (null)

然后我尝试通过import语句加载函数,如下所示

import {dependency} from '../src/index'

当我构建react应用程序时,没有抛出错误,但当我启动电子应用程序时,我得到了这样的错误

A JavaScript error occurred in the main process
Uncaught Exception:
/home/zxw/Desktop/bsd/public/main.js:4
import {dependency} from '../src/index'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1040:15)
    at Module._compile (node:internal/modules/cjs/loader:1076:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1175:10)
    at Module.load (node:internal/modules/cjs/loader:988:32)
    at Module._load (node:internal/modules/cjs/loader:829:12)
    at c._load (node:electron/js2c/asar_bundle:5:13339)
    at loadApplicationPackage (/home/zxw/Desktop/bsd/node_modules/electron/dist/resources/default_app.asar/main.js:121:16)
    at Object.<anonymous> (/home/zxw/Desktop/bsd/node_modules/electron/dist/resources/default_app.asar/main.js:233:9)
    at Module._compile (node:internal/modules/cjs/loader:1120:14)
libva error: vaGetDriverNameByIndex() failed with unknown libva error, driver_name = (null)

是否有办法将dependencies从main.js传递到index.js?

kx7yvsdv

kx7yvsdv1#

首先安装axios和express然后在react src文件中添加一个名为appDependency的文件

import axios from 'axios'

export function saveConfigFile(config) {
    try {
        axios.put('http://localhost:8888/config', config).then(response => {
            if (response.status !== 200) {
                throw response.data
            }
        })
    } catch (e) {
        console.error(`Error occrred while saving the config file: ${e}`)
        throw e
    }
}

export function createNewUser(username, pwd) {
    try {
        axios.post('http://localhost:8888/users', {
            username: username,
            pwd: pwd
        }).then((response) => {
            if (response.status !== 200) {
                throw response.data
            }
        })
    } catch (e) {
        console.error(`Error occrred while creating new user. ${e}`)
        throw e
    }
}

async function fetchTheConfig() {
    return await axios.get('http://localhost:8888/config').then((response) => {
        console.log(`The response is ${JSON.stringify(response.data)}`)
        if (response.status !== 200) {
            throw response.data
        } else {
            return response.data
        }
    })
}

export function getConfigFile() {
    try {
        return fetchTheConfig()
    } catch (e) {
        console.error(`err occurred while fetching the config file. ${e}`)
        throw e
    }
}

并在electronmain.js文件中使用express创建了一个服务器

const path = require('path');
const { app, BrowserWindow } = require('electron');
const express = require('express')
const exApp = express()
exApp.use(express.urlencoded())
exApp.use(express.json())

const config = {
  parentPwd: null,
  qa: {
    'configQuestion1': '123',
    'configQuestion2': '123',
    'configQuestion3': '123'
  },
  timeRangesNotAllowToUseTheComputer: [

  ],
  language: 'en',
  onlyWorkForTheUsers: ['test'],
  usernames: ['onTheRoad', 'test'],
  timeZones: { '中国': 'cn', '英国': 'uk' },
  choosedTimeZone: 'uk'
}

function configFile(req, res) {
  console.log(`request received getConfigFile`)
  res.status(200).send(config)
}

function saveConfigFile(req, res) {
  console.log(`The body is ${req.body.timeRangesNotAllowToUseTheComputer}`)
  res.status(200).send()
}

function createNewUser(req, res) {
  console.log(`The req is `)
}

function appDependecys() {
  exApp.get('/config', configFile)
  exApp.put('/config', saveConfigFile)
  exApp.post('/users', createNewUser)

  exApp.listen(8888)
}

appDependecys()

在react index.js中,我将其更改为

import React from 'react';
import ReactDOM from 'react-dom/client';
import './App.scss'
import './configFile'
import './fonts/NotoSansSC.otf'

import { init as initConfigFile } from './configFile'
import { init as initLanguage } from './international/language'
import App from './App';
import { getConfigFile, saveConfigFile, createNewUser } from './appDependency'

const root = ReactDOM.createRoot(document.getElementById('root'))
getConfigFile().then((cfg) => {
  console.log(`The fucking config is ${cfg}`)
  initLanguage()
  initConfigFile(cfg, saveConfigFile, createNewUser)
  root.render(
    <App />
  )
})

相关问题