highlight_highlight.js在vue项目中的基本用法

简介

  • highlight.js是一个将代码html, 即通过<pre>标签包裹的<code>标签内的代码字符串文本赋予样式的插件;

安装

  • npm i highlight.js -S
    

使用

在vue项目中的使用

  1. main.js文件中引入highlight.js主文件以及你想要适配的文本格式(比如js, css, html等), 以及所对应的文本样式

    1. 引入主文件

      1. import hljs from 'highlight.js/lib/core'
        
    2. 引入需要适配的文本格式, 我这里引入并注册javascript, css, json, html, scss五种代码格式

      1. import javascript from 'highlight.js/lib/languages/javascript'
        import json from 'highlight.js/lib/languages/json'
        import html from 'highlight.js/lib/languages/vbscript-html'
        import css from 'highlight.js/lib/languages/css'
        import scss from 'highlight.js/lib/languages/scss'
        hljs.registerLanguage('javascript', javascript)
        hljs.registerLanguage('json', json)
        hljs.registerLanguage('html', html)
        hljs.registerLanguage('css', css)
        hljs.registerLanguage('scss', scss)
        
    3. 引入想要使用的样式文件, 以an-old-hope为例

      1. import 'highlight.js/styles/an-old-hope.css'
        
    4. 全局注册hljs变量

      1. app.config.globalProperties.hljs = hljs
        
  2. 在你需要使用的组件/页面中引入全局变量hljs, 并直接调用highlightAll()方法

    1. // ArticleContent.vue
      // some code ...
      nextTick(() => {
        proxy.hljs.highlightAll()
      })
      
    2. 实现的效果如下所示

      1. image-20230918001823765
      2. 它将组件/页面中的通过<pre>包裹的<code>的文本全部高亮了

附录

获取可选的样式文件

  • highlight.js/styles/目录下选择想要的样式是相当繁琐的, 这里给出一段代码提供快速获取可选样式以及查看代码样式

