【发布时间】:2017-09-27 08:09:11
【问题描述】:
我正在尝试让 node-serialport 与电子和 webpack 一起使用。
我是importing serialports as external module:
# 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;
根据webpack docs on externals,我想我需要将serialport作为全局变量包含在内,但示例是针对jquery的,它是一个js文件,serialport是节点模块。
如何让它发挥作用?
【问题讨论】:
标签: javascript node.js webpack node-serialport