【本地是好的,线上环境报错系列】代码高亮,ChatGPT:这个问题我不会。

286 阅读3分钟

在React开发一个SQL显示功能时,本地开发可以正常高亮显示,但通过Vite打包部署之后,线上环境就没有高亮效果。我猜测是样式文件没有加载的问题,但不知道为什么? 这是正常现实的效果:

image.png

使用的组件是ReactMarkdownreact-syntax-highlighter

ChatGPT:这个我不会

然后我就去问ChatGPT了。 我把问题描述了一下,ChatGPT给出了一些解决方案和猜测。但通过它给的方式,我尝试了一下都没有得到解决。

原来ChatGPT也没有那么神,那我就放心了。

程序员本能

那么,当AI不能帮助我解决问题的时候,我第一个想法就是去官网查找问题出现的原因了。

通过访问react-syntax-highlighter的github页面,在readme中我发现了几个名词说明:

Prism

Using refractor we can use an ast built on languages from Prism.js instead of highlight.js. This is beneficial especially when highlighting jsx, a problem long unsolved by this module. The semantics of use are basically the same although a light mode is not yet supported (though is coming in the future). You can see a demo(with jsx) using Prism(refractor) .

import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { dark } from 'react-syntax-highlighter/dist/esm/styles/prism';
const Component = () => {
  const codeString = '(num) => num + 1';
  return (
    <SyntaxHighlighter language="javascript" style={dark}>
      {codeString}
    </SyntaxHighlighter>
  );
};

Light Build

React Syntax Highlighter used in the way described above can have a fairly large footprint. For those that desire more control over what exactly they need, there is an option to import a light build. If you choose to use this you will need to specifically import desired languages and register them using the registerLanguage export from the light build. There is also no default style provided.

import { Light as SyntaxHighlighter } from 'react-syntax-highlighter';

import docco from 'react-syntax-highlighter/dist/esm/styles/hljs/docco';

SyntaxHighlighter.registerLanguage('javascript', js);

我就将上述内容贴给了ChatGPT,让它帮我解释一下Prism和Light Build是什么意思。通过ChatGPT的问答,我知道了prism是一个全量打包的方式来加载样式文件,而light是一种轻量的方式,按需进行打包和加载的方式。如果你确定你的代码是固定的几种类型,就可以使用light的方式,然后注册相应的编程语言。使用prism是不需要注册编程语言的。

知道了这个之后再看我的代码:

import { Light as SyntaxHighlighter } from 'react-syntax-highlighter';
import {atomOneDark} from 'react-syntax-highlighter/dist/esm/styles/hljs';

我没有注册语言,但使用的是轻量打包方式,这就导致了在本地开发的时候,我可以正常显示,打包上线后却没有效果的原因。

因为我开发的功能是ai对话,会生成各种各样的开发语言的代码,这里我把Light方式改成了Prism方式,同时更换了主题:

import {Prism  as SyntaxHighlighter} from 'react-syntax-highlighter';
import { darcula } from 'react-syntax-highlighter/dist/esm/styles/prism';

重新打包部署之后,线上就显示正常了。

疑问

为什么使用light方式在本地高亮显示是正常的,线上就不行了呢?我的猜测,因为本地开发,对于加载网络资源的要求不是那么高,样式文件都会进行加载。但一旦打包部署上线后,每个样式文件都需要通过网络传输,当没有需求的样式文件被网络加载就会造成资源的浪费。

但我觉得react-syntax-highlighter插件可以做的再好一点,使用Light方式在本地开发的时候,需要强制要求注册开发语言,不注册就报错。这样对于问题的排查就更友好了。