markdown (原始)Angular 2包括外部JavaScript库

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown (原始)Angular 2包括外部JavaScript库相关的知识,希望对你有一定的参考价值。


// src/typings.d.ts
declare module 'hc-sticky';

// quotes-results.component.ts
import * as hcSticky from 'hc-sticky';

...

ngAfterViewInit() {
  // DOM is available

  const Sticky = new hcSticky('aside', {
    stickTo: 'main',
    queries: {
      980: {
        disable: true
      }
    }
  });
}

Example: adding underscore.js

install library:  
`npm install --save underscore` 

### Import the library into Angular (TypeScript)

TypeScript needs to understand underscore.js: when we are going to use an external library such as underscore we need to declare type definitions for TypeScript.
TypeScript provides declaration files (*.d.ts) which define types and standardize a JavaScript file/libraries for TypeScript.
Some libraries includes typing file, but in case a library does not have .d.ts file, you need to install it.
Use TypeSearch: [https://microsoft.github.io/TypeSearch/](https://microsoft.github.io/TypeSearch/) to find declaration file for the libraries you need. Here you'll find underscore.js declarations file:  
`npm install --save @types/underscore` 

### Import type declaration into Angular app

app.component.ts  
`import * as _ from 'underscore';`
or simply:  
`import 'underscore';`

TypeScript in that component now understand `_` and it easily works as expected.

### How to use a library which does not have type definition?

Create/edit `src/typings.d.ts` and add your package to it:  
`declare module 'your-library'`  
In your TypeScript now you need to import it by the given name:
```javascript
import * as yourPreferedName from 'your-library';
yourPreferedName.method();
```

////

`declare module '*';`   
The wildcard allows third party JavaScript libraries to be used even if they don’t include type definitions. This means the following would be acceptable in the project:
```javascript
import * as base64 from "base-64";
import * as utf8 from "utf8";
```

以上是关于markdown (原始)Angular 2包括外部JavaScript库的主要内容,如果未能解决你的问题,请参考以下文章

markdown Git重置回提交的原始副本,包括删除未跟踪的文件

markdown 在Cloud9上运行Angular 2和Angular 4

markdown Angular 2 Snippets - 基础知识

markdown Angular 2快速入门

markdown Angular 2+学习文档

markdown 缺少Angular 2和现代设计模式的介绍