Adding Cheerio.js to an Angular 6 project?

非 Y 不嫁゛ 提交于 2020-01-04 18:17:25

问题


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



来源:https://stackoverflow.com/questions/52580570/adding-cheerio-js-to-an-angular-6-project

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!