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

后端 未结 4 1342
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-10 20:23

I have the following renderer:

import SerialPort from \"serialport\";

new SerialPort(\"/dev/tty-usbserial1\", { baudRate: 57600 });

It\'s buil

4条回答
  •  遇见更好的自我
    2021-02-10 20:56

    I think @Alec Mev answer is amazing, at the time of written.

    In my case, all of the internet suggested hacks (like copying, loaders, etc..) was unsuccessful and really unclear.

    I wanted to call my own native node addon through electron renderer, but as mentioned by Alec Webpack doesn't handle the .node file as required. So in my case:

    Folder structure

    Electron project dir
    │   electron.main.js
    │   package.json
    │
    ├───Addon
    │   │   addon.js
    │   │   package.json
    │   │
    │   └───dist
    │           addon.node
    │
    └───render-site
        │   index.html
        │   js.js
        │   webpack.config.js
        │
        └───build
    
    • THIS IS DEMO - render-site is your webpack site, dist is your addon binary location.

    Very important is to set webpack target to 'electron-renderer', it allow you to use require of electron and other node modules like fs much more easily.

    In your site call the addon like the docs suggested

    const addon = require('electron').remote.require('./addon/dist/addon.node');
    

    That's it. You can run the webpack and serve the site while using the addon.

    Production is very straight forward, you just make sure to copy the addon to the build of electron (I'm using electron-builder copying system) with the relative path to electron.main.js.

    Hope it helped.

提交回复
热议问题