首页 > 解决方案 > PrismJS babel 配置在 React 中不起作用

问题描述

我安装了 babel-plugin-prismjs,使用以下代码制作了 .babelrc:

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

并将 Prism 导入 App.js。

这是 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;

但是该网页没有突出显示语法。我在这里想念什么?

标签: reactjsprismjs

解决方案


如果您在从create-react-app(CRA) 构建的 react 项目中使用它,您的代码将无法正常工作。你的 .babelrc 文件没有被使用。CRA 不公开 babel 配置。检查此答案以了解更多信息。

对于您的用例,最简单的方法是转到 prismjs 页面下载 CSS 文件。选择正确的主题,然后单击页面底部的“下载 CSS”。

在您的 App.js 代码中导入此 CSS 文件。

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.


推荐阅读