Search code examples
angulartypescriptcodemirror

Cannot get CodeMirror linting and JSHINT to work in Angular 2 application


Trying to get CodeMirror linting to work in my Angular 2 application. The CodeMirror editor is working grand (line numbers, syntax highlighting, themes etc.) but for some reason I cannot get linting to work. Please note I am using CodeMirror mode: 'application/json' and that is why it requires a javascript linter.

Here is what I have:

app.component.html

<codemirror class="action-type-details-code-mirror" [(ngModel)]="code" [config]="config" name="codeEdit"></codemirror>

app.component.ts

import { Component } from '@angular/core'
import { CodemirrorComponent } from 'ng2-codemirror';
import 'codemirror/mode/javascript/javascript';
import 'codemirror/addon/lint/lint';
import 'codemirror/addon/lint/javascript-lint';
import { JSHINT } from 'jshint';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./styles.less']
})

export class AppComponent {

code = `<p>My HTML</p>\n<!-- hello -->\n<p>Your HTML</p>`

constructor() {
  this.config = {
  lineNumbers: true,
  mode: 'application/json',
  gutters: ['CodeMirror-lint-markers'],
  theme: 'neo',
  lint: true
  };   
}

package.json

"devDependencies": {
  "@types/codemirror": "0.0.40"
},
"dependencies": {
  "jshint": "^2.9.5",
  "codemirror": "^5.26.0",
  "ng2-codemirror": "^1.1.2",
}

app.module.ts

imports: [
    /* ... */
    CodemirrorModule,
],

styles.less

@import "~codemirror/theme/neo.css";
@import "~codemirror/lib/codemirror.css";
@import "~codemirror/addon/lint/lint.css";

For some reason the linting feature doesn't work on the CodeMirror editor. I have debugged the application and have narrowed the issue down to the loading of JSHint. I think the problem is that JSHint isn't available on the window. Is there a way to import JSHint and make it available on the window?

Any help would be greatly appreciated.

Many thanks


Solution

  • I was having the exact same issue with linting in "javascript" mode. I kept getting the error:

    "Error: window.JSHINT not defined, CodeMirror JavaScript linting cannot run."

    This other stackoverflow answer resolved it for me:

    Codemirror lint feature not working react-codemirror in React/Redux/Typescript App

    Adding (<any>window).JSHINT = JSHINT; below your imports should do the trick.