How to do JSLint in Vim - javascript

I spend my days in vim, currently writing a lot of JavaScript. I've been trying to find a way to integrate JSLint or something similar into vim to improve my coding. Has anyone managed to do something like this?
I tried this: Javascript Syntax Checking From Vim, unfortunately the output is very crude.

The best-practice way IMO is:
Install Syntastic Vim plugin - Best syntax-checker around for plenty of languages, plus it integrates with Vim's location-list (==quickfix) window.
I recommend cloning from the GitHub repo and installing using a plugin manager like Vundle or Pathogen, since it's more frequently updated.
Choose one of the two options below:
JSLint
Install jsl (JSLint executable) using your favorite package manager (Ubuntu's apt-get, Mac's home brew, etc.).
Community-driven jshint.com (better than JSLint)
Install node.js using your favorite package manager.
Install Node Package Manager: 'curl https://npmjs.org/install.sh | sh' EDIT: npm IS PART OF node.js NOW
See http://npmjs.org for more info.
Install jshint globally: 'npm install jshint -g'
Put your jshint config file in your $HOME dir: '~/.jshintrc'
Here's JSHint-Node's example configuration file, they pulled from mine and added more stuff.
Here's my original copy, which you can also start from.
Overwrite Syntastic's syntax_checkers/javascript.vim file with this one - EDIT: NO LONGER NECESSARY WITH NEWEST SYNTASTIC VERSION.
Script copied from FactorayLab's really helpful Vim GitHub page, which I recommend every Vim user to check out.
Enjoy! :)

You can follow the intructions from JSLint web-service + VIM integration or do what I did:
Download http://jslint.webvm.net/mylintrun.js and http://www.jslint.com/fulljslint.js
and put them in a directory of your choice.
Then add the following line to the beginning of mylintrun.js:
var filename= arguments[0];
and change last line of code in mylintrun.js ("print( ...)") to:
print ( filename + ":" + (obj["line"] + 1) + ":" + (obj["character"] + 1) + ":" + obj["reason"] );
This makes in mylintrun.js output a error list that can be used with the VIM quickfix window (:copen).
Now set the following in VIM:
set makeprg=cat\ %\ \\\|\ /my/path/to/js\ /my/path/to/mylintrun.js\ %
set errorformat=%f:%l:%c:%m
where you have to change /my/path/to/js to the path to SpiderMonkey and /my/path/to/mylintrun.js to the path where you put the JS files.
Now, you can use :make in VIM and use the quickfix window (:he quickfix-window) to jump from error to error.

Another option is jslint.vim from Jesse Hallet. It's available on GitHub and works with or without Vim's QuickFix window. It's a nice plugin!

I've been very happy using node-lint
sudo npm -g install jslint
Then whack this somewhere in your .vim
set makeprg=jslint\ %
set errorformat=%-P%f,
\%E%>\ #%n\ %m,%Z%.%#Line\ %l\\,\ Pos\ %c,
\%-G%f\ is\ OK.,%-Q
Now a :make will run jslint. Errors appear in the quickfix window.

Here are the Mac OS instructions updated for Nov. 2012. Assumes you have Homebrew installed in order to get Node.js, and that you've already installed Syntastic for Vim (I use https://github.com/carlhuda/janus which provides this automatically):
$ brew install node.js
$ npm install -g jshint
Then add '/usr/local/share/npm/bin' to your PATH (probably in ~/.bashrc). For example, add the line:
export PATH="$PATH:/usr/local/share/npm/bin"
restart your Terminal and check that
$ jshint
is executable from the command line. Syntastic will discover jsHint automatically. Restart MacVim and enjoy!

Much better is to pipe the results through Lynx to deal with JSLint's unfortunate choice of HTML for output format. I have a blog post on how to do it here:
http://www.fleegix.org/articles/2008-09-06-jslint-in-vim-through-lynx

Related

How to check what is included in NPM package

