Gatsby-замечание-Prismjs не работает на HTML - PullRequest
0 голосов
/ 05 марта 2019

gatsby -mark-prismjs не работает с моими настройками.

Я пытаюсь выделить такие коды, как javascript и swift.

Содержимое моего блога взято с wordpress.com

enter image description here

Вот мой gatsby.config.js

,
      {
        resolve: `gatsby-transformer-remark`,
        options: {
          plugins: [
            {
              resolve: `gatsby-remark-prismjs`,
              options: {
                // Class prefix for <pre> tags containing syntax highlighting;
                // defaults to 'language-' (eg <pre class="language-js">).
                // If your site loads Prism into the browser at runtime,
                // (eg for use with libraries like react-live),
                // you may use this to prevent Prism from re-processing syntax.
                // This is an uncommon use-case though;
                // If you're unsure, it's best to use the default value.
                classPrefix: "language-",
                // This is used to allow setting a language for inline code
                // (i.e. single backticks) by creating a separator.
                // This separator is a string and will do no white-space
                // stripping.
                // A suggested value for English speakers is the non-ascii
                // character '›'.
                inlineCodeMarker: null,
                // This lets you set up language aliases.  For example,
                // setting this to '{ sh: "bash" }' will let you use
                // the language "sh" which will highlight using the
                // bash highlighter.
                aliases: {},
                // This toggles the display of line numbers alongside the code.
                // To use it, add the following line in src/layouts/index.js
                // right after importing the prism color scheme:
                //  `require("prismjs/plugins/line-numbers/prism-line-numbers.css");`
                // Defaults to false.
                showLineNumbers: false,
                // If setting this to true, the parser won't handle and highlight inline
                // code used in markdown i.e. single backtick code like `this`.
                noInlineHighlight: false,
              },
            },
            ],
          },
      },

gatsby.browser.js

require("prismjs/themes/prism-okaidia.css")

А это index.js

import React, { Component } from 'react'
import { Link } from 'gatsby'
import Layout from "../layouts"
import Headline from '../components/headline'
import "../styles/main.scss"
import { redirectTo } from '@reach/router'
import { graphql } from 'gatsby'

class IndexPage extends Component {
  render() {
    const data = this.props.data.wordpressPage
    var codeTest = `
      var _self = (typeof window !== 'undefined')
    ? window   // if in browser
    : (
      (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope)
      ? self // if in worker
      : {}   // if in node js
    );
    `
    var swift = `
      let test = "hellow"
      func test() -> Bool {
        return false
      }
    `
    return (
      <Layout>
      <Headline title={"I'm Shawn Baek"} subTitle={"iOS Developer"}/>
      <div
         style={{
           margin: '0 auto',
           maxWidth: 800,
           padding: '0px 1.0875rem 1.45rem',
           paddingTop: '1.45rem',
         }}
      >
      <div>
          <h1 style={{color:'rgb(76, 76, 76)'}}>{data.title}</h1>
          <div style={{color:'rgb(76, 76, 76)'}} dangerouslySetInnerHTML={{ __html: data.content }}></div>
      </div>
      <pre className="javascript">
          <code >
              {codeTest}
          
      
{} быстрое)}}экспорт const IndexPageQuery = graphql`query IndexPageQuery {wordpressPage (slug: {eq: "about"}) {заглавиесодержаниеdate (formatString: "ММММ ДД, ГГГГ")}}`экспорт по умолчанию IndexPage

1 Ответ

0 голосов
/ 05 марта 2019

gatsby-remark-whatever плагины специально предназначены для парсера Markdown Markdown, gatsby-transformer-remark.

Однако при использовании Gatsby + WordPress ваш контент поступает из WordPress, а не из файлов Markdown.,Это означает, что ваш WordPress-контент не изменяется этими плагинами, и, хотя вы потенциально можете это сделать, это, вероятно, не самый простой способ решения проблемы.

То же самое относится и к вашему тесту: эта строкапример кода не будет проходить через процесс Markdown в Gatsbty, поэтому плагин Markdown PrismJS не окажет никакого влияния.

Если вы используете плагин WordPress, который добавляет синтаксис, выделяет HTML, который вам нужен на стороне сервера в PHP, этодолжны быть переданы через WordPress REST API.

Затем вы можете вручную добавить нужные вам настройки CSS и темы (вроде как вы могли бы, если бы создавали интерфейс обычной темы WordPress.)

Кроме того, вы можете использовать Prism.js так же, как и в другом проекте React.Я думаю, что Как заставить PrismJS работать в React , учебник поможет вам больше всего.

Аналогичный пример, основанный на вашем коде, после запуска npm install prismjs:

// Import the PrismJS CSS, contained in the node_modules
// You might need to download a custom theme to support 
// some languages like Swift
import "prismjs/themes/prism.css";

import React, { Component } from "react";
import Prism from "prismjs";

class IndexPage extends Component {
  componentDidMount() {
    Prism.highlightAll();
  }

  render() {
    var sampleCode = `.example {
  font-weight: bold;
}`;

    return (
      <div>
        <pre>
          <code className="language-css">{sampleCode}
        
);}} экспорт по умолчанию IndexPage;

Если вы не используете какие-либо другие страницы Markdown, вы можете решить npm uninstall gatsby-remark-* плагинов и удалить их конфигурацию.Надеюсь, это полезно!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...