2017-09-27 80 views
0

我試圖讓node-serialport與電子和webpack一起工作。作爲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是節點模塊。

如何使它工作?

<script> 
    const SerialPort = require('serialport'); 
</script> 
<script src="dist/bundle.js"></script> 

的SerialPort是目前公認:

回答

0

多小時的挫折後,我從JavaScript這是應該由被的WebPack捆綁index.html文件移到

const SerialPort = require('serialport'); 

此外,它似乎像webpack-dev-server不能很好地與電子和串行端口。我必須推出全電子應用程序。