简体   繁体   English

如何在 Svelte 组件中运行 Prismjs?

[英]How do I run Prismjs in a Svelte component?

I'm simply trying to implement Prismjs into my Svelte project.我只是想在我的 Svelte 项目中实现 Prismjs。

I'm loading the CSS in my <head> and I'm importing the JS in my Svelte component.我在我的<head>中加载 CSS 并且我在我的 Svelte 组件中导入 JS。

I'm running into a similar issue described here: https://medium.com/get-it-working/get-prismjs-working-in-react-a6d989e59290我遇到了这里描述的类似问题: https://medium.com/get-it-working/get-prismjs-working-in-react-a6d989e59290

Basically, it seems I need to re-run the script after the component has rendered.基本上,似乎我需要在组件渲染后重新运行脚本。 I'm trying to accomplish this in the same way as it's described in React in the article by running Prism.highlightAll() inside of the onMount lifecycle.我试图通过在onMount生命周期内运行Prism.highlightAll()以与文章中 React 中描述的相同方式完成此操作。

I was hoping this approach would work, but I'm not getting anywhere.我希望这种方法能奏效,但我一无所获。 I still have to refresh the page to see the styles take effect.还是要刷新页面才能看到styles生效。 What am I missing here?我在这里想念什么?

tldr; tldr; this wasn't a Svelte issue.这不是 Svelte 问题。 It was an issue with my serializer for Sanity's blocks-to-html utility.这是我的 Sanity 的blocks-to-html实用程序的序列化程序的问题。

Hi @RichHarris, Upon putting together a repo for reproduction.嗨@RichHarris,在将一个回购放在一起进行复制时。 I found prism worked as expected.我发现棱镜按预期工作。 I was then able to narrow down my issue.然后我能够缩小我的问题。

I should have mentioned initially, I'm using Sapper and pulling in content from Sanity.我一开始就应该提到,我正在使用 Sapper 并从 Sanity 中提取内容。 I made a modification to the serializer for Sanity's block-content-to-html utility that is converting my portable text to markup.我对 Sanity 的block-content-to-html实用程序的序列化程序进行了修改,该实用程序将我的可移植文本转换为标记。 The <pre> tag is getting data-language='HTML' from Sanity, and the Prism CSS is expecting class="language-HTML . I modified my serializer to: <pre>标签正在从 Sanity 获取data-language='HTML' ,而 Prism CSS 期待class="language-HTML 。我将序列化程序修改为:

code: ({node}) => 
    h(
        "pre", 
        {
            "data-language": node.language, "class": "language-" + node.language
        }, 
        h("code", {}, node.code)
    )

Which was working after refreshing.刷新后工作。 The class attribute was getting added, and the CSS applied.正在添加 class 属性,并应用了 CSS。 I'm just sort of thumbing through the code as I don't really know how blocksToHtml works, but upon changing the object property to className , everything is working as expected:我只是在浏览代码,因为我真的不知道blocksToHtml是如何工作的,但是在将 object 属性更改为className后,一切都按预期工作:

code: ({node}) => 
    h(
        "pre", 
        {
            "data-language": node.language, className: "language-" + node.language
        }, 
        h("code", {}, node.code)
    )

Thanks for taking a look, Rich!谢谢你看,里奇! I'm really enjoying Svelte!我真的很喜欢 Svelte!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM