【问题标题】:PrismJS babel config not working in ReactPrismJS babel 配置在 React 中不起作用
【发布时间】:2021-05-14 01:40:30
【问题描述】:

我已经安装了 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;

但网页没有突出显示语法。我在这里错过了什么?

【问题讨论】:

    标签: reactjs prismjs


    【解决方案1】:

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

    对于您的用例,最简单的方法是go to prismjs page to download the CSS file。选择正确的主题,然后点击页面底部的“下载 CSS”。

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

    import '../prism.css';
    

    这适用于 Javascript 和其他一些内置语言包。如果您的语言没有显示正确的标记,您还需要手动导入这些语言。

    注意:这只是一种不退出 CRA 项目的解决方法。如果可以的话,推荐的方式还是使用 babel-plugin-prismjs。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 1970-01-01
      • 2021-07-06
      • 1970-01-01
      • 1970-01-01
      • 2018-01-05
      相关资源
      最近更新 更多