How to use a native node.js addon in React

白昼怎懂夜的黑 提交于 2021-02-10 14:25:44

问题


I have a react project in which I would like to use this native node.js addon, which is a wrapper for a C++ SDK.

I've successfully used this module in the past within an Electron project, and can run the sample successfully with node as well.

My question is how I would be able to use this in React, or write my own React friendly solution using the C++ SDK.

I've tried to clone the module and place it under a lib folder in my react project, I ran npm install within that folder to install it's dependencies and tried to run the included example directly with node. This went fine. But using the sample directly from within my React app fails with the following error code ts3client.on is not a function.

So it passes the line were the library is required with var ts3client = require('../../lib/node-ts3sdk-client/api.js'); but that's the furthest I managed to get. I could play around a little bit more, but would like to get some opinions on what might be the best approach here.

Edit As requested I have added a small example to reproduce the issue I am facing.

  1. Create a simple react app
    npm init react-app so-node-addon-react

  2. Clone this repository under src/lib/
    git clone https://github.com/svenpaulsen/node-ts3sdk-client.git

  3. Install the module's dependencies
    cd node-ts3sdk-client
    npm install

  4. Expose some part of the client example by wrapping the try-catch block starting from line 160 in an exported function like so

export function connect() {
  try { ... }
  catch { ... }
}
  1. Call the function from your project's App.tsx
import { connect } from './lib/node-ts3sdk-client/examples/client_minimal'
...
connect()
  1. Run the project npm start

This should result in the following error: ts3client.on is not a function

来源:https://stackoverflow.com/questions/57061352/how-to-use-a-native-node-js-addon-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!