javascriptreactjsprismjs

Prismjs not working error Prism is not defined


I'm trying to use prism to make a code editor, I copied a template from this codesandbox here. The error is:

./node_modules/prismjs/components/prism-clike.js
E:/Trabajos/Personal projects/OpenAI/Code translator/code-tranlator/node_modules/prismjs/components/prism-clike.js:1
> 1 | Prism.languages.clike = {
  2 |   'comment': [
  3 |       {
  4 |           pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,

For some context I'm using React, the code worked at first, then it stopped working, then started working again without me doing anything, which is odd, I tried uninstalling dependencies and reinstalling them with no success, I've searched the entire internet but there isn't much info on the subject (if any) so I'm stuck.

This is the relevant code from the component:

import React, { useState } from 'react'
import Editor from 'react-simple-code-editor'
import 'prismjs/components/prism-clike'
import 'prismjs/components/prism-javascript'
import 'prismjs/themes/prism.css'
import {useCodex} from '../Context/CodexContext'

export default function CodeEditor() {
    
    const { getCompletion } = useCodex();

    const code = `function add(a, b) {
        return a + b;
      }
      
      const a = 123;
      `

    const hightlightWithLineNumbers = (input) =>
        input
            .split('\n')
            .map(
                (line, i) =>
                    `<span class='editorLineNumber'>${i + 1}</span>${line}`
            )
            .join('\n')

    const [codeValue, setCodeValue] = useState(code)

    function handleSubmit(e) {
        e.preventDefault()
        getCompletion("translate this code from javascript to python " + codeValue);
        console.log("code value: ", codeValue);
    }

    return (
        <div className="container">
            <div className="row justify-content-center align-items-center">
                <Editor
                    value={codeValue}
                    onValueChange={(code) => setCodeValue(code)}
                    highlight={(code) => hightlightWithLineNumbers(code)}
                    padding={10}
                    textareaId="codeArea"
                    className="editor"
                    style={{
                        fontFamily: '"Fira code", "Fira Mono", monospace',
                        fontSize: 18,
                        outline: 0,
                    }}
                />
                <button className="btn btn-primary rounded w-25 my-5">asd</button>
            </div>
        </div>
    )
} 

note1: I don't know if this is relevant but I'm using bootstrap installed with node.


Solution

  • I faced the same issue while working on one of react projects where I was using Prism. I solved it by installing prismjs library and import as follows:

    import Prism from "prismjs";
    

    This should solve your problem!