[npm OpenFL] Making use of JavaScript libs

Is it possible, with a JavaScript based npm OpenFL project, to make use of other npm JavaScript libs?

For the purpose of example, I’ve been trying to integrate ws (npmNode.js WebSocket library) to make use of its WebSocketServer (my related post).

I’m able to bring in the ws library through npm install ws, updated wepack.common.js to include a reference to it and imported it in app.js.

However, it’s failing to compile because webpack encounters an “unexpected token”:

[339] ./node_modules/ws/lib/websocket-server.js 202 bytes {0} [built] [failed] [1 error]
    + 337 hidden modules

ERROR in ./node_modules/ws/lib/websocket-server.js
Module parse failed: Unexpected token (55:6)
You may need an appropriate loader to handle this file type.
|       path: null,
|       port: null,
|       ...options
|     };
 @ ./src/app.ts 15:25-59
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./src/app.ts

The token it’s referring to there, is this piece of JavaScript code:

This appears quite a lot in the ws library and to be honest, I’m not sure what to make of it. I’m not familiar with this specific ...options syntax.

This is a more complete snippet of that portion of the ws websocket-server.js code:

constructor(options, callback) {

    options = {
      maxPayload: 100 * 1024 * 1024,
      perMessageDeflate: false,
      handleProtocols: null,
      clientTracking: true,
      verifyClient: null,
      noServer: false,
      backlog: null, // use default (511 as implemented in net.js)
      server: null,
      host: null,
      path: null,
      port: null,

I’ve tried building the project as ES5, ES6 and now TypeScript, with the same results.
I’d appreciate any pointers, thank you.

Ah, found it quite by accident when I was looking up something else. It’s called “spread syntax” and would appear not to be supported by webpack.

It’s a means of merging JavaScript objects.

So it’s not that Webpack doesn’t support spread, but rather the loaders being used. (That’s what the error is referring to when it says “You may need an appropriate loader to handle this file type”).

Typescript was the right move on your part but what I think you’re missing is that the default webpack template for TypeScript in OpenFL doesn’t have a rule for .js files. So that lib is probably getting processed with vanilla JS which may not support the spread operator depending on your environment.

You’ll want to check this out here:

In your webpack common file a better test pattern would be /\.tsx?|\.jsx?$/ to run everything through TypeScript and benefit from improved language support. Disclaimer through, it looks like the npm version of OpenFL is on a rather old version of both Webpack (3.x) and Typescript (2.6.2), so it’s possible you may run into other issues depending on the libraries being used