ngx-markdown

授权协议 MIT License
开发语言 JavaScript
所属分类 程序开发、 Emoji 表情相关
软件类型 开源软件
地区 不详
投 递 者 井逸明
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Ngx-Markdown Logo

CircleCI Status Coverage Status NPM Version License Monthly Downloads

ngx-markdown

ngx-markdown is an Angular library that combines...

Demo available @ https://jfcere.github.io/ngx-markdown
StackBlitz available @ https://stackblitz.com/edit/ngx-markdown

Table of contents

Installation

ngx-markdown

To add ngx-markdown library to your package.json use the following command.

npm install ngx-markdown --save

As the library is using Marked parser you will need to add node_modules/marked/lib/marked.js to your application.

If you are using Angular CLI you can follow the angular.json example below...

"scripts": [
+ "node_modules/marked/lib/marked.js"
]

Syntax highlight

�� Syntax highlight is optional, skip this step if you are not planning to use it

To activate Prism.js syntax highlight you will need to include...

  • prism.js core library - node_modules/prismjs/prism.js file
  • a highlight css theme - from node_modules/prismjs/themes directory
  • desired code language syntax files - from node_modules/prismjs/components directory

Additional themes can be found by browsing the web such as Prism-Themes or Mokokai for example.

If you are using Angular CLI you can follow the angular.json example below...

"styles": [
  "styles.css",
+ "node_modules/prismjs/themes/prism-okaidia.css"
],
"scripts": [
  "node_modules/marked/lib/marked.js",
+ "node_modules/prismjs/prism.js",
+ "node_modules/prismjs/components/prism-csharp.min.js", # c-sharp language syntax
+ "node_modules/prismjs/components/prism-css.min.js" # css language syntax
]

Line Numbers plugin

To use the line numbers plugin that shows line numbers in code blocks, in addition to Prism.js configuration files, you will need to include the following files from prismjs/plugins/line-numbers directory to your application:

  • CSS styling for line numbers - prism-line-numbers.css
  • line numbers plugin script - prism-line-numbers.js

If you are using Angular CLI you can follow the angular.json example below...

"styles": [
  "src/styles.css",
  "node_modules/prismjs/themes/prism-okaidia.css",
+ "node_modules/prismjs/plugins/line-numbers/prism-line-numbers.css"
],
"scripts": [
  "node_modules/marked/lib/marked.js",
  "node_modules/prismjs/prism.js",
  "node_modules/prismjs/components/prism-csharp.min.js",
  "node_modules/prismjs/components/prism-css.min.js",
+ "node_modules/prismjs/plugins/line-numbers/prism-line-numbers.js"
]

Using markdown component and/or directive, you will be able to use the lineNumbers property to activate the plugin. The property can be used in combination with either data for variable binding, src for remote content or using transclusion for static markdown.

Additionally, you can use start input property to specify the offset number for the first display line.

<markdown [src]="path/to/file.js" lineNumbers [start]="5"></markdown>

Line Highlight plugin

To use the line highlight plugin that highlights specific lines and/or line ranges in code blocks, in addition to Prism.js configuration files, you will need to include the following files from prismjs/plugins/line-highlight directory to your application:

  • CSS styling for line highlight - prism-line-highlight.css
  • line highlight plugin script - prism-line-highlight.js

If you are using Angular CLI you can follow the angular.json example below...

"styles": [
  "src/styles.css",
  "node_modules/prismjs/themes/prism-okaidia.css",
+ "node_modules/prismjs/plugins/line-highlight/prism-line-highlight.css"
],
"scripts": [
  "node_modules/marked/lib/marked.js",
  "node_modules/prismjs/prism.js",
  "node_modules/prismjs/components/prism-csharp.min.js",
  "node_modules/prismjs/components/prism-css.min.js",
+ "node_modules/prismjs/plugins/line-highlight/prism-line-highlight.js"
]

Using markdown component and/or directive, you will be able to use the lineHighlight property to activate the plugin. The property can be used in combination with either data for variable binding, src for remote content or using transclusion for static markdown.

Use line input property to specify the line(s) to highlight and optionally there is a lineOffset property to specify the starting line of code your snippet represents.

<markdown [src]="path/to/file.js" lineHighlight [line]="'6, 10-16'" [lineOffset]="5"></markdown>

Emoji support

�� Emoji support is optional, skip this step if you are not planning to use it

To activate Emoji-Toolkit for emoji suppport you will need to include...

  • Emoji-Toolkit library - node_modules/emoji-toolkit/lib/js/joypixels.min.js

If you are using Angular CLI you can follow the angular.json example below...

"scripts": [
  "node_modules/marked/lib/marked.js",
+ "node_modules/emoji-toolkit/lib/js/joypixels.min.js",
]

Emoji plugin

Using markdown component and/or directive, you will be able to use the emoji property to activate Emoji-Toolkit plugin that converts emoji shortnames such as to native unicode emojis.

<markdown emoji>I ❤ ngx-markdown</markdown>

�� You can refer to this Emoji Cheat Sheet for a complete list of shortnames.

Math rendering

�� Math rendering is optional, skip this step if you are not planning to use it

To activate KaTeX math rendering you will need to include...

  • KaTex JavaScript library - node_modules/katex/dist/katex.min.js file
  • KaTex CSS customization - node_modules/katex/dist/katex.min.css file

If you are using Angular CLI you can follow the angular.json example below...

"styles": [
  "styles.css",
+ "node_modules/katex/dist/katex.min.css"
],
"scripts": [
  "node_modules/marked/lib/marked.js",
+ "node_modules/katex/dist/katex.min.js",
]

KaTeX plugin

Using markdown component and/or directive, you will be able to use the katex property to activate KaTeX plugin that render mathematical expression to HTML.

<markdown [src]="path/to/file.md" katex></markdown>

Optionally, you can use katexOptions property to specify KaTeX options.

import { KatexOptions } from 'ngx-markdown';

public options: KatexOptions = {
  displayMode: true,
  throwOnError: false,
  errorColor: '#cc0000',
  ...
};
<markdown [src]="path/to/file.md" katex [katexOptions]="options"></markdown>

�� Follow official KaTeX options documentation for more details on the available options.

Configuration

Main application module

You must import MarkdownModule inside your main application module (usually named AppModule) with forRoot to be able to use markdown component and/or directive.

import { NgModule } from '@angular/core';
+ import { MarkdownModule } from 'ngx-markdown';

import { AppComponent } from './app.component';

@NgModule({
  imports: [
+   MarkdownModule.forRoot(),
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
})
export class AppModule { }

If you want to use the [src] attribute to directly load a remote file, in order to keep only one instance of HttpClient and avoid issues with interceptors, you also have to provide HttpClient:

imports: [
+  HttpClientModule,
+  MarkdownModule.forRoot({ loader: HttpClient }),
],

Sanitization

As of ngx-markdown v9.0.0 sanitization is enabled by default and uses Angular DomSanitizer with SecurityContext.HTML to avoid XSS vulnerabilities. The SecurityContext level can be changed using the sanitize property when configuring MarkdownModule.

import { SecurityContext } from '@angular/core';

// enable default sanitization
MarkdownModule.forRoot()

// turn off sanitization
MarkdownModule.forRoot({
  sanitize: SecurityContext.NONE
})

�� Follow Angular DomSanitizer documentation for more information on sanitization and security contexts.

MarkedOptions

Optionally, markdown parsing can be configured by passing MarkedOptions to the forRoot method of MarkdownModule.

Imports:

import { MarkdownModule, MarkedOptions } from 'ngx-markdown';

Default options:

// using default options
MarkdownModule.forRoot(),

Custom options and passing HttpClient to use [src] attribute:

// using specific options with ValueProvider and passing HttpClient
MarkdownModule.forRoot({
  loader: HttpClient, // optional, only if you use [src] attribute
  markedOptions: {
    provide: MarkedOptions,
    useValue: {
      gfm: true,
      breaks: false,
      pedantic: false,
      smartLists: true,
      smartypants: false,
    },
  },
}),

MarkedOptions.renderer

MarkedOptions also exposes the renderer property which allows you to override token rendering for your whole application.

The example below overrides the default blockquote token rendering by adding a CSS class for custom styling when using Bootstrap CSS:

import { MarkedOptions, MarkedRenderer } from 'ngx-markdown';

// function that returns `MarkedOptions` with renderer override
export function markedOptionsFactory(): MarkedOptions {
  const renderer = new MarkedRenderer();

  renderer.blockquote = (text: string) => {
    return '<blockquote class="blockquote"><p>' + text + '</p></blockquote>';
  };

  return {
    renderer: renderer,
    gfm: true,
    breaks: false,
    pedantic: false,
    smartLists: true,
    smartypants: false,
  };
}

// using specific option with FactoryProvider
MarkdownModule.forRoot({
  loader: HttpClient,
  markedOptions: {
    provide: MarkedOptions,
    useFactory: markedOptionsFactory,
  },
}),

Other application modules

Use forChild when importing MarkdownModule into other application modules to allow you to use the same parser configuration across your application.

import { NgModule } from '@angular/core';
+ import { MarkdownModule } from 'ngx-markdown';

import { HomeComponent } from './home.component';

@NgModule({
  imports: [
+   MarkdownModule.forChild(),
  ],
  declarations: [HomeComponent],
})
export class HomeModule { }

Usage

ngx-markdown provides different approaches to help you parse markdown to your application depending on your needs.

�� As of Angular 6, the template compiler strips whitespace by default. Use ngPreserveWhitespaces directive to preserve whitespaces such as newlines in order for the markdown-formatted content to render as intended.
https://angular.io/api/core/Component#preserveWhitespaces

Component

You can use markdown component to either parse static markdown directly from your HTML markup, load the content from a remote URL using src property or bind a variable to your component using data property. You can get a hook on load complete using load output event property, on loading error using error output event property or when parsing is completed using ready output event property.

<!-- static markdown -->
<markdown ngPreserveWhitespaces>
  # Markdown
</markdown>

<!-- loaded from remote url -->
<markdown [src]="'path/to/file.md'" (load)="onLoad($event)" (error)="onError($event)"></markdown>

<!-- variable binding -->
<markdown [data]="markdown" (ready)="onReady()"></markdown>

Directive

The same way the component works, you can use markdown directive to accomplish the same thing.

<!-- static markdown -->
<div markdown ngPreserveWhitespaces>
  # Markdown
</div>

<!-- loaded from remote url -->
<div markdown [src]="'path/to/file.md'" (load)="onLoad($event)" (error)="onError($event)"></div>

<!-- variable binding -->
<div markdown [data]="markdown" (ready)="onReady()"></div>

Pipe

Using markdown pipe to transform markdown to HTML allow you to chain pipe transformations and will update the DOM when value changes.

<!-- chain `language` pipe with `markdown` pipe to convert typescriptMarkdown variable content -->
<div [innerHTML]="typescriptMarkdown | language : 'typescript' | markdown"></div>

Service

You can use MarkdownService to have access to markdown parser and syntax highlight methods.

import { Component, OnInit } from '@angular/core';
import { MarkdownService } from 'ngx-markdown';

@Component({ ... })
export class ExampleComponent implements OnInit {
  constructor(private markdownService: MarkdownService) { }

  ngOnInit() {
    // outputs: <p>I am using <strong>markdown</strong>.</p>
    console.log(this.markdownService.compile('I am using __markdown__.'));
  }
}

Renderer

Tokens can be rendered in a custom manner by either...

  • providing the renderer property with the MarkedOptions when importing MarkdownModule.forRoot() into your main application module (see Configuration section)
  • using MarkdownService exposed renderer

Here is an example of overriding the default heading token rendering through MarkdownService by adding an embedded anchor tag like on GitHub:

import { Component, OnInit } from '@angular/core';
import { MarkdownService } from 'ngx-markdown';

@Component({
  selector: 'app-example',
  template: '<markdown># Heading</markdown>',
})
export class ExampleComponent implements OnInit {
  constructor(private markdownService: MarkdownService) { }

  ngOnInit() {
    this.markdownService.renderer.heading = (text: string, level: number) => {
      const escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
      return '<h' + level + '>' +
               '<a name="' + escapedText + '" class="anchor" href="#' + escapedText + '">' +
                 '<span class="header-link"></span>' +
               '</a>' + text +
             '</h' + level + '>';
    };
  }
}

This code will output the following HTML:

<h1>
  <a name="heading" class="anchor" href="#heading">
    <span class="header-link"></span>
  </a>
  Heading
</h1>

�� Follow official marked.renderer documentation for the list of tokens that can be overriden.

Syntax highlight

When using static markdown you are responsible to provide the code block with related language.

<markdown ngPreserveWhitespaces>
+  ```typescript
    const myProp: string = 'value';
+  ```
</markdown>

When using remote URL ngx-markdown will use the file extension to automatically resolve the code language.

<!-- will use html highlights -->
<markdown [src]="'path/to/file.html'"></markdown>

<!-- will use php highlights -->
<markdown [src]="'path/to/file.php'"></markdown>

When using variable binding you can optionally use language pipe to specify the language of the variable content (default value is markdown when pipe is not used).

<markdown [data]="markdown | language : 'typescript'"></markdown>

Demo application

A demo is available @ https://jfcere.github.io/ngx-markdown and its source code can be found inside the demo directory.

The following commands will clone the repository, install npm dependencies and serve the application @ http://localhost:4200

git clone https://github.com/jfcere/ngx-markdown.git
npm install
npm start

AoT compilation

Building with AoT is part of the CI and is tested every time a commit occurs so you don't have to worry at all.

Road map

Here is the list of tasks that will be done on this library in the near future ...

  • Add copy-to-clipboard feature
  • Add a FAQ section to the README.md

Contribution

Contributions are always welcome, just make sure that ...

  • Your code style matches with the rest of the project
  • Unit tests pass
  • Linter passes

Support Development

The use of this library is totally free and no donation is required.

As the owner and primary maintainer of this project, I am putting a lot of time and effort beside my job, my family and my private time to bring the best support I can by answering questions, addressing issues and improving the library to provide more and more features over time.

If this project has been useful, that it helped you or your business to save precious time, don't hesitate to give it a star and to consider a donation to support its maintenance and future development.

License

Licensed under MIT.

  • ngx-markdown 是 Angular2+ 的一个第三方库,它的主要功能是将md文件转换为HTML格式,并且支持语法高亮。 GITHUB地址:https://github.com/jfcere/ngx-markdown 安装 1. 安装 ngx-markdown 使用 npm 进行安装,在 `angular`项目目录中执行: npm install ngx-markdown --save  

  • angular2 集成 Editor.md:https://blog.csdn.net/qq_16566415/article/details/73741247 "./node_modules/jquery/dist/jquery.min.js", "src/assets/editormd/editormd.js", "src/assets/editormd/lib/marked.min.js",

  • 遇到过这个需求,然后经历了一番搜索和尝试,基本解决了问题。 示例: 基本表格代码: |第一列|第二列|第三列| |-|-|-| |111|222|333| |111111111111111111111111111|22222222222222222222222222222222222222222222|3333333333333333333333333333333| 表格样式 第一列 第二列 第

  • 前言:笔者之前是使用富文本编辑器,现在转用markdown编辑器,但是在写文章的时候发现即使博客主页设置用上了代码高亮皮肤,但还是在插入代码段的时候不起作用,查阅了他人的博客才发现要加上key描述 类似这样,比如你写c++代码,你要在’’'之后加上c++语言的key:cpp,这样就可以实现你的代码高亮了,下面表格附上各类语言的关键字key(注:表格转自源) #include<bits/stdc++

  • 说明: Nginx的HTTP核心模块只解析request的请求行和请求头,不会主动读取HTTP 请求body数据,但是提供了ngx_http_read_client_request_body方法,供各个filter模块处理。 2.ngx_http_wait_request_handler:等待read事件上来,并且等到HTTP的request数据 ngx_http_process_request_

  • 优质插件 偶尔发现了掘金使用的bytemd 插件,vue,angulr,react 都可以进行支持,官方地址https://bytemd.js.org/#usage 任何前端框架通用 Editor.md https://pandao.github.io/editor.md/#dependents 1.1 AngularJs 12 使用 Editor.md 实现 Markdown 编辑 https:

  • Markdown-md文件 软件: Typora 下载官网: https://www.typora.io/#windows 编写方法:  

 相关资料
  • ngx-weui 是一个使用 Angular 构建的 WeUI 组件。 在线示例以及API文档。

  • ngx-fastdfs 是 nginx + lua +fastdfs 实现分布式图片实时动态压缩。 install 进入docker目录docker build -t  fastdfs:dev . 使用 docker -idt -p 80:80 fastdfs:dev /bin/bash进入容器执行/etc/rc.local 测试 进入容器执行test目录下的./test.sh或者直接执行下面脚本

  • ngx-admin Who uses ngx-admin?| Documentation | Installation Guidelines | Angular templates New! Material theme for ngx-admin Material admin theme is based on the most popular Angular dashboard templat

  • @sweetalert2/ngx-sweetalert2 Official SweetAlert2 integration for Angular This is not a regular API wrapper for SweetAlert (which already works very well alone), it intends to provide Angular-esque ut

  • ngx-dropzone A lightweight and highly customizable Angular dropzone component for file uploads. For a demo see DEMO. And the CODE for the demo. Install $ npm install --save ngx-dropzone Usage // in ap

  • ngx-slick Support angular 6+, Slick 1.8.1 Example Installation To install this library, run: $ npm install ngx-slick --save Consuming your library Once you have published your library to npm, you can