Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

prismjs - 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={{marginTop: "1em"}}>
      <code>{`xxx`}</code>
   </pre>
 </div>
}

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

When I add the data-line attribute to the HTML, as following.

pages/blog-article.tsx
...
    <pre className="language-hcl" style={{marginTop: "1em"}} 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.

Note that other Prism plugins seem to work; I tried out the line-numbers plugin and it didn't cause this problem.

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...