Home > Back-end >  How to import mathjs module in Nodejs using ES6 Module syntax?
How to import mathjs module in Nodejs using ES6 Module syntax?

Time:02-05

The following works for me:

import { zeros } from "mathjs";
const w = zeros(5, 5);

but I'm trying to do something like: math.zeros(5, 5) as what I saw in the documentation https://mathjs.org/docs/reference/functions/zeros.html which will allow me to use math to access a lot of functions such us math.matrix(), math.square(array) ...etc. But when I try to do the following:

import { math } from "mathjs";
const w = math.zeros(5, 5);

I get the following error

SyntaxError: The requested module 'mathjs' does not provide an export named 'math'

my package.json looks like this:

{
  . . .
  "type": "module",
  . . .
  "dependencies": {
    "mathjs": "^11.5.1"
  }
}

CodePudding user response:

Ref: MDN: import

import { zero } from "mathjs"; // it's a name import

with importing zero like that you get only access to the 'zero' method

Try using

import math from 'mathjs' // it's a default import of math
const w = math.zeros(5, 5);

By importing math like that you get access to all its methods

CodePudding user response:

trying to use:

import math from 'mathjs' // it's a default import of math
const w = math.zeros(5, 5);

didn't work for me either. What worked is the following:

import * as math from "mathjs";

as suggested by jonrsharpe.

  • Related