首页 文章

导入第三方库

提问于
浏览
0

我需要在angular2项目中导入第三方库 .

这是我做的:

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

现在是我被困的那一刻 . 如何导入和使用此库?有像 ShapeStage 这样的对象

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

这根本不起作用 .

我的文件夹结构:

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",
]

1 回答

  • 1

    您必须向 tsconfig.json 添加路径(和 baseUrl ):

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

    easeljs 的路径相对于您的 tsconfig.json .

    之后,您可以使用以下方法导入此库:

    import * as createjs from 'easeljs';
    

    并在项目中使用它,如:

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

    因为 @types 定义文件都有自己的定义模块的方式,所以您可能会遇到与导入方式不兼容的文件 . 据我所知,他们希望将其作为标准 .

    您应该创建一个本地typings文件夹并创建一个 easeljs.d.ts 文件,其中包含:

    /// <reference path="../../node_modules/@types/easeljs/index.d.ts" />
    
    declare module "createjs" {
        export = createjs;
    }
    

    确保引用路径指向正确的目录,我不知道你的项目结构:)

    之后,将本地typings文件夹添加到 tsconfig.jsontypeRoots 属性中:

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

    UPDATE

    显然,这不适用于此库 . 不幸 . 好的事情angular-cli有一个预加载脚本的选项:

    编辑你的 angular-cli.json 以添加库:

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

    不要在文件顶部使用导入,因此请删除 import * as createjs from 'easeljs' . 而且不需要本地打字文件夹 . 同时删除 tsconfig.json 中的 paths

相关问题