What is the best way to implement a third-party library that utilizes an outdated import method in Angular 4.x?

Can anyone guide me on how to include the mathjs library in Angular 4.0 and use it within a component?

Here are the steps I've taken so far:

yarn add mathjs

I believe there should be a method for injecting JS libraries during one of the build lifecycles so that the angular4 component can access it. JHipster uses Webpack and Yarn.

Next, I attempted to add to the Component (see docs):

import { mathjs } from "./mathjs";  

and

var math = require('mathjs');

Unfortunately, neither of these methods worked. What am I missing here?

UPDATE:

It seems like mathjs may be using an older approach by suggesting var math = require('mathjs'). Could this be similar to the JQuery question in some aspects...

UPDATE2

Answer №1

Thank you for asking this question, it's definitely something many developers encounter. Before we delve into the specifics, I want to address that this issue is related to TypeScript, JavaScript, and Webpack rather than Angular itself. I will be preparing a detailed write-up on this topic very soon on my blog.

The Problem:

Let's say you perform the following command:

npm install mathjs
  1. Next, you attempt to utilize math.js from a component.
  2. To do this, locate the math.js dist js file (node_modules/mathjs/dist/math.js) and import it like so:

    import {mathjs} from "../../node_modules/mathjs/dist/math";

  3. You might encounter an error message requesting to set "--allowJS." To resolve this, update your config in tsconfig.json as follows:

    Set --allowJS in config (tsconfig.json) 
    {    "compilerOptions": {
        "allowJs": true, ...

  4. Subsequently, you may encounter:

ERROR in ../node_modules/mathjs/dist/math.js (12209,13): Unreachable code detected.

  1. Upon inspecting the source of math.js, you'll notice it lacks a root wrapper function (the one function to rule them all). We'll dive deeper into this shortly.

Solution: install a typings file for the target library (@types/mathjs)

  1. Initially, check if you can obtain @typings files for your module at .
  2. Acquire the mathjs typings file from npm (https://www.npmjs.com/package/@types/mathjs) and proceed with npm install to include the typings .d.ts files within the target lib's node_modules directory

    npm install --save @types/mathjs

  3. Ensure to reference the type correctly

    import * as mjs from "mathjs"

Utilize it as shown:

console.log("e was: " + mjs.e);

I have provided a comprehensive solution for the math.js library on my GitHub repository: https://github.com/res63661/importOldJSDemoWithTypings/

Additional Tips: For illustrations, explore your Angular project. The CLI generates a node_modules folder each time you execute npm install after creating a new project using ng new. Dive into this directory and observe the d.ts files associated with numerous .js files.

When dealing with typings or defining your own (.d.ts files), remember to restart your server between builds since the typings don't update automatically.

Further Resources:

  1. http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html
  2. https://angular.io/guide/typescript-configuration#typescript-typings

Lastly:

If you find yourself stuck and the solutions mentioned above aren't working, consider crafting a custom wrapper for a different module by encapsulating it in a master export type like this:

export var moduleNamer = (function(){
  //module implementation
}());

Then place the .js file locally within your component and reference it accordingly:

//include the following line in your component:
import {moduleNamer} from "./source";  //from source.js

--rich

Answer №2

This method worked perfectly for Angular9.

Start by installing the npm package mathjs.

npm install mathjs

Next, import it into your component or directive.

import { round } from 'mathjs'

You can test it out with this code snippet.

console.log(round(math.pi, 3) )

Answer №3

Make sure to integrate the following script in your index.html file:

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

Next, include this line in your component file:

declare const math; 

You can now utilize the math function in your component:

ngOnInit(): void {
    console.log(math.sqrt(-4););
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to eliminate dates from the text of listed items

Before finalizing their registration, users on our site are shown a review page. This panel displays all the items they have selected, creating a unique and variable list for each individual. However, each item in the list starts with a distracting date/ti ...

Error in Express.js App: Attempting to access properties of an undefined object (specifically 'transfer-encoding')

Currently, I am developing a blogging app API using express and MongoDB. In my project, I want to include an image for each blog post. However, as someone who is new to express, I encountered a specific issue that has been puzzling me. The error message ...

What is the syntax for linking to a different file in the frontmatter of a markdown file?

Currently, I am in the process of setting up Astro's Content Collections. One particular task I would like to achieve is referencing a specific author from my `authorCollection` within an article. In attempting to accomplish this, I considered utiliz ...

Storing a Promise in a Variable in React

As a newcomer to JavaScript/React, I am finding it challenging to grasp the concept of using Promise and async. To illustrate, consider the API call getSimById in a JS file that returns a Promise: export function getSimById(simId) { return fetch(simsUrl ...

Is there a way to dynamically update the polyline on the map when I drag a marker to change the path, removing the previous one in the process?

I'm still fairly new to working with Javascript and the Google Maps API. I've come across various solutions to a similar issue that I'm facing, but none of them seem to work for my specific code. I'm starting to question whether the pol ...

Creating a form with multiple components in Angular 6: A step-by-step guide

I'm currently working on building a Reactive Form that spans across multiple components. Here's an example of what I have: <form [formGroup]="myForm" (ngSubmit)="onSubmitted()"> <app-names></app-names> <app-address> ...

Using setAttribute will convert the attribute name to lowercase

When creating elements, I use the following code: var l = document.createElement("label");. I then assign attributes with l.setAttribute("formControlName","e");. However, a problem arises where the setAttribute method converts formControlName to lowercase ...

Exploring numerical elements in interactive content

Struggling with the Wikipedia API and encountering issues with the results that are returned. {"query":{ "pages":{ "48636":{ "pageid":48636, Concerned about how to access a specific ID (such as 48636) without knowing it in advance ...

How can the service receive the return value from a subscribed subject?

I have a question about whether it is possible to retrieve the value from a call to Subject.next(). Can you suggest any other approaches on how to receive a response in the given scenario? My current situation involves a notify service that is used throug ...

Having trouble writing Jest test cases for a function that returns an Observable Axios response in Nest JS

I'm relatively new to the NestJS + Typescript + RxJs tech stack and I'm attempting to write a unit test case using Jest for one of my functions. However, I'm uncertain if I'm doing it correctly. component.service.ts public fetchCompon ...

Detecting modifications to an array with MobX

Today marks my first foray into learning MobX and I am eager to discover how to track all array changes (insertions, deletions, etc) with MobX. A practical example would definitely help clarify this: const TodoList = ({todos}) => ( <ul> ...

Generate a two-dimensional array of pixel images using HTML5 canvas

Hey everyone, I'm trying to copy an image pixel to a matrix in JavaScript so I can use it later. Can someone take a look and let me know if I'm using the matrix correctly? I'm new to coding so any help is appreciated. Thanks! <canvas id= ...

TypeError: describe is not a function in the Mocha testing framework

Encountering an issue with mocha-typescript throwing an error indicating that describe is not defined. TypeError: mocha_typescript_1.describe is not a function at DatabaseTest.WrongPath (test/database_test.ts:21:9) at Context.<anonymous> ...

"Error 400 encountered while trying to access the Google Blogger API

I'm encountering an issue while attempting to access Blogger through the JavaScript V3 API. Everything functions correctly when accessing my (public) test blog. However, when I use the same code to access my (private) test blog, I encounter an error. ...

I'd like some clarification on the code that dynamically adds routes using Typescript and Node Express. Can someone please

Running my API server with node/typescript and express / express validator, I came across this code that I found really useful for separating route logic: function createCustomRouter(route: Array<CustomRouteEntry>): Router { const customRouter = R ...

Enabling Cross-Site Request Forgery (CSRF) through Angular's HttpClientModule is causing an error message to appear: TS2552 -

As a novice in front-end development, I am looking to incorporate CSRF tokens into certain requests within a frontend application. The app is built using Angular version 12.2.17, and I am following the guidelines outlined in the Angular documentation: http ...

Experience choppy scrolling in Internet Explorer

Check out my click and drag scrolling Image Viewer here. While it functions perfectly in Firefox and Chrome, Internet Explorer is giving me some trouble. The movement seems jerky, especially when scrolling diagonally. It's like the scroll is sluggish ...

Preserving the status of your AngularJS application

Can the state of an AngularJS app be preserved using Angular local storage? I am developing an information-based app with a substantial amount of content, and I want to save the user's current "location" so that when they reopen the app later, it open ...

Can React JSX and non-JSX components be combined in a single project?

I'm currently faced with a question: If I have a parent component in JSX but need to include an HTML tag like <i class="fa fa-window-maximize" aria-hidden="true"></i>, which is not supported by React JSX (correct me if I'm wrong), can ...

I am trying to move to a different page, but for some reason the router.navigate function is not functioning within the subscribe

//I am attempting to redirect to another page once the subscribe method is executed, however I am encountering issues with the router.navigate function within the subscribe method. //In an effort to address this issue, I have attempted to store the data r ...