Skip to main content

Lint your Oracle JET code with ESLint


Javascript has grown so much in just past 5-6 years, it's quite unbelievable. More customers wants to build their front-end using one or the other JavaScript framework.
But, this massive growth also comes with some drawbacks, one of them is code quality and lack of proper standards. Even though each team has their own standards, often they get lost when development timelines gets a bit stringent.
I come from a Java world, so these coding guidelines/standards gets by default applied by a Java compiler or an IDE. (which we also conveniently ignore most of the time).

This is where ESLint comes in. A very easy to use and very well documented tool to impose standards and coding guidelines to your JavaScript project.

What is Linting?

Lint was the name originally given to a particular program that flagged some suspicious and non-portable constructs (likely to be bugs) in C language source code. The term is now applied generically to tools that flag suspicious usage in software written in any computer language.
- Source Wikipedia

Why lint your JavaScript?

Since there are no real compiler associated with Javascript and also not all IDEs provide this support, it is, I believe, mandatory to run lint on your JavaScript code.
Otherwise, most likely you end up with a project where its code looks like a house built by a child using nothing but a hatchet and a picture of a house, which might also have a huge impact on whether your code functionally.
Linting your code is also useful for finding certain classes of bugs, such as those related to variable scope. Assignment to undeclared variables (these leak into the global scope, contaminating it and possibly causing very difficult to find bugs) and use of undefined variables are examples of errors that are detectable at lint time.

Oracle JET and ESLint

Oracle JET doesn't provide out-of-the-box linting features. But ESLint is highly pluggable and easy to use. 
There are couple of Github projects on this already available and ready to use.

You will also find a blog on how to implement it here.

But being new to this JavaScript world, I found it hard to follow and use. So below is a simplified, step-by-step version on how to configure and use ESLint on your Oracle JET project. 

Github Link

All of below steps are added to a demo github project for you to download and see and use in your own project. Here is the link to it : https://github.com/sohamda/Linting-OracleJET

Prerequisites

  1. Oracle JET version 5 or above.
  2. OJET-CLI is installed.
  3. Your Oracle JET project is properly created and initialized.
  4. Install ESLint CLI : npm i -g eslint

Step #1: Install Dependencies

Inorder to use ESLint in Oracle JET, you need to installed a few dependencies. Make sure you install these are your "dev" dependencies, because they are of no use in your production release module.

npm install --save-dev eslint grunt-eslint

In above, along with "eslint", I also installed "grunt-eslint", because later in this blog I will show 2 ways to configure the linting task to your JET build, one of them is to attach it to your grunt build and for that we need this dependency.

Step#2: Initialize .eslintrc.js

Once dependencies are installed, we need to initialize a linting rule file. This is basically your project's coding standards and guidelines. ESLint documentation is quite extensive in this regard and provide an excellent guide on how to write this file.

What I did:
  1. Created a folder inside "./scripts" folder, named "linter".
  2. Ran this command from command line : eslint --init
The above command will ask you a series of question inorder to initialize your basic rulebook for your coding styles. 


 
I choose to use a popular style-guide, which is Airbnb and choose to have my config file as JavaScript.
The above will generate a ".eslintrc.js" file inside your linter directory.

Step#3: Define your coding standards 

Now the stage is set to define your own guidelines and standards which you want to follow in your Oracle JET project. This is where the Github projects (Oracle and Enpit) I have mentioned earlier comes handy. They have some pre-defined rules specified and is a very good starting point for you.
I have created a bit of my own version, combining both, which is below, but you are free to define yours.



The Github project link of my demo project is at the beginning, you can refer to that to copy this setting.

Step#4: Attach this to your build

The last step to all of this is to attach this to your build process, so that it never gets ignored and everyone makes a serious effort to follow the standards always.
I will mention 2 ways to attach this to your project's build process, one in the scaffold "Gruntfile.js" and another one in the "before_build.js" hook provided by JET. You can follow either but not both, I personally prefer #1 simply because it is easy to see and faster than using build hook.

1. In Gruntfile.js:
To enable eslint to your build, you need to update the scaffold "Gruntfile.js" .

Initialize Grunt to point to your ".eslintrc.js" and which ".js" files needs to be linted.
grunt.initConfig({
    eslint: {
        options: {
            configFile: 'scripts/linter/.eslintrc.js',
        },
        target: ['src/js/*.js', 'src/js/viewModels/*.js']
    }
});


Then register a task
grunt.registerTask('default', ['eslint']);