快速获取可选样式

  • 通过nodejs来读取该目录, 并将目录文件全部筛选出来

  • 在项目根目录下创建一个server.js文件, 写入以下代码, 注意hightlight.js/styles/的地址是否与项目中的地址匹配

  • const { opendir, appendFile } = require('fs/promises')
    const { resolve } = require('path')
    async function getStyle () {
      try {
        const dir = await opendir(resolve(__dirname, './node_modules/highlight.js/styles'))
        // console.log(dir)
        for await (const dirent of dir) {
          console.log(dirent)
          await appendFile(resolve(__dirname, './cssname.txt'), "'" + dirent.name + "'" + ',')
        }
      } catch (err) {
        console.log(err)
      }
    }
    getStyle()
    
  • 上面的代码会在根目录下创建一个cssname.txt文件

  • 复制生成的文本, 保存在下面代码的styleArr变量中

    • <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="UTF-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          <title>Document</title>
          <link rel="stylesheet" href="/node_modules/highlight.js/styles/default.css" />
          <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/highlight.min.js"></script>
          <script>
            hljs.highlightAll()
          </script>
        </head>
        <body>
          <div id="content">
            <div id="cnblogs_post_body" class="blogpost-body cnblogs-markdown">
              <h3 id="安装">安装</h3>
              <pre><code>npm install --save-dev http-proxy-middleware
      </code></pre>
              <h3 id="代理中间件配置">代理中间件配置</h3>
              <p><code>createProxyMiddleware([context,] config)</code></p>
              <pre><code class="language-js">const { createProxyMiddleware } = require('http-proxy-middleware');
      const apiProxy = createProxyMiddleware('/api', { target: 'http://www.example.org' });
      //                                    \____/   \_____________________________/
      //                                      |                    |
      //                                    context             options
      
      // 'apiProxy' is now ready to be used as middleware in a server.
      </code></pre>
              <ul>
                <li>createProxyMiddleware([代理路径],{target:[目标路径]})</li>
                <li>context:确定应将哪些请求代理到目标主机。</li>
                <li>options.target: 要代理到的目标主机。(协议+主机)</li>
              </ul>
              <h3 id="示例">示例</h3>
              <pre><code class="language-js">// include dependencies
      const express = require('express');
      const { createProxyMiddleware } = require('http-proxy-middleware');
      
      // proxy middleware options
      /** @type {import('http-proxy-middleware/dist/types').Options} */
      const options = {
      target: 'http://www.example.org', // target host
      changeOrigin: true, // needed for virtual hosted sites
      ws: true, // proxy websockets
      pathRewrite: {
      '^/api/old-path': '/api/new-path', // rewrite path
      '^/api/remove/path': '/path', // remove base path
      },
      router: {
      // when request.headers.host == 'dev.localhost:3000',
      // override target 'http://www.example.org' to 'http://localhost:8000'
      'dev.localhost:3000': 'http://localhost:8000',
      },
      };
      
      // create the proxy (without context)
      const exampleProxy = createProxyMiddleware(options);
      
      // mount `exampleProxy` in web server
      const app = express();
      app.use('/api', exampleProxy);
      app.listen(3000);
      </code></pre>
            </div>
          </div>
          <div id="changeStyleSelect"></div>
          <div id="changeStyle"></div>
          <script>
            const oPostBody = document.querySelector('#cnblogs_post_body')
            const html = oPostBody.innerHTML
            styleArr = [
              'a11y-dark.css',
              'a11y-light.css',
              'agate.css',
              'an-old-hope.css',
              'androidstudio.css',
              'arduino-light.css',
              'arta.css',
              'ascetic.css',
              'atom-one-dark-reasonable.css',
              'atom-one-dark.css',
              'atom-one-light.css',
              'base16',
              'brown-paper.css',
              'brown-papersq.png',
              'codepen-embed.css',
              'color-brewer.css',
              'dark.css',
              'default.css',
              'devibeans.css',
              'docco.css',
              'far.css',
              'felipec.css',
              'foundation.css',
              'github-dark-dimmed.css',
              'github-dark.css',
              'github.css',
              'gml.css',
              'googlecode.css',
              'gradient-dark.css',
              'gradient-light.css',
              'grayscale.css',
              'hybrid.css',
              'idea.css',
              'intellij-light.css',
              'ir-black.css',
              'isbl-editor-dark.css',
              'isbl-editor-light.css',
              'kimbie-dark.css',
              'kimbie-light.css',
              'lightfair.css',
              'lioshi.css',
              'magula.css',
              'mono-blue.css',
              'monokai-sublime.css',
              'monokai.css',
              'night-owl.css',
              'nnfx-dark.css',
              'nnfx-light.css',
              'nord.css',
              'obsidian.css',
              'panda-syntax-dark.css',
              'panda-syntax-light.css',
              'paraiso-dark.css',
              'paraiso-light.css',
              'pojoaque.css',
              'pojoaque.jpg',
              'purebasic.css',
              'qtcreator-dark.css',
              'qtcreator-light.css',
              'rainbow.css',
              'routeros.css',
              'school-book.css',
              'shades-of-purple.css',
              'srcery.css',
              'stackoverflow-dark.css',
              'stackoverflow-light.css',
              'sunburst.css',
              'tokyo-night-dark.css',
              'tokyo-night-light.css',
              'tomorrow-night-blue.css',
              'tomorrow-night-bright.css',
              'vs.css',
              'vs2015.css',
              'xcode.css',
              'xt256.css',
            ]
      
            selectHtml = []
            selectHtml.push('<select id="changeStyle">')
            for (i in styleArr) {
              OptionValue = styleArr[i]
              selectHtml.push('<option value="' + OptionValue + '" >' + OptionValue + '</option>')
            }
            selectHtml.push('</select>')
            selectHtmlString = selectHtml.join('')
            document.getElementById('changeStyleSelect').innerHTML = selectHtmlString
      
            obj = document.getElementById('changeStyle')
            obj.addEventListener('change', function (event) {
              var value = this.options[this.options.selectedIndex].value
              l = document.createElement('link')
              l.setAttribute('href', '/node_modules/highlight.js/styles/' + value)
              l.setAttribute('rel', 'stylesheet')
              document.head.appendChild(l)
            })
          </script>
        </body>
      </html>
      
    • 通过live-server来启动这一html文件, 就可以选择并查看自己喜欢的样式了.

posted @ 2023-09-18 00:50  Syinho  阅读(941)  评论(0编辑  收藏  举报