Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

markdownit how to use highlight #8

Open
bookyo opened this issue Dec 31, 2018 · 13 comments
Open

markdownit how to use highlight #8

bookyo opened this issue Dec 31, 2018 · 13 comments

Comments

@bookyo
Copy link

bookyo commented Dec 31, 2018

i write markdown content.
after $md.render() :

<pre><code class="language-javascript">var a=123
console.log(2323)
println(2323)
</code></pre>

highlight is not work,.
my nuxt.config.js:

markdownit: {
    breaks: true,
    linkify: true,
    injected: true,
    langPrefix: "language-"
  },
This question is available on Nuxt community (#c142)
@ghost ghost closed this as completed Dec 31, 2018
@ghost
Copy link

ghost commented Dec 31, 2018

This issue as been imported as question since it does not respect modules issue template. Only bug reports and feature requests stays open to reduce maintainers workload.
If your issue is not a question, please mention the repo admin or moderator to change its type and it will be re-opened automatically.
Your question is available at https://cmty.app/nuxt/modules/issues/c142.

@mmintel
Copy link

mmintel commented Aug 16, 2019

@bookyo did you find a solution?

@fulopkovacs
Copy link

@bookyo @mmintel I got it working in 3 steps:

After installing markdownit (npm install @nuxtjs/markdownit):

// nuxt.config.js

export default {
    ....
    // 1.) add markdown-it to modules:
    modules: [
        '@nuxtjs/markdownit',
    ],
    css: [
        // 2.) use a style for syntax highlighting
        'highlight.js/styles/github.css'
    ]
    ....
    markdownit: {
      // 3.) use syntax highlighting:
      highlight: function(str, lang) {
        if (lang && hljs.getLanguage(lang)) {
          try {
            return hljs.highlight(lang, str).value
          } catch (__) {}                                                                                        
          return '' // use external default escaping
        }
      }
    },
    ...
}

You can use different styles, check out this list.

It's been working for me so far, so I hope it'll help you too! ☺️

That weird highlight method is from the official and original markdown-it docs by the way (https://github.com/markdown-it/markdown-it#syntax-highlighting).

@MoonCheung
Copy link

@fulopkovacs I follow the code method you provided and it still doesn't work. How can I solve the problem so that markdown-it can highlight the syntax

@frikishaan
Copy link

frikishaan commented Mar 14, 2020

@fulopkovacs I follow the code method you provided and it still doesn't work. How can I solve the problem so that markdown-it can highlight the syntax

You can try this, it works for me in nuxt.js

highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return '<pre class="hljs"><code>' +
               hljs.highlight(lang, str, true).value +
               '</code></pre>';
      } catch (__) {}
    }

    return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
  }

Reference - https://markdown-it.github.io/markdown-it/

@ChucKN0risK
Copy link

ChucKN0risK commented Mar 31, 2020

I also have issues making highlight.js work with @nuxt/markdown-it.

I want to display formatted code in my article pages whose content comes from an API.

I get the following error when my article page loads: hljs is not defined in _slug.vue.

nuxt.config.js:

const hljs = require('highlight.js');

module.exports = async () => {
  return {
    modules: [
      '@nuxtjs/markdownit',
    ],

    markdownit: {
      html: true,
      preset: 'default',
      linkify: true,
      breaks: true,
      injected: true,
      highlight: function (str, lang) {
        // ➡️ hljs is undefined here ⬅️ 😢
        if (lang && hljs.getLanguage(lang)) {
          try {
            return '<pre class="hljs"><code>' +
                   hljs.highlight(lang, str, true).value +
                   '</code></pre>';
          } catch (__) {}
        }
        return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
      }
    },
  }
}

_slug.vue:

<template>
  <div>
    <main-header />
    <main>
      <sp-section>
        <div
          v-html="articleContent"
        />
      </sp-section>
    </main>
  </div>
</template>

<script>
  import hljs from 'highlight.js';

  export default {
    async asyncData({ app, params }) {
      try {
        const [ article ] = await app.$axios.$get(`http://localhost:1337/articles/?slug=${params.slug}`);
        return {
          article,
        };
      } catch (err) {
        return false;
      }
    },
    computed: {
      articleContent() {
        return this.$md.render(this.article.content);
      },
    },
  };
</script>

@fulopkovacs
Copy link

@ChucKN0risK
Hmmm, are you sure that you need to import hls from highlight.js in _slug.vue? I took a quick glance at my repo, and I imported it only in nuxt.config.js. I'm still at work, but I'll look into the problem after I finished.

@ChucKN0risK
Copy link

@fulopkovacs No I'm not sure I should import it inside _slug.vue. I only tried because of the error I had telling me that hljs is undefined in _slug.vue 😉

@ChucKN0risK
Copy link

@fulopkovacs Did you have any chance of checking my issue? Thanks in advance ;)

@fulopkovacs
Copy link

@ChucKN0risK I did look into it, but couldn't find anything in my local setup. I am definitely not an expert (not event a front-end dev by now), but the only thing I can think of is that maybe the markdownit nuxt plugin is not able to display asynchronously fetched content, since it uses markdownit-loader for preprocessing markdown-files (= convert them to html) on the server side. If I were you I'd check out the markdown-it markdown parser (this is actually the library that the markdownit nuxt plugin uses for parsing md). It can be used with highlightjs, and loaded from a cdn if you want to use it in the browser.

Again, I'm not an expert, and I might be wrong about the markdownit nuxt plugin, but I'm pretty sure that the markdown-it library could help you. To be honest, I'm probably not be the best person to help, since I've never used nuxt in production. I found that Hugo fits my needs a lot better (I use it for my personal blog). Oh, and sorry for the late response, I looked at the problem on the day I first replied, but didn't want to get back to you empty-handed. Time itself could not solve this problem though... 😅

@ChucKN0risK
Copy link

@fulopkovacs Thanks for taking the time to answer me ;) I managed to directly use mardown-it inside my _slug.vue component like so:

export default {
  async asyncData({ app, params }) {
    try {
      const [ article ] = await app.$axios.$get(`http://localhost:1337/articles/?slug=${params.slug}`);
      const content = markdownit({
        html: true,
        preset: 'default',
        linkify: true,
        breaks: true,
        highlight: function (str, lang) {
          return `<pre class="hljs language-${lang}"><code class="language-${lang} ${lang}">${hljs.highlightAuto(str).value}</code></pre>`;
        }
      }).render(article.content);
      return {
        article,
        content,
      };
    } catch (err) {
      return false;
    }
  },
}

My content is fetched and rendered server side ;)

@iancleary
Copy link

I know this is closed, but in case anyone searches for it, I found Samuel Coe's article very useful 🎉

How to Use Markdown-It with Highlight.js in a Nuxt Project

@pi0 pi0 reopened this Sep 8, 2020
@pi0
Copy link
Member

pi0 commented Sep 8, 2020

(opened until adding to docs or built-in feature)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants