import npm module using 'require' in Node.js - node.js

I have a naive question regarding importing npm modules on Node.js server.
I have installed 'ml-random-forest' module via npm and have been trying to import the package.
I can import it via import { RandomForestClassifier as RFClassifier } from 'ml-random-forest'; but I cannot import like var RFClassifier = require('ml-random-forest');
How can I import that package using 'require' ?

It seems that when you call :
import {existingVariableFromTheLib as
yourOwnNameForIt} from 'that_library'
You're actually importing an element of this library.
But when you're calling :
const anAlias = require('this_lib')
You're putting inside of the constant "anAlias" the totality of the library.
What you could try is then to call :
anAlias.existingVariableFromTheLib
Or, another way of dealing with this is to import using this way :
const {existingVariableFromTheLib}
=require('lib')
//or :
const anAlias =
require('lib').existingVar
//maybe
const anAlias =
require('lib').existingFunction()

Related

Unable to import Client from node-pg

I am trying to use Postgresql in a Node project. I am using modular imports, so I am having issues importing 'pg':
import * as pg from 'pg'
const { Client } = pg
let client = new Client()
leading to this error
let client = new Client()
^
TypeError: Client is not a constructor
I've looked at a couple other questions similar to this, but still have issues:
import { native as pg } from 'pg';
let client = new pg.Client()
leading to this error:
import { native as pg } from 'pg';
^^^^^^
SyntaxError: Named export 'native' not found. The requested module 'pg' is a CommonJS module, which may not support all module.exports as named exports.
Does anyone know what I can try to make this import correctly?
From the error suggestion, pg is a CommonModule which may not support all module.exports as named exports.
change the import from
import * as pg from 'pg'
to
import pg from 'pg'
will solve the import problem.

AWS X-ray import with Typescript

I currently use postgresql-node in my lambda with
import { Client } from 'pg'
I want to instrument the Postgresql lib with AWS X-ray. The Nodejs example has this line:
var AWSXRay = require('aws-xray-sdk');
var pg = AWSXRay.capturePostgres(require('pg'));
How would I convert the second line in that to proper Typescript. All the variations I come up with produce some errors or warnings. For example I would guess this would work:
const pg = AWSXRay.capturePostgres(require('pg'))
but not only you get ESlint warning for require being used without import but after that pg.Client says pg namespace not found.
Well, it's slightly ugly but this seems to work:
import * as pg from 'pg'
const patchedPg = AWSXRay.capturePostgres(pg)

How to fix "× TypeError: Object(...) is not a function"?

I'm making a netflix clone app in nodejs and got stuck on generateMedia function.
On TabContentOne.js file, On import { generateMedia } from 'react-media-query' it is dotted and when I run npm install #types/react-media-query it gives me errors. I did npm i react-media-query.
import React from 'react';
import styled from 'styled-components';
import { Button } from './Button';
import { generateMedia } from 'react-media-query'
// Media Query
const customMedia = generateMedia({
smDesktop: '1440px',
tablet: '960px'
})
This is the link from my bitbucket https://bitbucket.org/danclaudiu95/nodejs-reactjs.git
I'm expecting to use generateMedia function the put style on some elements in my application but the npm server doesn't start anymore.
I recommend using another package that does the same thing, "react-media-query" is outdated and removed from github.

Unable to import lodash

I'm new to TypeScript and I'm facing a problem while trying to load lodash.
Here is my code :
///<reference path="../../typings/lodash/lodash.d.ts"/>
///<reference path="../interfaces/IScheduler.ts"/>
import _ = require('lodash');
module MyModule {
export class LeastUsedScheduler implements IScheduler {
/// CODE HERE
}
}
I tried replacing the import line by :
import * as _ from lodash;
In the two cases I get :
"error| Cannot find name 'IScheduler'."
When I remove the import directive it compiles perfectly but _ is undefined at runtime.
I also tried to put the import inside the module without success.
I'm sorry It must be a very dumb question but I can't figure it out.
Thank you
EDIT :
I understood the problem. Referencing the typing for lodash created the variable _ in the scope. That's why it compiles fine without the import line. The problem is referencing the typing does not really import lodash. That's why it fails at runtime.
When I import lodash the compilation fails because lodash is already in the scope.
Thank you for your support.
I'm not 100% about the issue but can you try the following and let me know how it goes?
///<reference path="../../typings/lodash/lodash.d.ts"/>
///<reference path="../interfaces/IScheduler.ts"/>
import _ = require("lodash");
export class LeastUsedScheduler implements IScheduler {
doSomething(){
_.each([],function name(parameter) {
// ...
});
}
}
When compiled it looks like:
var _ = require("lodash");
var LeastUsedScheduler = (function () {
function LeastUsedScheduler() {
}
LeastUsedScheduler.prototype.doSomething = function () {
_.each([], function name(parameter) {
throw new Error("Not implemented yet");
});
};
return LeastUsedScheduler;
})();
exports.LeastUsedScheduler = LeastUsedScheduler;
If you import the module import _ = require("lodash"); but you don't use it, TypeScript will remove the import (I added the doSoemthing method for that reason).
Update: Why it didn't work?
The problem was that the module keyword is used to declare an internal module. At the same time the code was loading an external module. You should avoid mixing internal and external modules. You can learn more about the difference between internal and external modules at http://www.codebelt.com/typescript/typescript-internal-and-external-modules/.
Also, if you use internal modules avoid using the module keyword as it is deprecated and you should use the namespace keyword instead.

Importing Node modules in TypeScript

How can I import Node modules which reside in the node_modules folder in TypeScript?
I get an error message (The name ''async'' does not exist in the current scope) when I try to compile the following piece of TypeScript code:
// Converted from: var async = require('async');
import async = module('async');
You need to create a definition file and include this:
module "async" {}
then add a reference to this definition file in your TypeScript code
///<reference path='definition-file.d.ts' />
import async = module('async');
The standard "import blah = require('x')" semantics in typescript flat out don't work with node modules.
The easiest way to work around this is to define and interface and use require explicitly, rather than import:
// You can put this in an external blah.d file if you like;
// remember, interfaces do not emit any code when compiled.
interface qOrm {
blah:any;
}
declare var require:any;
var qOrm:qOrm = require("../node_modules/q-orm/lib/q-orm");
var x = qOrm.blah;
npm install --save-dev #types/async
npm install --save async
And the syntax:
import * as async from "async"

Resources