I installed this package: npm install #mediapipe/camera_utils
I would like to know how to find the contents of a package.
A good trick I've found is to use the website npmfs.com instead of npmjs.com (just replace "s" with "f" in a package url).
Here're the contents of that particular package (per each version)
and here're the contents of camera_utils.js from the latest version:
(function(){/*
Copyright The Closure Library Authors.
SPDX-License-Identifier: Apache-2.0
*/
'use strict';var e="function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){if(a==Array.prototype||a==Object.prototype)return a;a[b]=c.value;return a};function f(a){a=["object"==typeof globalThis&&globalThis,a,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var b=0;b<a.length;++b){var c=a[b];if(c&&c.Math==Math)return c}throw Error("Cannot find global object");}var h=f(this);
function k(a,b){if(b)a:{var c=h;a=a.split(".");for(var d=0;d<a.length-1;d++){var g=a[d];if(!(g in c))break a;c=c[g]}a=a[a.length-1];d=c[a];b=b(d);b!=d&&null!=b&&e(c,a,{configurable:!0,writable:!0,value:b})}}var l="function"==typeof Object.assign?Object.assign:function(a,b){for(var c=1;c<arguments.length;c++){var d=arguments[c];if(d)for(var g in d)Object.prototype.hasOwnProperty.call(d,g)&&(a[g]=d[g])}return a};k("Object.assign",function(a){return a||l});var m=this||self;var n={facingMode:"user",width:640,height:480};function p(a,b){this.video=a;this.h=0;this.g=Object.assign(Object.assign({},n),b)}function q(a){window.requestAnimationFrame(function(){r(a)})}function t(a,b){a.video.srcObject=b;a.video.onloadedmetadata=function(){a.video.play();q(a)}}function r(a){var b=null;a.video.paused||a.video.currentTime===a.h||(a.h=a.video.currentTime,b=a.g.onFrame());b?b.then(function(){q(a)}):q(a)}
p.prototype.start=function(){var a=this;navigator.mediaDevices&&navigator.mediaDevices.getUserMedia||alert("No navigator.mediaDevices.getUserMedia exists.");var b=this.g;return navigator.mediaDevices.getUserMedia({video:{facingMode:b.facingMode,width:b.width,height:b.height}}).then(function(c){t(a,c)}).catch(function(c){console.error("Failed to acquire camera feed: "+c);alert("Failed to acquire camera feed: "+c);throw c;})};var u=["Camera"],v=m;
u[0]in v||"undefined"==typeof v.execScript||v.execScript("var "+u[0]);for(var w;u.length&&(w=u.shift());)u.length||void 0===p?v[w]&&v[w]!==Object.prototype[w]?v=v[w]:v=v[w]={}:v[w]=p;}).call(this);
Note: NPM is actually adding this feature natively through the Explore tab but it's currently in beta.
First of all the best way to check will be npm
website itself from where you are
downloading this plugin.
During the installation itself you can check by command npm install -ddd
If you are willing to know more what all package content you need to
go to node_modules folder, find the package name which you are
looking for. Inside that folder you can find its own
pacakge.json file which includes all of its dependencies.

Building Chart.js master - generated .js gives errors

I am getting an error when I work with a version of Chart.js master that I compiled myself. I must be missing some kind of dependency that I've missed in the documentation. I have no clue what .js I need to include.
When I move my mouse-cursor over the chart I get a bunch of errors related to a missing Color library. Which one am I missing exactly?
TypeError: i.color(...).saturate is not a function
Edit:
I have created a JSFiddle here: http://jsfiddle.net/o9ebb5sq/
This piece of code does not show the problem (using Chart 2.0.0-Beta). This is why I copied this release into my software and tried again. The problem I am describing disappears.
I am running a master build (created using 'gulp build') Which makes me think the problem is either present in git master, or it is caused by my build environment.
I have installed the following npm packages before I ran gulp build
gulp 3.9.0
gulp-concat 2.6.0
gulp-connect 2.2.0
gulp-html-validator 0.0.5
gulp-jshint 1.12.0
gulp-karma 0.0.5
gulp-replace 0.5.4
gulp-size 2.0.0
gulp-uglify 1.4.2
gulp-util 3.0.7
semver 5.0.3
karma 0.13.14
inquirer 0.11.0
I expect that maybe I am missing something here or that one of the packages I've used to build Chart.js has an issue.
In the package.json on 2.0 they have included a new dependency "color": "git://github.com/chartjs/color" you will also need to include this. Odd thing is they alias this to a helper
color = helpers.color = function(color) {
if (!window.Color) {
console.log('Color.js not found!');
return color;
}
return window.Color(color);
},
So I would have expected for you to see the log unless you already have something in the global namespace named Color.

Node Build System in Sublime Text 2 for the First Time

