Technology Blogs by SAP
Learn how to extend and personalize SAP applications. Follow the SAP technology blog for insights into SAP BTP, ABAP, SAP Analytics Cloud, SAP HANA, and more.
cancel
Showing results for 
Search instead for 
Did you mean: 
marco_voelz
Employee
Employee

Introduction


JavaScript is a dynamically typed language and has many pitfalls. Therefore, static code checks are of great use - for beginners as well as for experienced developers. Literature is full of advice how to do things right and what to avoid (see Douglas Crockford: JavaScript: The Good Parts, David Flanagan: JavaScript: The Definitive Guide, Marijn Haverbeke: Eloquent JavaScript Second Edition). Fortunately, there are various tools available for checking your code automatically. Recently, JSHint has become the most popular because of its flexibility and integration into editors and toolsets.

Ideally, static code checks should be done at two levels:

  • During build time to ensure that the build breaks if your code contains errors, flaws, or some of the "bad parts" (as Douglas Crockford puts it)
  • During development while you type so you don't get frustrated by a build failing 10 times in a row because of trailing whitespace
  • Those two checks should be in sync to avoid double maintenance

This article is part of a series of articles about Test-Driven Development and JavaScript in which also the second topic will be covered in depth. Press 'like' on the overview blog post to stay tuned and get updates about more topics around software engineering with SAPUI5 and JavaScript!

Scope of this article


This article assumes you are building your project with maven and use Eclipse to write your JavaScript. If your backend is implemented in Java, maven is one of the most popular ways to manage your dependencies and automate your build. However, checking your code as you type in Eclipse is completely independent of your build process. JSHint can be integrated into other build processes as well (e.g. using Grunt).

Why JSHint?


JSHint started out as a fork of the very opinionated JSLint. One of its main advantages is that it is configurable via an external configuration file called .jshintrc. Furthermore, it offers a better configurability than JSLint, i.e. you can decide which checks are important for your project. It can be integrated easily into many editors such as Eclipse, WebStorm/IntelliJ, and Sublime as well as build tools such as maven and grunt.

Live Checks in Eclipse as you type


Go to the Eclipse marketplace via Help --> Marketplace and search for 'JSHint' and install the plugin jshint-eclipse. Create a .jshintrc file in the root folder of your project. A detailed explanation of JSHint configuration options can be found at the JSHint Options Reference. Here is the configuration file we use in our project as some starting point:


{
    "bitwise" : true,
    "camelcase" : false,
    "curly" : true,
    "eqeqeq" : true,
    "es3" : true,
    "forin" : true,
    "immed" : true,
    "latedef" : "nofunc",
    "newcap" : true,
    "noarg" : true,
    "noempty" : true,
    "nonew" : true,
    "plusplus" : false,
    "quotmark" : false,
    "undef" : true,
    "unused" : "vars",
    "strict" : false,
    "trailing" : true,
    "maxlen" : false,
    "laxbreak" : true,
    "globals" : {
        "window" : false,
        "document" : false,
        "jQuery" : false,
        "sap" : false,
        "cockpit" : false,
        "URI" : false,
        "getCurrentAccount" : false,
        "setTimeout" : false
    }
}






To enable checks in Eclipse go to Window --> Preferences --> JSHint --> Configuration and import the .jshintrc file in your project root.

Now right click on your project in the project explorer, choose properties --> JSHint and enable checks for all files you like. In our project, we don't check test files at the moment, so we have a check for all *.js files in src/main/js and all subdirectories. Save your changes.

Now it is time to see if JSHint works! Add a new file in src/main/js and paste the following code


function thisIsNeverUsed(){
if (1 == 0)
  console.log(" 1 is never equal 0")
  switch (something) {
  case 1:
   console.log("it is 1");
  default:
   break;
  }
return true;
var somethingElse = 3;
}






After saving the file you should end up with a nice set of JSHint errors, similar to mine.

Keep the file in your project and resist the urge of correcting the mistakes - we'll need it in the next section! :wink:

Integrating JSHint checks into your maven build


While integration into Eclipse is something which really helps you during development, there is only one way to ensure that certain error don't make it into the codebase: The build must fail. With maven, you can use the jshint-maven-plugin (formerly called jshint-mojo) to use the same .jshintrc file for checking your javascript code during the build. Copy the following to the <plugins> section of your pom.xml


<plugin>
<groupId>com.cj.jshintmojo</groupId>
<artifactId>jshint-maven-plugin</artifactId>
<version>1.3.0</version>
<executions>
  <execution>
   <goals>
    <goal>lint</goal>
   </goals>
  </execution>
</executions>
<configuration>
  <directories>
   <directory>src/main/js</directory>
  </directories>
  <failOnError>true</failOnError>
  <reportFile>${project.build.directory}/jslint.xml</reportFile>
  <reporter>jslint</reporter>
  <!-- assuming that the .jshintrc file is on the same level as the pom.xml -->
  <configFile>.jshintrc</configFile>
</configuration>
</plugin>






Try to build your project with mvn clean verify and it should fail with the same errors which you saw in Eclipse.

Disabling plugin execution during Eclipse builds

As of now, you have two JSHint checks configured: One by an Eclipse plugin, another one in your pom.xml. The maven integration of Eclipse, called m2eclipse, tries to interpret everything in your pom.xml and act accordingly. However, you don't need to do the same checks twice, so you should disable the execution of the jshint-maven-plugin during an Eclipse build. Paste the following snippet into the pluginManagement section of your pom.xml


<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
  <lifecycleMappingMetadata>
   <pluginExecutions>
    <pluginExecution>
     <pluginExecutionFilter>
      <groupId>com.cj.jshintmojo</groupId>
      <artifactId>jshint-maven-plugin</artifactId>
      <versionRange>[1.3,)</versionRange>
      <goals>
       <goal>lint</goal>
      </goals>
     </pluginExecutionFilter>
     <action>
      <ignore />
     </action>
    </pluginExecution>
   </pluginExecutions>
  </lifecycleMappingMetadata>
</configuration>
</plugin>



Interpreting JSHint Output

If you're unsure how to interpret JSHint's output, this might be a good resource for you: JSLint Error Explanations - Making Your Feelings Better

Conclusion


In this article, I described how you can use a combination of JSHint, the JSHint Eclipse plugin, and jshint-maven-plugin

  • to have live static code checks in Eclipse while you write JavaScript code
  • to have your build fail when someone tries to commit code that JSHint doesn't like

Now it's your turn: Write some clean code!

This article is part of a series of articles about Test-Driven Development and JavaScript in which also the second topic will be covered in depth. Press 'like' on the overview blog post to stay tuned and get updates about more topics around software engineering with SAPUI5 and JavaScript!

2 Comments