PrismJS babel config not working in React

1k Views Asked by At

I have babel-plugin-prismjs installed, made .babelrc with this code:

{
    "plugins": [
        ["prismjs", {
            "languages": ["javascript", "css", "html"],
            "plugins": ["line-numbers", "show-language", "copy-to-clipboard", "toolbar", "inline-color"],
            "theme": "prism-tomorrow",
            "css": true
            }
        ]
    ]
}

and imported Prism to App.js.

This is the code in App.js:

import React, { useEffect } from "react";
import Prism from "prismjs";

const code = `
const foo = 'foo';
const bar = 'bar';
console.log(foo + bar);
`.trim()

function App() {
  useEffect(() =>{
    Prism.highlightAll();
  }, [])

  return (
    <pre className="line-numbers">
      <code className="language-js">
        {code}
      </code>
    </pre>
  );
}

export default App;

But the webpage is not highlighting the syntax. What am I missing here?

1

There are 1 best solutions below

0
On BEST ANSWER

If you are using this in a react project built from create-react-app (CRA), your code will not work. Your .babelrc file is not being used. CRA does not expose babel configuration. Check this answer to understand more on this.

For your use-case the easiest way would be to go to prismjs page to download the CSS file. Select the right theme and click 'DOWNLOAD CSS' at the bottom of the page.

Import this CSS file in your App.js code.

import '../prism.css';

This will work for Javascript and some other built-in language packs. If proper markup for your language doesn't show up you will need to import those languages manually as well.

Note: This is just a work around to not ejecting your CRA project. The recommended way is still to use babel-plugin-prismjs if you can.