mirror of
https://github.com/facebook/docusaurus.git
synced 2025-06-05 12:22:45 +02:00
feat: hljs syntax highlighting & nits
This commit is contained in:
parent
0058b20d9e
commit
ea37e54477
8 changed files with 44 additions and 52 deletions
22
lib/core/components/Markdown/highlight.js
Normal file
22
lib/core/components/Markdown/highlight.js
Normal file
|
@ -0,0 +1,22 @@
|
|||
const hljs = require('highlight.js');
|
||||
const chalk = require('chalk');
|
||||
const escapeHtml = require('escape-html');
|
||||
|
||||
export default (str, rawLang) => {
|
||||
if (rawLang === 'text') {
|
||||
return escapeHtml(str);
|
||||
}
|
||||
const lang = rawLang.toLowerCase();
|
||||
try {
|
||||
if (hljs.getLanguage(lang)) {
|
||||
return hljs.highlight(lang, str).value;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(
|
||||
chalk.yellow(
|
||||
`Highlight.js syntax highlighting for language "${lang}" is not supported.`
|
||||
)
|
||||
);
|
||||
}
|
||||
return hljs.highlightAuto(str).value;
|
||||
};
|
|
@ -1,9 +1,8 @@
|
|||
/* eslint-disable react/no-danger */
|
||||
/* eslint-disable */
|
||||
|
||||
import React from 'react';
|
||||
import Markdown from 'remarkable';
|
||||
import hljs from 'highlight.js';
|
||||
import prismjs from 'prismjs';
|
||||
import highlight from './highlight';
|
||||
import anchors from './anchors';
|
||||
|
||||
class MarkdownBlock extends React.Component {
|
||||
|
@ -36,46 +35,7 @@ class MarkdownBlock extends React.Component {
|
|||
const {siteConfig} = this.props;
|
||||
const md = new Markdown({
|
||||
langPrefix: 'hljs css language-',
|
||||
highlight(str, reqLang) {
|
||||
const lang =
|
||||
reqLang || (siteConfig.highlight && siteConfig.highlight.defaultLang);
|
||||
if (lang === 'text') {
|
||||
return str;
|
||||
}
|
||||
if (lang) {
|
||||
try {
|
||||
if (
|
||||
siteConfig.usePrism === true ||
|
||||
(siteConfig.usePrism &&
|
||||
siteConfig.usePrism.length > 0 &&
|
||||
siteConfig.usePrism.indexOf(lang) !== -1)
|
||||
) {
|
||||
try {
|
||||
const language = alias[lang] || lang;
|
||||
// Currently people using prismjs on Node have to individually require()
|
||||
// every single language (https://github.com/PrismJS/prism/issues/593)
|
||||
require(`prismjs/components/prism-${language}.min`); // eslint-disable-line
|
||||
return prismjs.highlight(str, prismjs.languages[language]);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
if (hljs.getLanguage(lang)) {
|
||||
return hljs.highlight(lang, str).value;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
return hljs.highlightAuto(str).value;
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
|
||||
return '';
|
||||
},
|
||||
highlight: highlight,
|
||||
html: true,
|
||||
linkify: true
|
||||
});
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue