天天看點

Electron+Webpack+SerialPort搭建使用成功備忘錄Using Node.js addons in Electron's renderer with WebpackNode-serial port as external module in webpack - module not found

最近在做一個類收銀系統,找了QT,UWP和Electron,前兩個太過手生,最後選了Electron。用了vue_cli3.x建構的項目,其他一切正常,唯獨node-serialport怎麼編譯怎麼運作都是Cannot read property 'indexOf' of undefined at Function.getFileName,翻遍大江南北,終于找到解決方案,感謝stackoverflow提供的平台。

解決方案:

1、添加完serialport之後electron-rebuild;

2、webpack配置檔案排除serialport子產品,配置如下:

configureWebpack: {
    externals: {
        serialport: 'serialport',
    }
}      

3、複制根據electron編譯生成的【bindings.node】檔案到dist_electron根目錄下;

4、修改public目錄下的index檔案,手動引入serialport:

<body>
  <noscript>
    <strong>We're sorry but wuyou_client doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
  </noscript>
  <div id="app"></div>
  <!-- built files will be auto injected -->
  <script>const SerialPort = require('serialport');</script>
</body>      

做完以上操作之後即可全局使用serialport了,希望後面填坑的人可以少走我的彎路。

參考文章:

Using Node.js addons in Electron's renderer with Webpack

Node-serial port as external module in webpack - module not found

繼續閱讀