Ошибка с Node Serialport, используемым в электрон + реакция (веб-пакет)

Я пытаюсь создать кроссплатформенное приложение с использованием электрона и реагировать. Это приложение должно использоваться для связи с последовательным устройством с использованием Node Serialport. И скажу вам в самом начале: я новичок в вещах node.js, включая электрон и react.js)

Я следовал различным руководствам, чтобы перестроить Node Serialport для электрона, испытывая трудности. В конце концов, я уверен, что правильно его восстановил.

Когда я использую обходной путь от Patryk в Stackoverflow и поставить

<script>
  const sp = require('serialport');
  var sPort = sp('/dev/ttyACM0', {baudRate: 115200})
  sPort.write(new Uint8Array([0xff, 0x41, 0x01, 0x00, 0x42, 0xee]))
</script>

в index.hmtl я могу общаться со своим последовательным устройством. Но я не знаю, как я могу использовать последовательное соединение в моих дальнейших .js-файлах, таких как App.js.

когда я положил

var SerialPort = require('serialport');

or

var SerialPort = require( "electron" ).remote.require( "serialport" );

в мои .js-файлы я получаю следующие ошибки/предупреждения:

Консольный вывод от npm run dev

09:48:02 react.1      |  Compiling...
09:48:04 react.1      |  Compiled with warnings.
09:48:04 react.1      |  ./src/App.js
09:48:04 react.1      |    Line 7:  'SerialPort' is assigned a value but never used  no-unused-vars
09:48:04 react.1      |  ./node_modules/bindings/bindings.js
09:48:04 react.1      |  81:22-40 Critical dependency: the request of a dependency is an expression
09:48:04 react.1      |  ./node_modules/bindings/bindings.js
09:48:04 react.1      |  81:43-53 Critical dependency: the request of a dependency is an expression
09:48:04 react.1      |  Search for the keywords to learn more about each warning.
09:48:04 react.1      |  To ignore, add // eslint-disable-next-line to the line before.

Сообщение об ошибке в электронном окне:

TypeError: exists is not a function
Function.getRoot
node_modules/bindings/bindings.js:158
  155 |   // Avoids an infinite loop in rare cases, like the REPL
  156 |   dir = process.cwd()
  157 | }
> 158 | if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) {
  159 |   // Found the 'package.json' file or 'node_modules' dir; we're done
  160 |   return dir
  161 | }
View compiled
bindings
node_modules/bindings/bindings.js:60
  57 | 
  58 | // Get the module root
  59 | if (!opts.module_root) {
> 60 |   opts.module_root = exports.getRoot(exports.getFileName())
  61 | }
  62 | 
  63 | // Ensure the given bindings name ends with .node
View compiled
./node_modules/@serialport/bindings/lib/linux.js
node_modules/@serialport/bindings/lib/linux.js:1
> 1 | const binding = require('bindings')('bindings.node')
  2 | const AbstractBinding = require('@serialport/binding-abstract')
  3 | const linuxList = require('./linux-list')
  4 | const Poller = require('./poller')
View compiled
__webpack_require__
/home/bas/Documents/Projects/MicroGator/Code/GatorRemoteElectron/webpack/bootstrap 89408b2d7db2f964ac18:678
  675 | };
  676 | 
  677 | // Execute the module function
> 678 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
  679 | 
  680 | // Flag the module as loaded
  681 | module.l = true;
View compiled
fn
/home/bas/Documents/Projects/MicroGator/Code/GatorRemoteElectron/webpack/bootstrap 89408b2d7db2f964ac18:88
  85 |      console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
  86 |      hotCurrentParents = [];
  87 |  }
> 88 |  return __webpack_require__(request);
  89 | };
  90 | var ObjectFactory = function ObjectFactory(name) {
  91 |  return {
View compiled
(anonymous function)
node_modules/@serialport/bindings/lib/index.js:14
  11 |     break
  12 |   default:
  13 |     debug('loading LinuxBinding')
> 14 |     module.exports = require('./linux')
  15 | }
  16 | 
  17 | 
View compiled
./node_modules/@serialport/bindings/lib/index.js
http://localhost:5000/static/js/bundle.js:18558:30
__webpack_require__
/home/bas/Documents/Projects/MicroGator/Code/GatorRemoteElectron/webpack/bootstrap 89408b2d7db2f964ac18:678
  675 | };
  676 | 
  677 | // Execute the module function
> 678 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
  679 | 
  680 | // Flag the module as loaded
  681 | module.l = true;
View compiled
fn
/home/bas/Documents/Projects/MicroGator/Code/GatorRemoteElectron/webpack/bootstrap 89408b2d7db2f964ac18:88
  85 |      console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
  86 |      hotCurrentParents = [];
  87 |  }
> 88 |  return __webpack_require__(request);
  89 | };
  90 | var ObjectFactory = function ObjectFactory(name) {
  91 |  return {
View compiled
./node_modules/serialport/lib/index.js
node_modules/serialport/lib/index.js:2
  1 | const SerialPort = require('@serialport/stream')
> 2 | const Binding = require('@serialport/bindings')
  3 | const parsers = require('./parsers')
  4 | 
  5 | /**
View compiled
__webpack_require__
/home/bas/Documents/Projects/MicroGator/Code/GatorRemoteElectron/webpack/bootstrap 89408b2d7db2f964ac18:678
  675 | };
  676 | 
  677 | // Execute the module function
> 678 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
  679 | 
  680 | // Flag the module as loaded
  681 | module.l = true;
View compiled
fn
/home/bas/Documents/Projects/MicroGator/Code/GatorRemoteElectron/webpack/bootstrap 89408b2d7db2f964ac18:88
  85 |      console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
  86 |      hotCurrentParents = [];
  87 |  }
> 88 |  return __webpack_require__(request);
  89 | };
  90 | var ObjectFactory = function ObjectFactory(name) {
  91 |  return {
View compiled
./src/App.js
src/App.js:7
  4 | 
  5 | import 'typeface-roboto'
  6 | 
>  7 | var SerialPort = require('serialport');;
  8 | 
  9 | class App extends Component {
  10 |   render() {

Мой App.js выглядит так:

import React, { Component } from 'react';
import TargetTabs from './components/TargetTabs'
import './App.css';

import 'typeface-roboto'

var SerialPort = require('serialport');

class App extends Component {
  render() {
    return (
    <div>
      <TargetTabs />
    </div>
    );
  }
}

export default App;

Поэтому, если бы вы могли указать мне правильное направление, чтобы либо использовать переменную из блока сценария в index.html в других моих js-файлах, либо устранить предупреждения/ошибки, чтобы я мог использовать стандартное требование, я был бы очень признателен.

Возможно даже оба... :)


person Knalltuete    schedule 19.09.2018    source источник
comment
Не могли бы вы опубликовать свой код app.js, пожалуйста?   -  person UpTheCreek    schedule 19.09.2018
comment
Кажется, это не имеет отношения к node-serialport, а к тому, как обслуживаются статические файлы. Я новичок в node.js, и у меня была ошибка, которая осталась незамеченной.   -  person Knalltuete    schedule 30.10.2018