Writing WebSocket client with TypeScript running both on browser and Node.JS - node.js

I am writing a typescript code that would run in a web-browser and would be tested with Node.JS.
My client code looks like below.
import * as WebSocket from 'ws';
export class SomeClient {
constructor(url) {
this.ws = new WebSocket(url);
}
send(data: any) {
this.ws.send(data);
}
}
I had no problem in writing a unit test code using mocha/chai.
However, trying to bundle this code, browserify includes all the 'ws' node module and the size of the output file is almost 100kb. If I remove the import 'ws' statement, the bundle file size shrinks less than 1kb. But, in this case, the Node.JS test complains with 'WebSocket is not defined' error.
I think, this is because WebSocket is natively supported in web browsers but not supported in Node.JS and the external 'ws' module is required to run properly.
How can I make a bundle with the minimum size for web browsers yet can use in Node.JS???

Try isomorphic-ws:
npm i isomorphic-ws -s
or universal-websocket-client:
npm install --save universal-websocket-client

I struggled with the same problem, best solution I could find was to use isomorphic-ws create a decs.d.ts in my typescript rootDir with the following content
declare module "isomorphic-ws";
and then use it inside typescript like that:
import { IsoWebSocket } from "isomorphic-ws";
var ws = new IsoWebSocket("wss://echo.websocket.org") as WebSocket;

Related

Cannot use import statement outside a module with #pusher/push-notifications-web nodejs - beams

I am trying to follow this tutorial using nodejs and express: https://pusher.com/docs/beams/reference/web/#npm-yarn
First I did: npm install #pusher/push-notifications-web before adding the code.
But when I add this code in the index.js file:
import * as PusherPushNotifications from "#pusher/push-notifications-web";
const beamsClient = new PusherPushNotifications.Client({
instanceId: "<YOUR_INSTANCE_ID_HERE>",
});
beamsClient.start().then(() => {
// Build something beatiful 🌈
});
I get this error:
SyntaxError: Cannot use import statement outside a module
It's also not very clear to me from the tutorial if the code has to be in the frontend or the backend. I tried both but got the same result.
How can I fix this problem?
The error is caused by the fact that you're trying to use ES module specific features in a regular CommonJS file (the default behavior in Node.js). However, what you're looking at is the Web SDK for Pusher which won't help you achieve your goals.
You need the server SDK for Node.js - https://pusher.com/docs/beams/reference/server-sdk-node/.
Verify that you have the latest version of Node.js installed and you have 2 ways of fixing that
Set "type" field with a value of "module" in package.json. This will ensure that all .js and .mjs files are interpreted as ES modules.
// package.json
{
"type": "module"
}
Use .mjs as file extension instead of .js.

Module not found: Error: Can't resolve 'fs' when trying to use a NodeJS library

I initiated a basic ReactJS app using npx create-react-app, then I ejected using npm run eject. Now when I am trying to import the Casual library by import casual from 'casual';, I get the following error:
Compiled with problems:
ERROR in ./node_modules/casual/src/casual.js 3:13-37
Module not found: Error: Can't resolve 'fs'
in '/home/me/project/node_modules/casual/src'
And the code around line number 3 in casual.js looks like this:
var helpers = require('./helpers');
var exists = require('fs').existsSync;
var safe_require = function(filename) {
if (exists(filename + '.js')) {
return require(filename);
}
return {};
};
...
I found answers to similar questions. Those were mainly Node or Angular related. I also tried answers suggesting some changes in webpack config, but no luck.
The reason is Casual doesn't work on the front end. It runs on Node.js only.
You need to install maybe a new package to make things work.
Fs is unavailable on the browser so it won't work. Instead, you should use casual-browserify, it will work on browsers.

"ReferenceError: WebSocket is not defined" when using RxJs WebSocketSubject and Angular Universal

