2020年12月31日星期四

Using Prism.js line-highlight plugin with Next.js app causes "Text content did not match" error

I have basic Prism.js functionality working with my Next.js site by doing the following things:

package.json:

  "dependencies": {     ...      "next": "9.5.3",      "react": "16.13.1",      "typescript": "3.9.4",      "prismjs": "1.22.0"    },    "devDependencies": {      ...      "@types/prismjs": "1.16.2"    }  

pages/_app.tsx:

...  import "prismjs/themes/prism-tomorrow.css";  ...  

pages/blog-article.tsx:

...  import Prism from "prismjs";  import "prismjs/components/prism-hcl";  import "prismjs/plugins/line-highlight/prism-line-highlight";  ...    export default function BlogArticle(){    useEffect(() => {      if (typeof window !== 'undefined') {        Prism.highlightAll();      }    }, []);      return <div>      <pre className="language-hcl" style=>        <code>{`xxx`}</code>     </pre>   </div>  }  

That all works fine and source code is hightlighted properly - the problem comes when I try to import the line-highlight plugin for Prism.

When I add the data-line attribute to the HTML in pages/blog-article.tsx:

...      <pre className="language-hcl" style= data-line={1}>        <code>{`xxx`}</code>     </pre>  ...  

I get the following error:

Warning: Text content did not match. Server: "xxx   " Client: "xxx"  

So, if I'm understanding right: this is an error from Next.js, telling me that my server-rendered and client-rendered content are different?

Looking at the error message, it looks like the plugin is adding a newline at the end of the content, but only during the server-render, not the client-render.

Is this a bug with Prism.js, the line-highlight plugin or am I doing something wrong?

Is there a workaround I can do to get it going?

https://stackoverflow.com/questions/65527040/using-prism-js-line-highlight-plugin-with-next-js-app-causes-text-content-did-n January 01, 2021 at 11:04AM

没有评论:

发表评论