Incorporate an external library

I am currently facing a challenge in my angular2 project where I need to import a 3rd party library.

Here are the steps I have taken so far:

ng new myproject
npm install --save createjs-easeljs
npm install @types/easeljs

However, I am stuck at this point. How do I go about importing and utilizing this library? Some of the objects in the library include Shape and Stage.

import { Shape, Stage } from '../../../node_modules/createjs-easeljs/lib/easeljs-0.8.2.min.js';

Unfortunately, this method does not seem to work.

This is how my folder structure looks like:

dynam194:src timo$ tree -L 2
.
├── app
│   ├── app.component.css
│   ├── app.component.html
│   ├── app.component.spec.ts
│   ├── app.component.ts
│   ├── app.module.ts
│   └── canvas
├── assets
├── environments
│   ├── environment.prod.ts
│   └── environment.ts
├── favicon.ico
├── index.html
├── main.ts
├── polyfills.ts
├── styles.css
├── test.ts
├── tsconfig.json
└── typings
    └── easeljs.d.ts

tsconfig.json

"paths": {
  "easeljs": ["../node_modules/createjs-easeljs/lib/easeljs-0.8.2.min.js"]
},
"sourceMap": true,
"target": "es5",
"typeRoots": [
  "../node_modules/@types",
  "typings",
]

Answer №1

To successfully integrate the easeljs library into your project, you need to make some modifications in your tsconfig.json:

{
  "compilerOptions": {
    ...
    "baseUrl: ".",
    "paths": {
      "easeljs": ["../node_modules/createjs-easeljs/lib/easeljs-0.8.2.min.js"]
    },
  }
}

The path specified for easeljs should be relative to the location of your tsconfig.json.

Once you have added the path, you can import the library using:

import * as createjs from 'easeljs';

You can then utilize the library within your project like so:

let stage: createjs.Stage = new createjs.Stage('myCanvas');
let shape: createjs.Shape = new createjs.Shape();

Sometimes, the definition files in the @types folder may not align perfectly with how modules are imported. It is recommended to create a local typings folder and include an easeljs.d.ts file with proper references.

/// <reference path="../../node_modules/@types/easeljs/index.d.ts" />

declare module "createjs" {
    export = createjs;
}

Ensure the reference path is accurately pointing to the correct directory based on your project structure.

In addition, add the local typings folder to the typeRoots property in your tsconfig.json:

{
  "compilerOptions": {
    ...
    "typeRoots": [
      "../node_modules/@types",
      "typings/local"
    ]
   }
}

UPDATE

If the above method does not work for the easeljs library, consider using Angular CLI's script preload option:

Edit your angular-cli.json file to incorporate the library:

{
  "apps": [
    {
      ...
      "scripts": [
        "../node_modules/createjs-easeljs/lib/easeljs-0.8.2.min.js"
      ],
    }
  ]
}

Remove the

import * as createjs from 'easeljs'
, avoid using paths in tsconfig.json, and exclude the local typings folder to ensure smooth integration.

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

How can I make my webpage fill the entire width of an iPhone screen when in landscape mode using Angular or React?

While testing my website on my iPhone, I noticed a significant gap appearing on either side of the app in landscape view in Safari. Is there a solution to fix this issue? The problem occurs in both Angular and React applications, examples of which are disp ...

MongoDB was successfully updated, however the changes are not being displayed on the redirected

