我尝试使用react和webpack实现SyntaxHighlighter.
我通过npm安装它.
npm install –save syntaxhighlighter
它完美安装.现在的问题是如何正确导入它.
我试过这样的:
import SyntaxHighlighter from 'syntaxhighlighter';
但它不起作用,Chrom控制台报告错误如:
TypeError: Cannot assign to read only property ‘exports’ of object ‘#’
如何在webpack中使用syntaxHighlighter并做出反应?
最佳答案 第1步:安装react-syntax-highlighter
npm install react-syntax-highlighter
第2步:导入react-syntax-highlighter
import SyntaxHighlighter from "react-syntax-highlighter";
第3步:导入样式
import { aStyle } from "react-syntax-highlighter/styles/hljs-or-prism";
第4步:显示您的代码
<SyntaxHighlighter language="yourLanguage" style={aStyle}>
{yourCode}
</SyntaxHighlighter>
例
import React from "react";
import ReactDOM from "react-dom";
import SyntaxHighlighter from "react-syntax-highlighter";
import { docco } from "react-syntax-highlighter/styles/hljs";
function App() {
return (
<div className="App">
<SyntaxHighlighter language="javascript" style={docco}>
{console.log('Hello world!...');}
</SyntaxHighlighter>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
实时运行示例
>我创建了这个实时运行示例:https://codesandbox.io/s/wyjp41m1zl
完整文档
>支持的hls语言:https://github.com/conorhastings/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_HLJS.MD
>支持棱镜语言:https://github.com/conorhastings/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_PRISM.MD
> Github回购:https://github.com/conorhastings/react-syntax-highlighter