RobotWebTools / rclnodejs

Node.js version of ROS 2.0 client
https://docs.ros.org/en/humble/Concepts/Basic/About-Client-Libraries.html?highlight=rclnodejs#community-maintained
Apache License 2.0
311 stars 70 forks source link

Unable to selectively import from rclnodejs #868

Closed wayneparrott closed 1 year ago

wayneparrott commented 1 year ago

Recently I impl'ed a small utility in TypeScript that only required a few objects from rclnodejs. So I used this import syntax:

import { init, Node } from 'rclnodejs';

async function main() {
  await init();
  const node = new Node('foo');
  node.spin();
}

This example fails with the following stacktrace:

    if (this._rosVersionChecked) {
             ^

TypeError: Cannot read properties of undefined (reading '_rosVersionChecked')
    at init (/home/wayne/dev/ros_utils/node_modules/rclnodejs/index.js:248:14)
...

Because of the stateful nature of the rcl object of index.js it is not possible to selectively import the init fn and by extension any objects.

This failure is caused by the init() function's this not being bound to the stateful rcl object of index.js. A quick fix is to move the _rosVersionChecked property to the global scope of index.js. This small change enables fine-grained import, e.g., import { init, Node} from rclnodejs rather than the classic wildcard import from rclnodejs, e.g., import * as rclnodejs from 'rclnodejs'

I hope this makes sense. I'll submit a PR for consideration that should make this more clear.