From e04af8a627ab8535995fa9cbcdd3933d7bb45b34 Mon Sep 17 00:00:00 2001 From: Tom MacWright Date: Thu, 17 Mar 2016 18:29:30 -0400 Subject: [PATCH] Use specific highlighters instead of including all of them. Halves the bundle size --- package.json | 2 +- src/components/section.js | 2 +- src/highlight.js | 39 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 src/highlight.js diff --git a/package.json b/package.json index adafd44..d0e6f0f 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ "eslint-plugin-babel": "^3.0.0", "eslint-plugin-react": "^3.14.0", "github-slugger": "^1.0.1", + "highlight.js": "^9.2.0", "isomorphic-fetch": "^2.2.0", "lodash.debounce": "^4.0.3", "minifyify": "^7.1.0", @@ -45,7 +46,6 @@ "react-dom": "^0.14.6", "react-pure-render": "^1.0.2", "remark": "^3.2.0", - "remark-highlight.js": "^2.0.0", "remark-html": "^2.0.2", "remark-slug": "^3.0.1", "unist-util-select": "^1.3.0", diff --git a/src/components/section.js b/src/components/section.js index b10c2c1..28c22b8 100644 --- a/src/components/section.js +++ b/src/components/section.js @@ -1,7 +1,7 @@ import React from 'react'; import remark from 'remark'; import remarkHTML from 'remark-html'; -import remarkHighlight from 'remark-highlight.js'; +import remarkHighlight from '../highlight'; import PureRenderMixin from 'react-pure-render/mixin'; import { postHighlight } from '../../custom'; diff --git a/src/highlight.js b/src/highlight.js new file mode 100644 index 0000000..f022aad --- /dev/null +++ b/src/highlight.js @@ -0,0 +1,39 @@ +import visit from 'unist-util-visit'; + +import hljs from 'highlight.js/lib/highlight'; +import python from 'highlight.js/lib/languages/python'; +import javascript from 'highlight.js/lib/languages/javascript'; +import json from 'highlight.js/lib/languages/json'; +import bash from 'highlight.js/lib/languages/bash'; + +hljs.registerLanguage('python', python); +hljs.registerLanguage('javascript', javascript); +hljs.registerLanguage('json', json); +hljs.registerLanguage('bash', bash); + +/** + * Adapted from remark-highlight.js + * https://github.com/ben-eb/remark-highlight.js + */ +export default function attacher() { + function visitor(node) { + if (!node.lang) { + return; + } + + let data = node.data; + + if (!data) { + node.data = data = {}; + } + + data.htmlContent = hljs.highlightAuto(node.value, [node.lang]).value; + data.htmlAttributes = data.htmlAttributes || {}; + data.htmlAttributes.class = [ + 'hljs', + data.htmlAttributes.class + ].filter(Boolean).join(' '); + } + + return ast => visit(ast, 'code', visitor); +}