Reputation: 931
I need to import an 3rd party library in an angular2 project.
Here is what I did:
ng new myproject
npm install --save createjs-easeljs
npm install @types/easeljs
Now is the moment I am stuck. How do I import and use this library? There are objects like Shape
or Stage
import { Shape, Stage } from '../../../node_modules/createjs-easeljs/lib/easeljs-0.8.2.min.js';
This does not work at all.
My folder structure:
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",
]
Upvotes: 0
Views: 484
Reputation: 71891
You have to add a path (and a baseUrl
) to your tsconfig.json
:
{
"compilerOptions": {
...
"baseUrl: ".",
"paths": {
"easeljs": ["../node_modules/createjs-easeljs/lib/easeljs-0.8.2.min.js"]
},
}
}
with the path to easeljs
being relative to your tsconfig.json
.
After that you can import this library using:
import * as createjs from 'easeljs';
And use it inside your project like:
let stage: createjs.Stage = new createjs.Stage('myCanvas');
let shape: createjs.Shape = new createjs.Shape();
Because the @types
definition files all have their own way of defining modules, its likely you come across one that's not compatible with that way of importing. As far as i know though, they want to make that the standard.
You should create a local typings folder and create a easeljs.d.ts
file containing:
/// <reference path="../../node_modules/@types/easeljs/index.d.ts" />
declare module "createjs" {
export = createjs;
}
Make sure the reference path is pointing to the right directory, I don't know your project structure :)
After that add the local typings folder to the typeRoots
property of your tsconfig.json
:
{
"compilerOptions": {
...
"typeRoots": [
"../node_modules/@types",
"typings/local"
]
}
}
UPDATE
Apparently, this does not work for this library. Unfortunately. Good thing angular-cli has an option to preload scripts:
edit your angular-cli.json
to add the library:
{
"apps": [
{
...
"scripts": [
"../node_modules/createjs-easeljs/lib/easeljs-0.8.2.min.js"
],
}
]
}
Do not use an import on top of your file, so remove import * as createjs from 'easeljs'
. And no need for the local typings folder. Also remove the paths
in your tsconfig.json
Upvotes: 1