Then call this task from existing "build" task. And your "Gruntfile.js" should look like below.



To run/use this, you just need to use one of the below commands :
  1. grunt
  2. grunt eslint
  3. grunt build
  4. grunt build:release
As you can see, "serve" is out of the linting scope, most of the time for me is to make sure my logic works then actually implementing coding standards. But it is combined to "build", and will fail this if linting has errors.
Running this will result into something like below:



2. In before_build.js hook:
Oracle JET provides a few build hooks by default, they can located inside "scripts/hooks/", and are the best place to put custom tasks/code if you are using "ojet-cli" for your builds. This technique also very useful in reporting, you can log the results of linting.
I am using "colors" package to log the linting results, this is just for beautification, if you want you can ignore this.
First I initialize the CLIEngine object.
var CLIEngine = require("eslint").CLIEngine;

Then provide the .eslintrc.js file to it.
var cli = new CLIEngine({
    configFile : 'scripts/linter/.eslintrc.js'
});

Then run it on my .js files.
var report = cli.executeOnFiles(['src/js/*.js', 'src/js/viewModels/*.js']);

Then I log this report to a log file.
const fs = require('fs');
fs.writeFile('liniting.log', JSON.stringify(report, null, 4), function (err) {
    if (err) throw err;
    if(report.errorCount > 0) {
        console.log(colors.red("Linting errors found: " + report.errorCount));
    } else {
        console.log(colors.green("Linting errors found: " + report.errorCount));
    }
});

Finally your before_build.js should look like below:

You can read further about ESLint NodeJS APIs here.

To run/use this, you just need to use one of the below commands :
  1. ojet build
  2. ojet build --release
  3. ojet serve
When you run this, you should result something like below. 
But be informed, this will not stop the build process if there are linting errors, which is one of the major difference with my previous approach, but this produces a "liniting.log" in your project root directory with all linting results.





Comments

Post a Comment

Popular posts from this blog

Rich Text Editor - Oracle JET

Oracle JET has a lot of excellent UI components, but according to Murphy's law, client always comes up with something which you don't have at your disposal. So, driven by one of my client's requirements, I created a Rich Text Editor or WYSIWYG editor for Oracle JET. This is based on Quill JS and fully customizable. Github project download: https://github.com/sohamda/JET-Web-Components/tree/master/rich-text-editor I will explain in this blog, on how to integrate it in your own Oracle JET project. 1. Create and initialize your JET application and then put the downloaded web component inside "src\js\jet-composites" folder. 2. Once copied update your viewModel first. Add a snippet for passing the default content to be displayed by the editor after load. 3. Update view to load this editor Above you can see the "toolbar-options" property, that controls which options you should display to user on the editor. Those are basically the forma

Create Micro CRUD services for Oracle Database Cloud using NodeJS

I will try to explain, how you can use NodeJS to create mirco services for the tables in your Oracle Database Cloud or on-premise Database. Complete Github project : https://github.com/sohamda/LeasifyAPIs You need to do "npm install" to download the node_modules. Step by Step guide : 1. NodeJS : either 32 or 64 bit. If you already have NodeJS installed, please check whether it is 64 or 32. Use below command to figure that out : C:\>node > require('os').arch() If you get : 'ia32' , then it is 32 bit installation. 2. Install oracle-db node module .  This was a lengthy and time consuming installation for me, because for Windows, it has a lot of pre-requisites. If you are a Mac user, you are lucky. :) I followed : https://community.oracle.com/docs/DOC-931127 There is also a detailed one in github : https://github.com/oracle/node-oracledb/blob/master/INSTALL.md 3. Config your DB Cloud Create a user and couple of tables on which we'

Layout Management & CSS Classes with Oracle JET

Oracle JET provides automatic responsive layout using CSS classes. So that, from large screens to small screens the application fits itself the best possible way. JET’s layout management are based on 2 types of CSS classes “Responsive Grid” and “Flex”. Responsive grid classes which deals with size, number of columns and functions of a particular <div>. Naming convention of these classes are oj- size - function - columns sizes can be: sm, md, lg, xl functions can be: hide, only-hide columns can be: any number between 1 to 12.   Just like Bootstrap, JET also divides the width of the available space into 12 columns, so for example, if you want a section of your page should take up atleast 5 columns if you divide the available screen into 12 columns, you need use : oj- size -5. Now comes the size part, you need to define that for each size of the screen, from hand-held mobile devices to large or extra large desktop screens. With combination with theses grid c