I have read this post on an error with node in Sublime Text 2, this post on finding where node was installed, and this post on what seems to be the same issue, but none of them have helped so far. I would also prefer to use node.js. Please bear in mind, I am a programming newbie, so descriptions of locations of directories will have be absolute path names in order for me to understand.
I followed the instructions here, and my Node.sublime-build file looks like this:
{
"cmd": ["node", "$file", "$file_base_name"],
"working_dir": "${project_path:${folder}}",
"selector": "*.js"
}
I restarted Sublime Text 2, but it didn't work. I restarted my computer, but to no avail.
Currently, /usr/local/bin is where node is stored, and my $PATH contains that directory. At least, I think. My $PATH (I am in a bash_profile) looks like this:
-bash: /Users/David/.rvm/gems/ruby-2.0.0-p353/bin:/Users/David/.rvm/gems/ruby-2.0.0-p353#global/bin:/Users/David/.rvm/rubies/ruby-2.0.0-p353/bin:/Users/David/.rvm/bin:/usr/local/heroku/bin:/Users/David/.rbenv/shims:/Users/David/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin: No such file or directory
I think the solution may be found in the line in the Sublime Text 2 console error messages that reads,
[path: /usr/bin:/bin:/usr/sbin:/sbin]
Do I need to insert /usr/local/bin: into it? If so, how? I am running Mac OS X 10.7.5. Even if there's another thread that I haven't found, I'd gladly forgo reputation points in order to get the solution to my problem.
Cheers!
There are three options for getting your build systems to work.
First, you can edit your Node.sublime-build file to look like this:
{
"cmd": ["/usr/local/bin/node", "$file", "$file_base_name"],
"working_dir": "${project_path:${folder}}",
"selector": "*.js"
}
by adding /usr/local/bin/ to the beginning of the node command to give its fully qualified path.
Alternatively, since you're on Lion (this doesn't work on Mt Lion), you can alter the path for Dock-launched programs (by default it's /usr/bin:/bin:/usr/sbin:/sbin, as you've seen). From Terminal, run the following:
launchctl setenv PATH $PATH
(you may have to prefix it with sudo, I'm not sure). The, run:
osascript -e 'tell app "Dock" to quit'
and restart Sublime. This has the advantage of allowing other build systems (I'm especially thinking of Ruby, since you're using RVM) to work out of the box, without messing around with their .sublime-build files as well. For this and the next option, you'll need to remember to update the path when you update Ruby.
The third option, which is necessary on Mountain Lion (not sure about Mavericks) is outlined in my answer here. Basically, you need to edit /etc/launchd.conf (or create it if it doesn't exist) to define PATH, then save and reboot. This is necessary because the launchctl command on 10.8 doesn't do what we want it to do. This option may also work on Lion, but I haven't tested it, since I had already upgraded to Mt Lion before I developed it.
I hope this all helps. Good luck!

Transforming TypeScript into JavaScript

I'm wondering how is it possible to transform the TypeScript into JavaScript in a cross platform manner. I'm aware about availability of node package manager for typescript, but are there any other alternatives which can be used on the server side?
The TypeScript compiler is built in TypeScript, and hence is available as a JS file (tsc.js) that can be run using just about any ES3-compiliant VM or JS implementation.
That said, the compiler's current file I/O infrastructure only supports Node and Windows Scripting Host file APIs. If you'd like to recommend for support for another environment, feel free to reach out to the team at our GitHub site (Formerly CodePlex)
Short version: use Node if you can. It's becoming unavoidable nowadays.
Maybe it's not the answer you want, but as everybody mentioned, the compiler is a JS file, so, your options are the options of executing a JS file.
In Windows, there are 2 obvious ones, Node, and Windows Script Host.
You know about node already, the other option is a component that comes with all versions of Windows (I think), you can do it like this:
cscript path/to/tsc.js source-file.ts
You can see all compiler options by just:
cscript path/to/tsc.js
On Linux I assume you should be able to use (in addition to node):
V8 standalone shell, replace node or cscript with v8-shell
ExecJS https://github.com/sstephenson/execjs
Any other JS runner available on the selected platform (another answer mentioned Rhino for example)
Update: Another answer suggests the compiler API is only compatible with node and Windows Script Host (cscript tool), so, if correct, then on Linux you'll need Node to compile TypeScript.
If you are looking for something like apt get tsc (or whatever the Linux/Mac package managers are like), I think there isn't.
I remember reading somewhere that the I/O is optimized for Node and Windows Script Host, so, if you have problems with options, you'll probably end up with Node if seeking platform independence.
Update: Another answer here confirms the same about compatibility.
Concretely, on the server (assuming your server has Node.js available), you'd simply run:
node path/to/tsc.js yourFile1.ts yourFile2.ts [etc]
You can run that command without any input filenames to see the command-line help for tsc.js.
From the command line you can use ts-node:
npm install ts-node
Then call the command like this:
tsc file.ts --outFile file.js
I have a project which compiles Typescript to Javascript in Java:
https://github.com/martypitt/typescript4j
As discussed in other answers, this makes use of Rhino, so has no dependencies on npm or node.
Here's an example:
// Instantiate the compiler:
TypescriptCompiler compiler = new TypescriptCompiler();
// Compile a string:
String output = compiler.compile("class Greeter { greeting: string; }");
// Or, compile and output to a file:
compiler.compile(new File("example.ts"), new File('output.js'));
I use it in another project - 'Bakehouse' to perform on-the-fly compilation of typescript resources within Spring environments
If it's Java that you need to target then you could run tsc.js with the Rhino engine as part of your build process.
To compile ts -> js: node is available for all common platforms, so I fail to see why you'd want to have a tsc.java when you already have a tsc.js. Installing node is no big deal. In fact, it's easier than Java.
Once you have your proj.js file, you can then copy it to which ever deployment platform you wish to use.
From my point of view, JavaScript - or more accurately ECMAScript is an alternative to Java. So I'm happy that I don't have to wrangle JVM etc to use the tool. But if you prefer Java, then why even bother with JS?
SublimeText2 Trick
You can transpile typescript to javascript directly from SublimeText2 (you need node) :
Create a Typescript.sublime-build file in /Sublime Text 2/Packages/User with this content :
{
"cmd": ["tsc", "$file"],
"selector" : "source.ts",
"path": "/usr/local/bin:$PATH"
}
then, now, you can transpile your code with ctrl+B or cmd+B
I've been playing around with this, and can compile TypeScript with javascript with the following code:
<script src=typescript.js></script>
<script>
var scriptText = ""
+ "/// <reference path=\"test.ts\"/>" + "\r\n"
+ "class Car {"
+ " constructor (private name: string) { } "
+ " getName() { "
+ " var juice = new Juice();"
+ " return name; "
+ " } "
+ "} "
+ "var car = new Car('Subaru Impreza');"
+ "console.log(car.getName());";
var TextWriter = function () { };
TextWriter.prototype = {
collected: '',
Write: function (sc) {
this.collected += sc;
},
WriteLine: function(sc) {
this.collected += sc + '\n';
},
toString: function() {
return this.collected;
}
};
var output = new TextWriter();
var tsc = new TypeScript.TypeScriptCompiler(output);
var script = tsc.addUnit(scriptText, "");
tsc.emit();
console.log(output.toString());
</script>
It's not exactly ideal though. I'm trying to get something running so I can convert TypeScript to JS within C# (using Javascript .NET), but i'm getting a stack overflow on the ts.addUnit call.
You probably don't wanna use ts-node, because it is slow, instead follow following steps for fast .ts files compilation (Make sure node is installed):
npm i -D #types/node typescript nodemon
npx tsconfig.json and select node from the list. You are free to modify it as per your needs.
Create a file names src/index.ts in your project root.
Then in your package.json, add the following 2 scripts:
"scripts": { "watch": "tsc -w", "dev": "nodemon dist/index.js" },
Then use:
npm run watch
npm run dev
And, it will automatically look for changes in .ts files and you can see the compiled file output in the terminal as you go!
This is what worked for me:
First, installed the typescript node module >> npm install -g typescript. This gives a command line utility tsc.
Next, tsc gulpfile.ts gulp-config.ts typings/tsd.d.ts
this will transpile the gulpfile.ts and gulp-config.ts files to gulpfile.js and gulp-config.js. We supply the typings/tsd.d.ts file as reference for correct transpilation.
The typescript node module covers many options >> tsc -h to specify output directory or file, etc..
If you are using "firebase -tool" you can use
npm run build
inside your functions directory.

Batman.js new app issue

I've repeated steps from batman.js readme:
npm install -g batman
batman new mj
cd mj
batman server
And got this in Firebug trying to open localhost:1047
global is not defined
Mj.run();
localhost:1047 (line 52)
Mj.global is not a function
Mj.global(true);
mj.js (line 15)
Mj is undefined
Mj.run();
Did I missed something or should I open issue? Googling batman.js global is not defined gives no relevant results...
As it was pointed by user341180, problem is about node.js version. Have anybody patch for latest versions, or downgrade is the most wise way to deal with batman today?
Hmmm... In README.md it is stated that you'll need to install node.js (0.4.x for now, 0.5.x support forthcoming), but package.json contains:
"engines": {
"node": "~>0.6.0 || ~>0.7.0"
}
So, I'm confused. I suppose, package.json has more recent update, so batman should work with my node.js v0.6.19.
My current workaround is to define root = # befor class Mj extends Batman.App and replace #global yes with root.Mj = # inside one.
There were a lot of changes between 0.9.0 and 0.10.0 and removing global was one of them. Looks like the generator wasn't updated and is still generating 0.9.0 code.
I'm not actually sure how you're running the generator, it throws an error about calling camelize on an undefined object for me.
Anyway, this is definitely a 0.10.0 bug.
Added
The readme also looks like it wasn't updated from 0.9.0
More Followup
Looks like Shopify have fixed this in edge now

Categories