问题描述
我创建了一个全新的Angular 6项目并安装了Cheerio.js:
npm install cheerio
一旦安装了Cheerio.js,我发现将其添加到项目中所要做的就是导入并将其添加到NgModule导入中:
import'@ angular / platform-browser'的{BrowserModule};从 @ angular / core导入
{NgModule};
从 ./app.component导入{AppComponent};
进口*作为来自 cheerio的cheerio;
@NgModule({
声明:[
AppComponent
],
导入:[
BrowserModule,
cheerio
],
提供者:[],
引导程序:[AppComponent]
})
出口类AppModule {}
但是,执行此操作后,出现TypeScript错误,类似于找不到模块'cheerio'的声明文件。 / p>
我会用这种错误的方式吗?我只需要能够在Angular应用程序中解析一些HTML并阅读Cheerio.js是必经之路。
不要在 NgModule
的进口
内添加 cheerio
,基本上 imports
数组采用Angular应用程序模块名称,在其中您想在angular应用程序内部使用第三方库。
基本上,您应该在 angular.json $ c内添加
cheerio
文件引用$ c>文件脚本
选项。这将确保 cheerio
插件已加载到捆绑文件中。现在可以使用了。
脚本:[
...,
node_modules /cheerio/lib/cheerio.js
]
然后使用<$ c $ Angular代码中的c> cheerio 插件函数。但是,您还应该安装 cheerio
类型,这样打字稿就不会对此有所抱怨。
npm i -D @ types / cheerio
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.
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
这篇关于将Cheerio.js添加到Angular 6项目中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!