Why are semicolons omitted in all my source js files? - javascript

I'm starting a web project in Aptana and have downloaded bootstrap (v 3.3.7) and jQuery (compressed). When I imported the files into my js folder, all the files came up with a warning sign and the only warnings I can see are that there are missing semicolons everywhere. I think I've read that semicolons aren't necessary in js (although it's best practice to use them), but I've downloaded these files before for class and didn't receive this warning.
Have I done something wrong? Are these files OK to work with?

Are these files OK to work with?
Yes, missing semicolons in most (but not all) places can be corrected by the JavaScript parser using the error-correction procedure* called Automatic Semicolon Insertion, which is built into the language specification. So leaving them out in the places ASI will fix for you is indeed allowed. But it's important to know ASI's rules if you're doing that. (And important to know the rules for ; in any case.) The Bootstrap team knows the rules. (jQuery uses explicit semicolons.)
It sounds like you just have a lint-style warning enabled that you didn't have enabled before that flags up missing semicolons even in places ASI will fix.
You could disable the warning by searching in the options for "lint" or "code style" or "code quality" options, finding the relevant option, and turning it off, but I wouldn't. Instead, I'd look for how to exempt libraries from lint/code style/code quality analysis, since the source of every library you use is unlikely to fit your overall coding style rules.
* According to the language's original creator, Brendan Eich:
ASI is (formally speaking) a syntactic error correction procedure. If you start to code as if it were a universal significant-newline rule, you will get into trouble.
(Amusingly, he also said he wishes he'd made newlines more significant originally, rather than less. But as he said, that ship sailed in 1995...)

Related

How to analyze JavaScript and CSS coverage across multiple pages/sites

The Chrome Dev Tools JavaScript and CSS Coverage Drawer is pretty neat, except for one thing... It would be nice if it could be left on, and not reinitiate its analysis between pages.
I would like to be able to analyze an entire site, a subset of pages, or a set of websites, and find what is unused amongst them.
I get that it would mean browsing entire projects and using every feature (or setting up tests) to be thorough/precise, but that's not as tedious as what I have to do entirely without such a utility/feature. (And it doesn't seem like you would need to be meticulous to obtain usable or initial observations from a sub-thorough audit. The DevTools utility doesn't facilitate automated tests on its own either.)
The codebase at issue is huge (1.9mb uncompressed on the front end), and (possibly) contributed to by many developers who may or may not have left relics, legacy code, or abandoned dependencies. There is possibly also code that is only relevant in parts of projects, which could reveal opportunities for reducing dependency scope.
Is there a way to begin to crack into code use without a laborious manual deep dive?
It was one of the first things that came to mind when learned about the Google's coverage utility, and I assumed it would be capable of analyzing multiple pages collectively, but it doesn't.
Is there anything else that does this? Does any utility exist that can search an entire site or multiple pages and find unused JS and CSS?
Side note: The CSS is in SASS. For that and other reasons I may need to manually analyze the results and improve the code, which is trivial comparatively, so I'm not looking for a feature to automate code improvements. It's a similar situation with the JS which is minified.
This is not a request for a recommendation on poduct/software. It is asking if task X is possible, which is technically answerable with a yes or no.
UPDATE: It does seem like there are utilities for CSS, but still nothing found for JS.
For Static Analysis:
Try unusedcss.com to analyse unused CSS code across the entire website. More - Helium CSS
Try deadfile which is a simple util to find deadcode and unused files in any JavaScript project.
For Dead-code Removal:
Try purgecss to remove unused CSS code from your project.
Try Google's closure compiler which parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left.
That being said, detecting unused code is a hard problem to solve, because there are countless ways to invoke a given piece of code. Hence, these tools wisely and with your best judgement.

Monaco: What is the best way to create a language syntax definition for a custom language in the monaco-editor?

I have a fairly simple custom DSL created in antlr4. I'm trying to find the easiest way to use it in a web based monaco-editor with all the bells and whistles.
I see you can create monarch definitions from scratch using: https://microsoft.github.io/monaco-editor/monarch.html
(The problem with that is for future changes I'd have to keep 2 things up to date, the antlr grammar and the monarch json definition. Also, since they are separate implementations, how could I be certain they both match/agree).
I also see you can manually use an ANTLR generated lexer/parser to do everything yourself with just ANTLR: https://tomassetti.me/writing-a-browser-based-editor-using-monaco-and-antlr/
(Compared to monarch, this seems like a LOT of manual work, and I'm having trouble finding many examples of this or much documentation).
Is there an easy way to just generate the monarch json definition from the antlr files? If no, which of the first 2 options is generally preferred and why?
An ANTLR file is really just your syntax. It would probably be possible to get syntax highlighting from there, but I don’t recall seeing anything that does that for Monaco.
Beyond syntax highlighting, you’ll want code completion. If you target the Typescript target, then there’s the C3 code completion project that Mike Lischke (hope I spelled that right) put together. It gets you about as close as you can get I from just the grammar, but you still have work to do looking things up in you symbol table, taking scope into account. Etc. it’s also tricky to hand it the right logical cursor position (Mike has written up good guidance on getting it right (it made a lot more sense to me when I reread it after working through it though).
It can be made to work with the JavaScript target, but that’s a bit more work. (Mainly in adding to methods the type script target has that the JavaScript target does not.
Also, it’s not going to just plug in to Monaco. It will save you a lot of work when you write your code though.

How to make jslint less verbose

My "IDE" of choice (it's not a real IDE) is Sublime Text 2.
There are nice plugins for this editor. One that I enjoy using a lot is SublimeClang: It parses your C/C++ code as you write it and shows you where errors and warnings are, just like a "real" IDE. This is fantastic because it cuts out the code/compilation cycle so I only ever need to go back to my terminal once I have my code already written because I can see my errors as I am working on the code.
I had hoped that jsLint (there are plugins for integrating this with the editor as well) would help accomplish the same task for me so that I can spot syntax errors before I test my page in the browser. Oftentimes the best way to do this involves uploading the entire file to the server and loading it up in the browser: While this workflow can be heavily streamlined already there is a lot of appeal to being able to locally check the code before uploading.
The problem I have with jslint is that it throws out way too many opinions about esoteric stylistic choices, many of which I do not care for. You want me to put all my declarations together in one line? No thank you, I have all of these comments here next to the variables, I'm keeping those comments!
Are there flags I can provide to jslint so that it will only warn me about syntax errors?
Many people feel the same way you do about JSLint. One result is the alternative JSHint. Many people find its defaults more to their liking. There are Sublime plugins for it too. Two of them are listed at http://www.jshint.com/platforms/.
JSLint does have several options to change its behavior.
It looks like you can define these in the sublime-jslint.sublime-settings file included with the plugin you linked to (in the "jslint_options" section).

Unused css - how do you clean it up?

Probably any experienced web developer would be familiar with this problem: over time your css files can grow pretty huge and ugly because of all the no longer used selectors, which might be pretty tricky to find. I'm working on a rails project where we tend to re-design things quite frequently, which leads to a tonne of deadweight css. What's the best way to find and remove it?
Now, I do know that there is a rails plugin called deadweight built specifically for that purpose. However, here's my problem with deadweight: first of all, it completely ignores selectors used in javascript. Next, it scans only those pages that you configure it to scan which means there's a risk of removing something that is used on pages that you didn't scan for some reason. Finally, it finds unused selectors only in compiled css (we use LESS) - matching these against the actual code is a bit too involved.
I have also tried http://unused-css.com/ - they're great, but can't access localhost and, again, can only scan compiled CSS.
I really think there must be a better way of doing this. Actually, some time ago I decided to optimise one particular css file by grepping each selector in the entire project directory (emacs + rinari mode make it super-easy and super-fast), and each time I didn't see any html or css in the results I removed the style. Zero problems, worked like a charm. Obviously, I'm not going to do that for the entire site. However, I really don't believe that this couldn't be automated. Now, before I fire up my python and code this up, can anyone actually tell me if I'd be reinventing the wheel?
Check out uCSS library from Opera Software.
It helps you to find unused CSS, as well as duplicate CSS. Also, you can get an overview of how many times each rule has been used in your markup. Several options are available by setting up a config file.
Update:
Another great alternative: csscss.
Written in Ruby and supports SASS, Less.
Update:
Another great alternative: uncss.
It works across multiple files and supports Javascript-injected CSS.
Dust Me Selecters and/or CSS Usage Firefox extensions can help you weed out unused CSS.
In Chrome's Developer Tools you can use the Web Page Performance tool to find unused CSS rules.

Should I use JSLint or JSHint JavaScript validation? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am currently validating my JavaScript against JSLint and making progress on, it's assisting me to write better JavaScript - in particular in working with the Jquery library.
I have now come across JSHint, a fork of JSLint.
So I am wondering for web applications, which are very much JavaScript was driven, which is the better or most applicable validation tool to work against:
JSLint or JSHint?
I want to decide now on a validation mechanism and moving forward, use this for client side validation.
And Difference between jshint and jslint? Please explain in single javascript example.
Links:
jshint- http://www.jshint.com/
jslint- http://jslint.com/
TL;DR
Use JSLint if you're looking for a very high standard for yourself or your team, but bear in mind that it's not necessarily the standard, only a standard, some of which comes to us dogmatically from Doug Crockford.
If you want to be a bit more flexible or have some old pros on your team that don't buy into JSLint's opinions or are going back and forth between JavaScript and other C-family languages regularly, try JSHint.
Full version
Two articles with the reasoning behind the fork explain why JSHint exists:
JSHint: A Community-Driven Fork Of JSLint
Why I forked JSLint to JSHint
The idea behind JSLint is that it's community-driven rather than Crockford-driven. JSHint is generally more lenient (or at least configurable or agnostic) on a few stylistic and minor syntactical opinions that JSLint is a stickler for.
For example, if you think both 1. and 2. below are fine, or if you want to write code with one or more of 1.'s aspects that aren't available in 2., JSHint is for you. If you think 2. is the only correct option, use JSLint. I'm sure there are other differences, but this highlights a few.
Passes JSHint out of the box - fails JSLint
(function() {
"use strict";
var x=0, y=2;
function add(val1, val2){
return val1 + val2;
}
var z;
for (var i=0; i<2; i++){
z = add(y, x+i);
}
})();
Passes Both JSHint and JSLint
(function () {
"use strict";
var x = 0, y = 2, i, z;
function add(val1, val2) {
return val1 + val2;
}
for (i = 0; i < 2; i += 1) {
z = add(y, x + i);
}
}());
I find the JSLint code more visually appealing. The only features of it that I disagree with are its hatred of more than one var declaration in a function and of for-loop var i = 0 declarations, and some of the whitespace enforcements for function declarations.
A few of the whitespace things that JSLint enforces are not necessarily bad but are just out of sync with some pretty standard whitespace conventions for other languages in the family (C, Java, Python, etc.) often followed as conventions in Javascript as well. Since I'm writing in various of these languages throughout the day and working with team members who don't like Lint-style whitespace in our code, I find JSHint to be a good balance. It catches legitimate bugs and very badly formed code, but doesn't bark at me like JSLint does (sometimes, in ways I can't disable) for the stylistic opinions or syntactic nitpicks that I don't care for.
A lot of good libraries aren't Lint'able, which to me demonstrates that there's some truth to the idea that some of JSLint is just about pushing one version of "good code" (which is, indeed, good code). But then again, the same libraries (or other good ones) probably aren't Hint'able either, so, touché.
[EDIT]
This answer has been edited. I'm leaving the original answer below for context (otherwise the comments wouldn't make sense).
When this question was originally asked, JSLint was the main linting tool for JavaScript. JSHint was a new fork of JSLint, but had not yet diverged much from the original.
Since then, JSLint has remained pretty much static, while JSHint has changed a great deal - it has thrown away many of JSLint's more antagonistic rules, has added a whole load of new rules, and has generally become more flexible. Also, another tool ESLint is now available, which is even more flexible and has more rule options.
In my original answer, I said that you should not force yourself to stick to JSLint's rules; as long as you understood why it was throwing a warning, you could make a judgement for yourself about whether to change the code to resolve the warning or not.
With the ultra-strict ruleset of JSLint from 2011, this was reasonable advice -- I've seen very few JavaScript codesets that could pass a JSLint test. However with the more pragmatic rules available in today's JSHint and ESLint tools, it is a much more realistic proposition to try to get your code passing through them with zero warnings.
There may still occasionally be cases where a linter will complain about something that you've done intentionally -- for example, you know that you should always use === but just this one time you have a good reason to use ==. But even then, with ESLint you have the option to specify eslint-disable around the line in question so you can still have a passing lint test with zero warnings, with the rest of your code obeying the rule. (just don't do that kind of thing too often!)
[ORIGINAL ANSWER FOLLOWS]
By all means use JSLint. But don't get hung up on the results and on fixing everything that it warns about. It will help you improve your code, and it will help you find potential bugs, but not everything that JSLint complains about turns out to be a real problem, so don't feel like you have to complete the process with zero warnings.
Pretty much any Javascript code with any significant length or complexity will produce warnings in JSLint, no matter how well written it is. If you don't believe me, try running some popular libraries like JQuery through it.
Some JSLint warnings are more valuable than others: learn which ones to watch out for, and which ones are less important. Every warning should be considered, but don't feel obliged to fix your code to clear any given warning; it's perfectly okay to look at the code and decide you're happy with it; there are times when things that JSlint doesn't like are actually the right thing to do.
There is an another mature and actively developed "player" on the javascript linting front - ESLint:
ESLint is a tool for identifying and reporting on patterns found in
ECMAScript/JavaScript code. In many ways, it is similar to JSLint and
JSHint with a few exceptions:
ESLint uses Esprima for JavaScript parsing.
ESLint uses an AST to evaluate patterns in code.
ESLint is completely pluggable, every
single rule is a plugin and you can add more at runtime.
What really matters here is that it is extendable via custom plugins/rules. There are already multiple plugins written for different purposes. Among others, there are:
eslint-plugin-angular (enforces some of the guidelines from John Papa's Angular Style Guide)
eslint-plugin-jasmine
eslint-plugin-backbone
And, of course, you can use your build tool of choice to run ESLint:
grunt-eslint
gulp-eslint
I had the same question a couple of weeks ago and was evaluating both JSLint and JSHint.
Contrary to the answers in this question, my conclusion was not:
By all means use JSLint.
Or:
If you're looking for a very high standard for yourself or team, JSLint.
As you can configure almost the same rules in JSHint as in JSLint. So I would argue that there's not much difference in the rules you could achieve.
So the reasons to choose one over another are more political than technical.
We've finally decided to go with JSHint because of the following reasons:
Seems to be more configurable that JSLint.
Looks definitely more community-driven rather than one-man-show (no matter how cool The Man is).
JSHint matched our code style OOTB better that JSLint.
I'd make a third suggestion, Google Closure Compiler (and also the Closure Linter). You can try it out online here.
The Closure Compiler is a tool for making JavaScript download and run faster. It is a true compiler for JavaScript. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls.
Foreword: Well, that escalated quickly. But decided to pull it through. May this answer be helpful to you and other readers.
Code Hinting
While JSLint and JSHint are good tools to use, over the years I've come to appreciate what my friend #ugly_syntax calls:
smaller design space.
This is a general principle, much like a "zen monk", limiting the choices one has to make, one can be more productive and creative.
Therefore my current favourite zero-config JS code style:
StandardJS.
UPDATE:
Flow has improved a lot. With it, you
can add types to your JS with will help you prevent a lot
of bugs. But it can also stay out of your way, for instance
when interfacing untyped JS. Give it a try!
Quickstart / TL;DR
Add standard as a dependency to you project
npm install --save standard
Then in package.json, add the following test script:
"scripts": {
"test": "node_modules/.bin/standard && echo put further tests here"
},
For snazzier output while developing, npm install --global snazzy and run it instead of npm test.
Note: Type checking versus Heuristics
My friend when mentioning design space referred to Elm and I encourage you to give that language a try.
Why? JS is in fact inspired by LISP, which is a special class of languages, which happens to be untyped. Language such as Elm or Purescript are typed functional programming languages.
Type restrict your freedom in order for the compiler to be able to check and guide you when you end up violation the language or your own program's rules; regardless of the size (LOC) of your program.
We recently had a junior colleague implement a reactive interface twice: once in Elm, once in React; have a look to get some idea of what I'm talking about.
Compare Main.elm (typed) ⇔ index.js (untyped, no tests)
(ps. note that the React code is not idiomatic and could be improved)
One final remark,
the reality is that JS is untyped. Who am I to suggest typed programming to you?
See, with JS we are in a different domain: freed from types, we can easily express things that are hard or impossible to give a proper type (which can certainly be an advantage).
But without types there is little to keep our programs in check, so we are forced to introduce tests and (to a lesser extend) code styles.
I recommend you look at LISP (e.g. ClojureScript) for inspiration and invest in testing your codes. Read The way of the substack to get an idea.
Peace.
Well, Instead of doing manual lint settings we can include all the lint settings at the top of our JS file itself e.g.
Declare all the global var in that file like:
/*global require,dojo,dojoConfig,alert */
Declare all the lint settings like:
/*jslint browser:true,sloppy:true,nomen:true,unparam:true,plusplus:true,indent:4 */
Hope this will help you :)
There is also an another actively developed alternative - JSCS — JavaScript Code Style:
JSCS is a code style linter for programmatically enforcing your style
guide. You can configure JSCS for your project in detail using over
150 validation rules, including presets from popular style guides like
jQuery, Airbnb, Google, and more.
It comes with multiple presets that you can choose from by simply specifying the preset in the .jscsrc configuration file and customize it - override, enable or disable any rules:
{
"preset": "jquery",
"requireCurlyBraces": null
}
There are also plugins and extensions built for popular editors.
Also see:
Perfect code, zero effort

Categories