Adding Cheerio.js to an Angular 6 project?

2019-07-30 05:06发布

问题:

I created a brand-new Angular 6 project and installed Cheerio.js:

npm install cheerio

Once Cheerio.js was installed, I figured all I had to do to add it to my project was to import it and add it to the NgModule imports:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import * as cheerio from 'cheerio';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    cheerio
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

However, after doing this, I'm getting a TypeScript error, something along the line of "Could not find a declaration file for module 'cheerio'."

Am I going about this the wrong way? I just need to be able to parse some HTML within the Angular app and read that Cheerio.js was the way to go.

回答1:

Don't add cheerio inside imports of your NgModule, basically imports array takes an Angular application module name, where in you wanted to use third party library inside angular application.

Basically you should add cheerio file reference inside your angular.json file scripts option. This will ensure that cheerio plugin is loaded inside your bundle file. It is ready to use now.

"scripts": [
  ...,
  "node_modules/cheerio/lib/cheerio.js"
]

Then to use cheerio plugin function inside you Angular code. But you should also install cheerio typings, such that typescript would not complain against it.

npm i -D @types/cheerio


回答2:

You also need to install cheerio types npm install --save @types/cheerio