我正在尝试让 node-serialport 与电子和 webpack 一起使用。
# webpack.config.js
externals: {
serialport: "serialport"
}
这是我的应用程序中的代码:
// 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);
});
麻烦在第一行:const SerialPort = require('serialport');
Webpack 编译一切都没有错误,但我有一个浏览器控制台错误:
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
这在 webpack 生成的 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;
/***/ })
/******/ ]);
错误线正是module.exports = serialport;
根据externals 上的webpack 文档,我想我需要以某种方式将串行端口作为全局变量包含在内,但该示例适用于 jQuery,它是一个 js 文件,串行端口是节点模块。
如何让它发挥作用?