Sunday, September 22, 2019

Static code analysis and source code complexity tool - Plato for Typescript

I was looking for a tool which can report code complexity for an Angular application. The application is written in Typescript and there are hardly any tools for it.

The first place to look was Wikipedia : https://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis#JavaScript which has some tools for Javascript but none for Typescript.

Looking across the web : https://www.npmjs.com/search?q=keywords:complexity , I came across tools like Plato and Complexity Report based on EsComplex. I was quickly drawn to Plato for it nice graphical reports.

npm install -g plato

Still the problem was how to make Plato run on TypeScript. Yes there were people asking for it on the web but no answers.

Now I knew all the TS code of my angular application is compiled and put into main.js. So I applied Plato on the file directly. First thing I hit was a memory constraint put by node that it can use a maximum memory of around 1.5GB. So had to increase it using:

node --max_old_space_size=4096 ./node_modules/es6-plato/bin/plato -r -d report -e .eslintrc.json -t "MyApp" -x .json dist\MyApp\main.js.

It worked but resultant report was so big that beyond the basic summary, navigating it was causing browser to error out. Looking into it in notepad++, I found that it a lot of Angular internal code around Webpack and then a small amount of the application code.

So had to work out a better solution. Need to compile the individual TS files in to JS file and run plato only on them.

Luckily we have a tsc compiler for TS which will output the JS and then can run plato on it.
So first install:

npm install -g typescript

Now we can run the build task from VS Code directly using CTRL+SHIFT+B i.e. Run Build Task and select tsc:build

This will execute the command:

node_modules\.bin\tsc.cmd -p tsconfig.json

Depending on your tsconfig.json, your output will normally be at :

"outDir": "./dist/out-tsc",

Now when I look at ./dist/out-tsc/src/app, I see all by TS files compiled and resulting in to JS and JS.MAP files.

Now I can run plato and it does not even hit the 1.5 GB memory as it has smaller files to look into :

plato -r -d report -e .eslintrc.json -t "MyApp" -x .json dist/out-tsc/src

and see some wonderful results:



No comments: