markdown-it + highlight.js简易实现
1、配置highlightjs,针对markdown中各种语言高亮,针对对应的标签 pre code 里面的样式 -- index.js
var hljs = require('highlight.js'); // hljs 只针对pre code 里面的样式 hljs.registerLanguage('actionscript', require('highlight.js/lib/languages/actionscript')); hljs.registerLanguage('apache', require('highlight.js/lib/languages/apache')); hljs.registerLanguage('armasm', require('highlight.js/lib/languages/armasm')); hljs.registerLanguage('xml', require('highlight.js/lib/languages/xml')); hljs.registerLanguage('asciidoc', require('highlight.js/lib//languages/asciidoc')); hljs.registerLanguage('avrasm', require('highlight.js/lib/languages/avrasm')); hljs.registerLanguage('bash', require('highlight.js/lib/languages/bash')); hljs.registerLanguage('clojure', require('highlight.js/lib/languages/clojure')); hljs.registerLanguage('cmake', require('highlight.js/lib/languages/cmake')); hljs.registerLanguage('coffeescript', require('highlight.js/lib/languages/coffeescript')); hljs.registerLanguage('cpp', require('highlight.js/lib/languages/cpp')); hljs.registerLanguage('arduino', require('highlight.js/lib/languages/arduino')); hljs.registerLanguage('css', require('highlight.js/lib/languages/css')); hljs.registerLanguage('diff', require('highlight.js/lib/languages/diff')); hljs.registerLanguage('django', require('highlight.js/lib/languages/django')); hljs.registerLanguage('dockerfile', require('highlight.js/lib/languages/dockerfile')); hljs.registerLanguage('ruby', require('highlight.js/lib/languages/ruby')); hljs.registerLanguage('fortran', require('highlight.js/lib/languages/fortran')); hljs.registerLanguage('glsl', require('highlight.js/lib/languages/glsl')); hljs.registerLanguage('go', require('highlight.js/lib/languages/go')); hljs.registerLanguage('groovy', require('highlight.js/lib/languages/groovy')); hljs.registerLanguage('handlebars', require('highlight.js/lib/languages/handlebars')); hljs.registerLanguage('haskell', require('highlight.js/lib/languages/haskell')); hljs.registerLanguage('ini', require('highlight.js/lib/languages/ini')); hljs.registerLanguage('java', require('highlight.js/lib/languages/java')); hljs.registerLanguage('javascript', require('highlight.js/lib/languages/javascript')); hljs.registerLanguage('json', require('highlight.js/lib/languages/json')); hljs.registerLanguage('less', require('highlight.js/lib/languages/less')); hljs.registerLanguage('lisp', require('highlight.js/lib/languages/lisp')); hljs.registerLanguage('livescript', require('highlight.js/lib/languages/livescript')); hljs.registerLanguage('lua', require('highlight.js/lib/languages/lua')); hljs.registerLanguage('makefile', require('highlight.js/lib/languages/makefile')); hljs.registerLanguage('matlab', require('highlight.js/lib/languages/matlab')); hljs.registerLanguage('mipsasm', require('highlight.js/lib/languages/mipsasm')); hljs.registerLanguage('perl', require('highlight.js/lib/languages/perl')); hljs.registerLanguage('nginx', require('highlight.js/lib/languages/nginx')); hljs.registerLanguage('objectivec', require('highlight.js/lib/languages/objectivec')); hljs.registerLanguage('php', require('highlight.js/lib/languages/php')); hljs.registerLanguage('python', require('highlight.js/lib/languages/python')); hljs.registerLanguage('rust', require('highlight.js/lib/languages/rust')); hljs.registerLanguage('scala', require('highlight.js/lib/languages/scala')); hljs.registerLanguage('scheme', require('highlight.js/lib/languages/scheme')); hljs.registerLanguage('scss', require('highlight.js/lib/languages/scss')); hljs.registerLanguage('smalltalk', require('highlight.js/lib/languages/smalltalk')); hljs.registerLanguage('stylus', require('highlight.js/lib/languages/stylus')); hljs.registerLanguage('swift', require('highlight.js/lib/languages/swift')); hljs.registerLanguage('tcl', require('highlight.js/lib/languages/tcl')); hljs.registerLanguage('tex', require('highlight.js/lib/languages/tex')); hljs.registerLanguage('typescript', require('highlight.js/lib/languages/typescript')); hljs.registerLanguage('verilog', require('highlight.js/lib/languages/verilog')); hljs.registerLanguage('vhdl', require('highlight.js/lib/languages/vhdl')); hljs.registerLanguage('yaml', require('highlight.js/lib/languages/yaml')); var mdHtml; var defaults = { html: false, // Enable HTML tags in source xhtmlOut: false, // Use '/' to close single tags (<br />) breaks: false, // Convert '\n' in paragraphs into <br> langPrefix: 'language-', // CSS language prefix for fenced blocks linkify: true, // autoconvert URL-like texts to links typographer: true, // Enable smartypants and other sweet transforms // options below are for demo only _highlight: true, _strict: false, _view: 'html' // html / src / debug }; defaults.highlight = function (str, lang) { var esc = mdHtml.utils.escapeHtml; if (lang && hljs.getLanguage(lang)) { try { return '<pre class="hljs"><code>' + hljs.highlight(lang, str, true).value + '</code></pre>'; } catch (__) {} } return '<pre class="hljs"><code>' + esc(str) + '</code></pre>'; }; function mdInit() { mdHtml = window.markdownit(defaults) .use(require('markdown-it-abbr')) .use(require('markdown-it-container'), 'warning') .use(require('markdown-it-deflist')) .use(require('markdown-it-emoji')) .use(require('markdown-it-footnote')) .use(require('markdown-it-ins')) .use(require('markdown-it-mark')) .use(require('markdown-it-sub')) .use(require('markdown-it-sup')) .use(require('markdown-it-imsize')) .use(require('markdown-it-attrs'),{ // optional, these are default options leftDelimiter: '{', rightDelimiter: '}', allowedAttributes: [] // empty array = all attributes are allowed }) // 可以添加class .use(require('markdown-it-kbd')) //模拟kbd [[x]] .use(require('markdown-it-katex'),{"throwOnError" : false, "errorColor" : " #cc0000"}); //数学语法高亮 $\sqrt{3x-1}+(1+x)^2$ // html 标签美化 mdHtml.renderer.rules.table_open = function () { return '<table class="table table-striped">\n'; }; // 替换 emoji mdHtml.renderer.rules.emoji = function (token, idx) { return window.twemoji.parse(token[idx].content); }; // Inject line numbers for sync scroll. Notes: // // - We track only headings and paragraphs on first level. That's enough. // - Footnotes content causes jumps. Level limit filter it automatically. function injectLineNumbers(tokens, idx, options, env, slf) { var line; if (tokens[idx].map && tokens[idx].level === 0) { line = tokens[idx].map[0]; tokens[idx].attrJoin('class', 'line'); tokens[idx].attrSet('data-line', String(line)); } return slf.renderToken(tokens, idx, options, env, slf); } mdHtml.renderer.rules.paragraph_open = mdHtml.renderer.rules.heading_open = injectLineNumbers; } $(function () { mdInit(); var source = $('.source').val(); $('#markinit').html(mdHtml.render(source)); $('.source').on('keyup paste cut mouseup',function(){ var source = $('.source').val(); $('#markinit').html(mdHtml.render(source)); }); })
2、 index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>markdown</title> <link rel="stylesheet" href="./index.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@9.15.10/styles/ocean.css" integrity="sha256-/k48Q/el/eYQ+d4125d0zSBy6P56LX8iKiUFnP1DU40=" crossorigin="anonymous"> <script src="https://cdn.bootcss.com/markdown-it/10.0.0/markdown-it.min.js"></script> <script src="https://cdn.bootcss.com/highlight.js/9.15.10/highlight.min.js"></script> <script src="https://cdn.bootcss.com/twemoji/12.0.4/2/twemoji.min.js"></script> <script src="https://cdn.jsdelivr.net/jquery/1.11.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.5.1/katex.min.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/github-markdown-css/2.2.1/github-markdown.css"/> </head> <body> <textarea class="source full-height"> --- __Advertisement :)__ - __[pica](https://nodeca.github.io/pica/demo/)__ - high quality and fast image resize in browser. - __[babelfish](https://github.com/nodeca/babelfish/)__ - developer friendly i18n with plurals support and easy syntax. You will like those projects! --- # h1 Heading 8-) ## h2 Heading ### h3 Heading #### h4 Heading ##### h5 Heading ###### h6 Heading ## Horizontal Rules ___ --- *** ## Typographic replacements Enable typographer option to see result. (c) (C) (r) (R) (tm) (TM) (p) (P) +- test.. test... test..... test?..... test!.... !!!!!! ???? ,, -- --- "Smartypants, double quotes" and 'single quotes' ## Emphasis **This is bold text** __This is bold text__ *This is italic text* _This is italic text_ ~~Strikethrough~~ ## Blockquotes > Blockquotes can also be nested... >> ...by using additional greater-than signs right next to each other... > > > ...or with spaces between arrows. ## Lists Unordered + Create a list by starting a line with `+`, `-`, or `*` + Sub-lists are made by indenting 2 spaces: - Marker character change forces new list start: * Ac tristique libero volutpat at + Facilisis in pretium nisl aliquet - Nulla volutpat aliquam velit + Very easy! Ordered 1. Lorem ipsum dolor sit amet 2. Consectetur adipiscing elit 3. Integer molestie lorem at massa 1. You can use sequential numbers... 1. ...or keep all the numbers as `1.` Start numbering with offset: 57. foo 1. bar ## Code Inline `code` Indented code // Some comments line 1 of code line 2 of code line 3 of code Block code "fences" ``` Sample text here... ``` Syntax highlighting ``` js var foo = function (bar) { return bar++; }; console.log(foo(5)); ``` ``` java public String rsaSign(PrivateKey privateKey, String content, String charset){ java.security.Signature signet = java.security.Signature.getInstance(“SHA1WithRSA”); signet.initSign(privateKey); signet.update(content.getBytes(charset)); byte[] signed = signet.sign(); return new String(Base64.encodeBase64(signed),charset); } ``` ## Tables | Option | Description | | ------ | ----------- | | data | path to data files to supply the data that will be passed into templates. | | engine | engine to be used for processing templates. Handlebars is the default. | | ext | extension to be used for dest files. | Right aligned columns | Option | Description | | ------:| -----------:| | data | path to data files to supply the data that will be passed into templates. | | engine | engine to be used for processing templates. Handlebars is the default. | | ext | extension to be used for dest files. | ## Links [link text](http://dev.nodeca.com) [link with title](http://nodeca.github.io/pica/demo/ "title text!") Autoconverted link https://github.com/nodeca/pica (enable linkify to see) ## Images ![Minion](https://octodex.github.com/images/minion.png) ![Stormtroopocat](https://octodex.github.com/images/stormtroopocat.jpg "The Stormtroopocat") Like links, Images also have a footnote style syntax ![Alt text][id] With a reference later in the document defining the URL location: [id]: https://octodex.github.com/images/dojocat.jpg "The Dojocat" ## Plugins The killer feature of `markdown-it` is very effective support of [syntax plugins](https://www.npmjs.org/browse/keyword/markdown-it-plugin). ### [Emojies](https://github.com/markdown-it/markdown-it-emoji) > Classic markup: :wink: :crush: :cry: :tear: :laughing: :yum: > > Shortcuts (emoticons): :-) :-( 8-) ;) see [how to change output](https://github.com/markdown-it/markdown-it-emoji#change-output) with twemoji. ### [Subscript](https://github.com/markdown-it/markdown-it-sub) / [Superscript](https://github.com/markdown-it/markdown-it-sup) - 19^th^ - H~2~O ### [\<ins>](https://github.com/markdown-it/markdown-it-ins) ++Inserted text++ ### [\<mark>](https://github.com/markdown-it/markdown-it-mark) ==Marked text== ### [Footnotes](https://github.com/markdown-it/markdown-it-footnote) Footnote 1 link[^first]. Footnote 2 link[^second]. Inline footnote^[Text of inline footnote] definition. Duplicated footnote reference[^second]. [^first]: Footnote **can have markup** and multiple paragraphs. [^second]: Footnote text. ### [Definition lists](https://github.com/markdown-it/markdown-it-deflist) Term 1 : Definition 1 with lazy continuation. Term 2 with *inline markup* : Definition 2 { some code, part of Definition 2 } Third paragraph of definition 2. _Compact style:_ Term 1 ~ Definition 1 Term 2 ~ Definition 2a ~ Definition 2b ### [Abbreviations](https://github.com/markdown-it/markdown-it-abbr) This is HTML abbreviation example. It converts "HTML", but keep intact partial entries like "xxxHTMLyyy" and so on. *[HTML]: Hyper Text Markup Language ### [Custom containers](https://github.com/markdown-it/markdown-it-container) ::: warning *here be dragons* ::: </textarea> <div id="markinit" class="markdown_views"></div> <script src="index22.js"></script> </body> </html>
3.package.json
{ "name": "webpackdemo", "version": "1.0.0", "description": "demo", "main": "index.js", "scripts": { "test": "webpack-dev-server --progress --colors --host 127.0.0.1 --port 7890 --in", "try": "webpack-dev-server --progress --colors --in" }, "keywords": [ "demo" ], "author": "Mr liu", "license": "ISC", "devDependencies": { "ansi": "^0.3.0", "autoprefixer-stylus": "^0.14.0", "benchmark": "~2.1.0", "browserify": "^16.3.0", "chai": "^4.2.0", "coveralls": "^3.0.4", "css-loader": "^0.28.10", "eslint": "^6.0.1", "express": "^4.14.0", "highlight.js": "^9.15.10", "istanbul": "^0.4.5", "markdown-it-abbr": "^1.0.4", "markdown-it-container": "^2.0.0", "markdown-it-deflist": "^2.0.0", "markdown-it-emoji": "1.4.0", "markdown-it-footnote": "^3.0.1", "markdown-it-for-inline": "^0.1.0", "markdown-it-ins": "^2.0.0", "markdown-it-mark": "^2.0.0", "markdown-it-sub": "^1.0.0", "markdown-it-sup": "^1.0.0", "markdown-it-testgen": "^0.1.3", "mocha": "^6.1.4", "ndoc": "^5.0.0", "pug-cli": "^1.0.0-alpha6", "style-loader": "^0.20.3", "stylus": "^0.54.5", "supertest": "^4.0.2", "terser": "^4.1.2", "webpack": "^4.41.1", "webpack-cli": "^3.3.9", "webpack-dev-server": "^3.8.2" }, "dependencies": { "argparse": "^1.0.7", "entities": "~2.0.0", "linkify-it": "^2.0.0", "markdown-it-attrs": "^3.0.1", "markdown-it-imsize": "^2.0.0", "markdown-it-katex": "^2.0.3", "markdown-it-kbd": "^2.0.0", "mdurl": "^1.0.1", "uc.micro": "^1.0.5" } }
4、readme
webpack npm run try