'import npm module using 'require' in 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' ?



Solution 1:[1]

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()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AVALFINN