skip to Main Content

I am trying to, pardon my wording as this is my first time trying to import a library to a personal project, import the library package mathjs.

(https://mathjs.org/docs/getting_started.html).

However I keep getting the error on my site "math is undefined" when I go to use it.

See photo of the error in console log here

// Example in my JavaScript of me attempting to access this library:
math.evaluate('12 / (2.3 + 0.7)');

This is my first time attempting anything like this. I must be missing a step.
What step am I missing?

Steps I took/have taken include:

  1. Ran NPM install

npm install mathjs –save

  1. Checked package.json and the new dependency is there:
  "dependencies": {
    "mathjs": "^12.4.0"
  }
  1. These two (tested separately) give the original error "math is undefined."

<script src="math.js" type="text/javascript"></script>

<script src="math.min.js" type="text/javascript"></script>

  1. But replacing those with require gave a separate, fatal error:

const math = require('mathjs');

Fatal error: Constant expression contains invalid operations in C:xampphtdocsGroceryListGeneratorPagesindex.php on line 3

2

Answers


  1. You have to have an import. I don’t know what they are for mathJS. But something like this should work. Have it at the top of your JS file

    import {a, b, c, etc}

    Edit: A recent comment said the answer

    import { atan2, chain, derivative, e, evaluate, log, pi, pow, round, sqrt }

    Login or Signup to reply.
  2. Mathjs functions is not defined in the global scope of your JavaScript code. This usually happens when you haven’t properly imported the library or haven’t made the imported object accessible in the specific part of your code where you’re trying to use it.
    Double-check that you’ve correctly installed mathjs using npm:

    npm install mathjs --save
    
    <script src="node_modules/mathjs/dist/math.min.js"></script>
    

    If you’re using a modern bundler like Webpack you can use the import statement:

    import * as math from 'mathjs';
    console.log(math.evaluate('12 / (2.3 + 0.7)'))
    

    Or if you are including HTML file you can work in this :

    <script src="node_modules/mathjs/dist/math.min.js"></script>
    console.log(math.evaluate('12 / (2.3 + 0.7)'))
    

    If the import statement or script tag is placed within a function or a block with limited scope, the math object might not be accessible outside that scope. Ensure it’s defined or imported where you need it.

    If you have other libraries that might define a variable named math, consider renaming or using a namespace to avoid conflicts.

    If you’re using a bundler, make sure it’s configured correctly to handle the mathjs library and its dependencies.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search