Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxHighlighter with webpack and react

I try to implement SyntaxHighlighter using react and webpack.

I install it via npm.

npm install --save syntaxhighlighter

It install perfectly. Now the problem is how to import it properly.

I've tried like this:

import SyntaxHighlighter from 'syntaxhighlighter';

But it doesn't work, Chrom console reports the error like:

TypeError: Cannot assign to read only property 'exports' of object '#'

How can I use syntaxHighlighter with webpack and react?

like image 814
Marco Avatar asked Aug 11 '26 23:08

Marco


1 Answers

Step 1: Install react-syntax-highlighter

npm install react-syntax-highlighter

Step 2: Import react-syntax-highlighter

import SyntaxHighlighter from "react-syntax-highlighter";

Step 3: Import a style

import { aStyle } from "react-syntax-highlighter/styles/hljs-or-prism";

Step 4: Display your code

<SyntaxHighlighter language="yourLanguage" style={aStyle}>
     {yourCode}
</SyntaxHighlighter>

Example

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);

Live running example

  • I created this live running example: https://codesandbox.io/s/wyjp41m1zl

Full documentation

  • Supported languages for hls: https://github.com/conorhastings/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_HLJS.MD
  • Supported languages for prism: https://github.com/conorhastings/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_PRISM.MD
  • Github repo: https://github.com/conorhastings/react-syntax-highlighter
like image 157
Ala Eddine JEBALI Avatar answered Aug 14 '26 17:08

Ala Eddine JEBALI



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!