问题
I'm trying to get node-serialport to work with electron and webpack.
I'm importing serialports as external module:
# webpack.config.js
externals: {
serialport: "serialport"
}
This is the code in my app:
// read NMEA data from serial port
const SerialPort = require('serialport');
console.log(SerialPort.list());
const Readline = SerialPort.parsers.Readline;
const port = new SerialPort('/dev/tty.Redmi-ShareGPS', { baudRate: 4800 });
const parser = port.pipe(new Readline({ delimiter: '\r\n' }));
// Open errors will be emitted as an error event
port.on('error', function(err) {
console.log(err.message);
})
// send NMEA data to GPS.js
parser.on('data', function(data) {
// gps.update(data);
});
Trouble is in first line: const SerialPort = require('serialport');
Webpack compiles everything without error, but I have a browser console error:
Uncaught ReferenceError: serialport is not defined
at Object.<anonymous> (bundle.js:65651)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:65630)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:31520)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:25595)
at __webpack_require__ (bundle.js:20)
at _ol_ (bundle.js:63)
at bundle.js:66
Which origins at this in webpack generated bundle.js:
/* 315 */
/***/ (function(module, exports, __webpack_require__) {
// read NMEA data from serial port
const SerialPort = __webpack_require__(316);
console.log(serialport.list());
const Readline = SerialPort.parsers.Readline;
const port = new SerialPort('/dev/tty.Redmi-ShareGPS', { baudRate: 4800 });
const parser = port.pipe(new Readline({ delimiter: '\r\n' }));
// Open errors will be emitted as an error event
port.on('error', function (err) {
console.log(err.message);
});
// send NMEA data to GPS.js
parser.on('data', function (data) {
// gps.update(data);
});
/***/ }),
/* 316 */
/***/ (function(module, exports) {
module.exports = serialport;
/***/ })
/******/ ]);
The error line is exactly module.exports = serialport;
According to webpack docs on externals, I suppose I somehow need to include serialport as a global variable, but the example is for jQuery which is a js file, and serialport is node module.
How to make it work?
回答1:
After many hours of frustration, I moved
const SerialPort = require('serialport');
from javascript file which is supposed to be bundled by webpack to index.html:
<script>
const SerialPort = require('serialport');
</script>
<script src="dist/bundle.js"></script>
SerialPort is now recognized.
Also, it seems like webpack-dev-server doesn't work very well with Electron and serialport. I have to launch full electron app.
回答2:
Try remote
.
You might also want to try using remote
:
const SerialPort = require( "electron" ).remote.require( "serialport" );
来源:https://stackoverflow.com/questions/46442623/node-serial-port-as-external-module-in-webpack-module-not-found