I have a project of 100+ javascript files each with 1-5 missing semicolons according to JSHint (as a result multiple people working on the project with different conventions).
I'd like to bulk fix everything as it's not practical to fix each individually. I've found this: https://github.com/jshint/fixmyjs but I don't see a way only fix semicolons without 'fixing' other things (tabs -> spaces, for example).
Does anyone know of way to do this? I'm comfortable with the possibility that it might cause breakage/introduce bugs. I've look over the errors and they look pretty routine.
JavaScript does not require semicolons (other than the one exception you saw earlier). This is because JavaScript is clever and it can add the semicolons where needed automatically. This happens behind the scenes and you will not notice it. This process is called Automatic Semicolon Insertion (ASI).
Semicolons are an essential part of JavaScript code. They are read and used by the compiler to distinguish between separate statements so that statements do not leak into other parts of the code.
Since Typescript is a strict superset of JavaScript, semicolon insertion applies to Typescript as well. This means that in most cases, semicolons are not required.
I really hope you like this as a solution. Be vary careful that you verify with jshint again after you've fixed the issues. And out of curiosity, how did you manage to get so many broken javascript files?
#!/bin/sh
function fixFile {
for i in `jshint $1 | grep -i "Missing semicolon" \
| sed -e 's/\([^0-9]*\)\([0-9]*\)\(.*$\)/\2/'`;
do
sed -i $1 -e $i's/\(\s*\)$/;/'
done
}
fixFile $1
The above uses jshint to produce some error lines, greps them for the missing semicolon errors only, extracts the line number of each error, then seds the file in place on that line to remove any trailing whitespace and replace it with a semicolon.
The file...
var a = 5, c = 4
function helloWorld() {
if (this == doesntmakesense)
console.log('hello' + 'world');
}
console.log(a+c);
console.log('finished')
...becomes...
var a = 5, c = 4;
function helloWorld() {
if (this == doesntmakesense)
console.log('hello' + 'world');
}
console.log(a+c);
console.log('finished');
Where petty semantic errors are ignored, and only semicolons treated.
I'd save the bash script as something like fixFile.sh
and then run find . -name "*.js" -exec ./fixFile.sh {} \;
But please commit beforehand. All commands are run at your own risk ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With