reactjs - 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;
但是该网页没有突出显示语法。我在这里想念什么?
解决方案
如果您在从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.
推荐阅读
- unicode - 为什么这个 AutoHotKey 脚本偶尔不执行前 250 行?
- flutter - 退出应用时 Flutter 保存应用状态(登录首页后应用从登录页面启动)
- url - 是否可以参数化网络 [URL] 查询?
- html - 带链接的引导卡中同样高
- swift - 检查两个位置之间的距离(以 KM 为单位)
- python - 将熊猫系列标签拆分为python中新数据框的索引和列?
- java - java - 如何在Java Spring Boot中将一个对象映射到另一个对象
- json - 如何在父级别要求中引用子属性
- python - 如何独立运行 websockets
- html - 如何使用表单操作将数据从 HTML FORM 发送到 http 服务器?