How to syntax-highlight HTML inside JavaScript strings in Sublime

Viewed 3949

Is there any Sublime package to syntax-highlight HTML inside JavaScript strings?

(Note the question is only about HTML inside JS strings, not syntax highlighting in general.)

Specifically I am writing Angular components using inline templates

angular.module('compMod', []).component('myComp', {
    template: `<div>Some Text</div>`
});

and looking to highlight HTML syntax inside the ES6 template strings.

2 Answers

As @Calvin commented above, I wouldn't say this is a good practice, yet I wouldn't necessarily say it's entirely bad one. Anyways, here's my naive solution (haven't tested it for any edge cases):

Install babel package for sublime text and choose it as the default syntax for your your *.js files.

Next, edit JavaScript (Babel).sublime-syntax, which is located inside the Babel package directory, e.g. ~/.config/sublime-text-3/Packages/Babel/.

Search for the section template-string-body:, and add at its beginning the following two lines, similar to @VRPF's suggestion:

- meta_content_scope: text.html.basic.embedded.js
- include: scope:text.html.basic

Now you have a full support in es6 + HTML syntax within template-strings.

I would just create a new syntax highlighter as you dont have to worry if they update the normal packages.

Go to Tools > Developer > New Syntax...

%YAML 1.2
---
# See http://www.sublimetext.com/docs/3/syntax.html
name: Javascript HTML
file_extensions:
  - element.js
  - tag.js
  - jsx
  - js
scope: source.js.tag
contexts:
  main:
    - match: ""
      push: Packages/JavaScript/JavaScript.sublime-syntax
      with_prototype:
      - match: '([a-zA-Z$_][\w$_]*)?(`)'
        push:
          - meta_content_scope: text.html.basic.embedded.js
          - include: 'scope:text.html.basic'
          - match: '`'
            pop: true
          - match: '\$\{'
            captures:
              0: punctuation.definition.template-expression.begin.js
            push:
              - meta_scope: meta.template.expression.js
              - include: 'scope:source.js'
              #- meta_content_scope: source.js.embedded.expression
              - match: '\}'
                scope: punctuation.definition.template-expression.end.js
                pop: true

Then save as JavascriptHTML.sublime-syntax

Restart Sublime then you can go to View > Syntax > Open all with this ext as > Javascript HTML

Related