Two methods of highlighting with highlight.js code in React
problem
resolvent
Use highlight.js npm package (not recommended)
yarn add highlight.js
import hljs from 'highlight.js'; import 'highlight.js/styles/default.css';
-
Use in function component //function component //Cataloged/miao/ out /no/blog/guest (@/azimiao. com) function component1(props){ React.useEffect(()=>{ document.querySelectorAll("pre code").forEach(block => { try{hljs.highlightBlock(block);} catch(e){console.log(e);} }); }); return( <div>{…………}</div> ); } -
Use in class component class Preview extends Component { ComponentDidMount() {//Edit/miao/Out /Not/Blog/Guest (@/azimiao. com) this.highlightCallBack(); } componentDidUpdate() { //Cataloged/miao/haunted/blog/guest (@/azimiao. com) this.highlightCallBack(); } highlightCallBack = () => { document.querySelectorAll("pre code").forEach(block => { try{hljs.highlightBlock(block);} catch(e){console.log(e);} }); }; render(){ Return (/* Press/Meow/ Out /Not/Blog/Guest (@/azimiao. com)*/ <div>{……}</div> ); } } This method has a very obvious disadvantage: when webpack is packaged, highlight.js will be packaged into mian.js by default, resulting in an increase of about 900 KiB in the entire file.
Use CDN library
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/highlightjs/ cdn-release@10.1.1 /build/styles/github.min.css"> <script src="//cdn.jsdelivr.net/gh/highlightjs/ cdn-release@10.1.1 /build/highlight.min.js"></script>
-
Use in function component //function component function component1(props){ React.useEffect(()=>{ document.querySelectorAll("pre code").forEach(block => { try{hljs.highlightBlock(block);} catch(e){console.log(e);} }); }); return( <div>{…………}</div> ); } -
Use in class component class Preview extends Component { componentDidMount() { this.highlightCallBack(); }/*@Cataloged @ miao @ out @ no @ (@/azimiao. com)*/ componentDidUpdate() { this.highlightCallBack(); }/*Cataloged/miao/ out /no/blog/guest (@/azimiao. com)*/ highlightCallBack = () => { document.querySelectorAll("pre code").forEach(block => { try{hljs.highlightBlock(block);} catch(e){console.log(e);} }); }; render(){ Return (/* Press/Meow/ Out /Not/Blog/Guest (@/azimiao. com)*/ <div>{…………}</div> ); } }