[英]How to correctly use PrismJS and its typings with typescript / angular 2
我正在用angular-cli構建一個小應用程序,我想使用PrismJS,但我無法讓它工作。
所以基本上我已經創建了一個vendor文件夾,我將 Prism 的腳本和樣式放在其中,並將它們加載到index.html 中。
我還需要安裝類型定義才能編譯我的應用程序:
npm i --save-dev @typings/prismjs
然后,我只需要在我的代碼中的任何地方調用Prism.whatever()
,但這不起作用。
甚至我的 IDE 也無法識別命名空間Prism
。
通過檢查定義( index.d.ts
)的內容,我看到自 1.6 版以來,它不包含
declare var Prism : PrismJS.Prism;
了。 只有一些export namespace Prism
。 所以我想知道我是否必須導入一些東西,因為使用了任何declare
。
從定義文件中導入一些東西對我來說似乎很奇怪。
因為我想跳過這個,我安裝了一個舊版本的定義(1.4.16),其中包含
declare var Prism : PrismJS.Prism;
現在,我的 IDE (webstorm) 很高興! 它可以識別Prism
。 但是當我嘗試編譯時,webpack 仍然輸出錯誤:
Cannot find name 'Prism'
所以我的問題很基本:我忘記了什么?
很抱歉這個明顯的問題。
謝謝!
在 angular-cli 中像這樣添加prism.js:
"scripts": [
"../node_modules/prismjs/prism.js"
],
之后,你可以讓打字稿滿意
declare var Prism;
並像那樣使用它
<code [innerHtml]="myCode"></code>
ngAfterViewInit() {
const code = 'var data = 1;';
this.myCode = Prism.highlight(code, Prism.languages.javascript);
}
我想你已經做到了——
npm install prismjs -S
npm install @types/prismjs -D
現在你需要將它導入到 n 組件中 -
import * as prism from 'prismjs';
然后使用棱鏡js支持的prism.whatEverMethod()
我想擴展以前的答案,使其能夠使用除默認語言之外的其他語言。 首先,使用npm i prismjs
安裝 Prism。
在你的angular.json
添加:
"scripts": [
"../node_modules/prismjs/prism.js"
]
在您的組件中導入必要的語言:
import 'prismjs';
import 'prismjs/components/prism-css';
import 'prismjs/components/prism-javascript';
// ...you can import further languages aswell
declare var Prism: any;
請參閱此處了解所有可用語言。
最后,應用代碼高亮:
code: string = 'helloWorld() { console.log("hello world"); }';
languageIdentifier: string = 'typescript';
ngOnInit() {
this.code = Prism.highlight(this.code, Prism.languages[this.languageIdentifier]);
}
在模板中:
<code [innerHtml]="code"></code>
我已經嘗試過 angular-prism 和 ng2-prism 沒有成功(但我可能是壞的嗎?)。
您可能希望在 setTimeout 中添加 ngAfterViewInit 中的代碼,以不觸發“表達式在檢查后已更改”。 錯誤。
ngAfterViewInit() {
setTimeout(() => {
const code = 'var data = 1;';
this.myCode = Prism.highlight(code, Prism.languages.javascript);
}
}
同樣在 html 中,如果您希望它正確顯示,則更正確:
<pre><code [innerHtml]="myCode" class="language-csharp"></code></pre>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.