I have implemented the delete action in Node/Express as a web framework, where it is structured within a higher-level route: .delete((req, res) => { db.collection('collection-name').findOneAndDelete({ topic_title: req.body.topic_title}, ...

Transform a literal string type definition into a string value (similar to the typeof operator), or is it the other way around in TypeScript?

Is there a way to retrieve the string value of a string literal type without having to define it twice, similar to the typeof operator in C#? myStringLiteral: 'STRING TYPE'; myString: string = typeof(myStringLiteral); // I want myString to be e ...

Avoid using `@typescript-eslint/no-floating-promises` when using a `const` function

Can anyone help me understand why the @typescript-eslint/no-floating-promises rule works with some async functions but not all? To my understanding, these two functions should be equivalent: const getUser = async (userId: string): Promise<User> => ...

The majority of the sliding banner is crafted using 90% HTML and CSS3, with just a touch

I devised a clever script to smoothly slide an image back and forth across the screen using CSS3. Unfortunately, I encountered a problem with CSS animations - they do not support changing the background-image directly. Attempting to overcome this limitatio ...

Does D3 iterate through the entire array every time we define a new callback?

It seems that every time a callback is set, d3 loops through the entire array. Initially, I thought that functions like attr() or each() were added to a pipeline and executed all at once later on. I was trying to dynamically process my data within d3&apo ...

Issue with login form in IONIC: Form only functions after page is refreshed

Encountering an issue with my Ionic login form where the submit button gets disabled due to invalid form even when it's not, or sometimes displays a console error stating form is invalid along with null inputs. This problem seems to have surfaced afte ...

Facing challenges in both client-side and server-side components

import axios from 'axios'; import Image from 'next/image'; export const fetchMetadata = async({params}) => { try { const result = await axios(api url); return { title: title, description: Description, } / } catch (error) { con ...

Cricket score update features on the client side

Looking for assistance with client-side code development! I am currently working on an Android application using Ionic that involves live cricket scores. I have purchased a cricket API and understand how to connect to it using Node.js on the server side. ...

Pressing the button in JqGrid will assign an identification number

I am facing an issue with selecting rows in my JqGrid, so I found a solution on which suggests that I need an ID for every row. Whenever I add data to my Grid by pressing a button, I tried assigning each row an ID using a simple click counter function. H ...

Entering _this

I am encountering an issue with my typescript file where it is failing TSLint. I need some help resolving this problem. The structure of the object in question is as follows: export default class Container extends Vue { // methods doSomething() { ...

Exploring the retrieval of stored information from $localStorage within an AngularJS framework

I have been working on a MEAN app, and after a user successfully logs in, I want to save the returned user data in the localStorage of the browser for future use. I am using the ngStorage module for this purpose. Below is the code snippet from my LoginCont ...

Unable to reach the sub-component of the JSON object that was returned

For some reason, I can't seem to access a sub object of a returned $Resource object that fetched a group of JSON objects. It's baffling me. Resource > $resolved: true > $then: function (b, g) {var j=e(),h= > data: Object > 519bc5f6 ...

Executing unique calculations on Kendo UI Grid Columns

For experienced users, this may seem simple, but as a newcomer, I'm struggling with a basic arithmetic task. I want to multiply one of the column values (DealValue) by 0.05 in my Kendo grid setup. Despite looking through the Kendo docs, I couldn' ...

Using yargs to pass parameters/arguments to a Node script through an npm script

Is it feasible to retrieve a key from yargs when utilizing as an npm script argument? A user inputs in the OSX terminal: npm run scaffold --name=blah which triggers in package.json: "scaffold" : "node ./scaffold/index.js -- " This leads to const yar ...

What is the best way to trigger a function in the parent component when a child component is clicked

I'm facing a scenario where I have two components - a parent and a child. Within the child component, there is a button. My goal is to trigger a method in the parent component when the user clicks on that button within the child component. Any ideas o ...

Initial binding of Angular2 ControlGroup valueChanges event

My form contains <input type="text"> elements and I've noticed that ControlGroup.valueChanges is triggered during initial data binding when using [ngFormModel] and ngControl. As a result, it gives the impression to the user that the form has al ...

When utilizing mat-select within a Custom Element (web component), the options are displayed outside of the shadow DOM

When I incorporate a mat-select element into my custom element, the options appear outside of the shadow dom in the HTML. This means that the options are not displayed directly below the select control. After some investigation, I discovered that setting ...

How to Use Framer Motion in Next.js for window.innerWidth Less Than 768

I am trying to use window.innerWidth to control the timing of an animation (Framer Motion) in my Next.js project, but I keep encountering the error message: ReferenceError: window is not defined Here's a simplified version of my ValuesSection.jsx co ...

Executing JavaScript's addEventListener() function without specifying the event that triggers it

I am currently working on creating a grid of boxes that can be clicked, sending notifications with their respective IDs to the server using SocketIO. <body> <div class="wrapper"> <div id="1" class="box"></div> <div id="2 ...