I'm setting up an angular 6.x univeral project in order to leverage its SSR (Server-Side Rendering) capabilities. In my app, I'm using websocket communication using RxJs.
More specifically, I'm, using WebSocketSubject and webSocket in my angular universal 6.x project, which works fine on the browser platform. However, when running the node web server (that contains the SSR stuff (Server-Side Rendering)), an error is thrown:
ReferenceError: WebSocket is not defined
Example code:
// not actually code from the reproduction repo
import { WebSocketSubject, webSocket } from 'rxjs/webSocket';
const socket: WebSocketSubject<any> = webSocket('wss://echo.websocket.org');
socket.subscribe(msg => doSomething(msg));
Please note, that the error doesn't occur on the browser version of the app (i.e. ng serve won't throw the error), but only after compiling the SSR stuff and running the express web server. To reproduce the error, the builds have to be run first:
# install dependencies
npm install
# build angular bundles for browser and server platforms
npm run build:client-and-server-bundles
# build the webserver
npm run webpack:server
# start the webserver
npm run serve:ssr
# the app is now being served at http://localhost:8081/
# open it in the browser and the error will occur: 'ReferenceError: WebSocket is not defined'
I've also set up a reproduction repo.
Environment I'm using:
Runtime: Angular 6
RxJS version: 6.2.0, 6.2.1, 6.2.2 (tested all)
Edit 2018-08-02
I was able to address the problem more accurately. It seems, that this is also a webpack problem. Angular Universal creates a js bundle for running the angular app on the node server, but there is natively no websocket implementation on Node. Therefore, it has to be added manually as a dependency (npm package). I tried adding it to the js server bundle (const WebSocket = require('ws'); manually, which resolves the problem (i.e. ReferenceError disappears). However, when I add it to the TypeScript code that gets transcompiled into the js bundle later on, it won't work.
Further details
The webpack loader ts-loader is used for compiling TypeScript => JavaScript
The websocket depedency was added to the package.json: "ws": "^6.0.0"
Attempting to reference the ws dependency by adding const WebSocket = require('ws'); to the uncompiled TypeScript code won't resolve the issue. It would get compiled into var WebSocket = __webpack_require__(333); in the js output file, the dependency won't be able to be resolved.
Manually changing var WebSocket = __webpack_require__(333); => const WebSocket = require('ws'); in the compiled js file would resolve the issue, but of course it's a hack.
So, the questions are:
Can I "force" webpack to compile the dependency const WebSocket = require('ws'); => const WebSocket = require('ws'); (no changes)?
Or, would it might be a better solution, to register this dependency in the angular universal npm package and create a pull request?
The RxJS webSocket function can receive a WebSocket Constructor as an argument. This can be used to run webSocket in a non-browser/universal environment like this.
const WebSocketConstructor = WebSocket || require('ws')
const socket: WebSocketSubject<any> = webSocket({
url: 'wss://echo.websocket.org',
WebSocketCtor: WebSocketConstructor,
});
// OR...
import { WebSocket, ...otherStuff... } from 'ws';
import { webSocket, ...otherStuff... } from 'rxjs/webSocket';
const socket$ = webSocket({
url: 'wss://someplace.com',
WebSocketCtor: WebSocket,
});
All it takes is this:
// set WebSocket on global object
(global as any).WebSocket = require('ws');
And of course, we need the ws dependency as well in the package.json:
npm i ws -s
In nodeJS apps with ES6 or similar, you must use this:
global.WebSocket = require('ws')
For example:
import { WebSocketSubject, webSocket } from 'rxjs/webSocket';
global.WebSocket = require('ws'); // <-- FIX ALL ERRORS
const subject = webSocket('ws://...');
No more errors.
My first answer!! Cheers
I created a npm package using websockets.
To provide compatibility for server side js and browser js i use this code.
(Note: it is typescript)
if (typeof global !== 'undefined') {
(global as any).WebSocket = require('ws');
}
Like you mentioned, the browser already has a WebSocket in its global object window but node does not.
Since the browser does not have global, this simple check works well.
Compiled code:
if (typeof global !== 'undefined') {
global.WebSocket = require('ws');
}

how to use node module with es6 import syntax in typescript

I have a typescript project which has uses one of our node modules which normally runs in our front-end. We are now looking to use this module in node on our server.
The module uses es6 import syntax import { props } from 'module/file'
When I include a ref in typescript using either of the following methods
import { props } from 'module/file';
var props = require('module/file');
I get the following error from typescript
unexpected token 'import'
(function (exports, require, module, __filename, __dirname) { import
It's a big job to re-write the module, and I've tried using babel with babel-plugin-dynamic-import-node, as well as SystemJS.
The problem with these systems is that they are all asynchronous, so I can't import the module in the standard fashion, so I would need to do a whole bunch of re-write when we get to the point that I can use import natively in node.js.
I can't be the first person to have this issue, but I can't seem to find a working solution.
--------------- update with set-up -------------
In response to #DanielKhoroshko's response. The original module I am trying to import is normally packaged by webpack in order to use on the front-end. I am now trying to use this same module both server-side and in the front-end (via webpack on the front-end) without re-writing the imports to use require and without running webpack to bundle the js to use on the server.
To be clear, the original module is written in JS, our service which is trying to use this module is written in typescript and transpiled. When the typescript tries to require the old module which uses import, it is at this point that we are running into the issue.
------------------ some progress ---------------------------
I've made some progress by creating a file in my imported module which uses babel in node.js to transpile the es6 code into commonJS modules.
I've done this via
var babel = require("babel-core")
var store = babel.transformFileSync(__dirname + '/store.js', {
plugins: ["transform-es2015-modules-commonjs"]
});
module.exports = {
store: store.code
}
I can now get the store in my new node.js project. However, the submodules within the store.js file are not included in the export.
So where in my module, it says
import activities from './reducers/activities';
I now get an error
Cannot find module './reducers/activities'
How can I get babel to do a deep traversal to include the sub-directories?
unexpected token 'import' means you are running es-modules code in environment that doesn't support import/export commands. If you are writing you code in TypeScript it's important to transpile it first before building for the browser or use ts-node to run it server-side.
If you are using webpack there are loaders ts-loader and awesome-typescript-loader
What is your setup?
To describe the module you would need to create an activities.d.ts file in the same folder where the js-version (I understood it is called activities.js and containers a reducer) resides with the following (approx.):
import { Reducer } from 'redux';
export const activities: Reducer<any>;
#Daniel Khoroshko was right in many ways, I ended up finding #std/esm which lets you import es6 modules and worked find for fetching the included imports as well.
var babel = require('babel-register')({
presets: ["env"]
});
require = require('#std/esm')(module);
var store = require('ayvri-viewer/src/store');
exports.default = {
store: store
}
I had to run babel to get a consistent build from es6 to node compatible es5

How to test Angular2 pipe in nodejs with mocha without karma

I'd like to be able to test an Angular2 pipe purely in nodejs environment without including karma etc.
It is possible to use typescript files as test suites for mocha
https://templecoding.com/blog/2016/05/05/unit-testing-with-typescript-and-mocha/
But when I have a import {Pipe} from '#angular/core' it gives me
/Users/foo/node_modules/#angular/core/src/util/decorators.js:173
throw 'reflect-metadata shim is required when using class decorators';
^
reflect-metadata shim is required when using class decorators
Even if I write require('reflect-metadata') in my test file it still breaks with the same error.
Angular internally has this check:
(function checkReflect() {
if (!(Reflect && Reflect.getMetadata)) {
throw 'reflect-metadata shim is required when using class decorators';
}
})();
And after requireing reflect-matadata I indeed have Reflect on the global object, however it still doesn't work...
Anyway is there a way to test an Angular pipe purley in nodejs with mocha?
I'm using webpack to bundle the app so the file I'm requring in my test file looks like this:
import {Pipe} from '#angular/core';
#Pipe({
name: 'filterBy'
})
export class FilterByPipe {
transform(items = [], prop, val) {
return items.filter(someFilteringAlgorithm(prop, val));
}
}
I didn't test pipes yet, but here a post that explain how to test Angular 2 application in Node with Mocha. But It use Webpack instead of ts-node : Here
Hope It can help.

Resources