Our team is working to build a coding standards document for JavaScript. Things like semi-colon use, spaces vs. tabs, curly brace usage, multiple var statements, etc. I was thinking it'd be nice to include a single code block (at the end) that demonstrates our standards visually.
Fonts are sometimes displayed as a pangram to show an example of each letter. For example:
The quick brown fox jumps over the lazy dog
Is there anything like this for JavaScript?
Obviously the number of syntax combinations is non-discrete, but surely the common cases could be demonstrated by a short example. Has anyone run across a code block like this?
Update
To be clear, I'm not looking for standards documents that are littered with isolated examples of each concept. We already have a standards document like that.
I'm looking for a single code example that incorporates the most common standards into a single example.
You can set these rules and enforce them via tools like JSHint and JSBeautifier.
Using these tools you can set up a pre-commit hook in your SCM of choice which will run the linter/beautifier and explain if the files don't match the correct specification.
Then, everything in your repo will be an example of how to code!
It's pretty trivial to do this if you're using something like Grunt since there are tasks for both JSBeautifier and JSHint.
There are countless other tools that provide this functionality as well.
You could do it in
a BASH script calling the CLI tools for these programs
JAKE
CAKE
a MAKEFILE
A custom node script
etc, etc, etc
If you purely want to document it, you can see the comments on your question pointing to several company's specific Javascript style guidelines which you can use in your place wholesale, or use to generate your own. Although I would push you to create tools to enforce these.
Related
I have some html files that I need to do automated processing on, basically regex replaces, but also some more complex actions like copying select blocks of text from one file to another.
I want to create a series of scripts that will let me do this processing (it will need to be done more than once on different batches of files). It would be trivial to use Go for this (read the file into memory, regex, save to disk) but I am the only member of the project that's familiar with Go.
Javascript is a tad more ubiquitous, and I do have project members who are familiar with the language, so it's a better fit in that respect. If I'm not around later, someone else could edit the scripts.
Is there a simple way to write some JS scripts to do on-disk text processing? I'm looking for a cross-platform solution (OSX, Windows). Ideally, once the scripts are written, they can be executed by double-clicking an icon--there will be "not computer people" involved at some point.
Also, I'd like to be able to do some kind of alert/message box to inform the user of the success/failure of the script. (This may be a tall order, and is of secondary importance.)
What I've looked at:
Node.js was the first thing that popped into my head, because I know that it has file system access tools, and obviously regex capacity. But I've never used Node before, and based on the tutorials I've read, it seems like overkill for something this simple.
There's a whole slew of "javascript compiling" tools that you can find by googling around. Some are not cross-platform, some seem old or not actively maintained, etc. None of them caught my eye as easy to pick up and just write some JS scripts with.
Any thoughts?
Node.js is a simple solution and with it's framework you can create or later modify your script to your needs. This way you will not be locked down by someone else's code. And it is not that difficult to to use.
Here is a quick tutorial on accesing files using node.js
http://www.sitepoint.com/accessing-the-file-system-in-node-js/
And here is a quick tutorial on using a node module called Cheerio. It allow you to access html files using "jquery like syntax". You don't need to use regex.
http://maxogden.com/scraping-with-node.html
I worked on a project for a client once and it required parsing thru hundreds of html files to check and replace certain image files based on certain criterias. I wasn't familiar with node at the time so I read some tutorials and wrote the script in about an hour.
And as long as Nodejs' path is set, you can run it on the command line.
Some tips:
You need any kind of DOM HTML parser, not only JS nor specifically JS.
You can do that thing with Java with use of jTidy or jSoup libraries (I've used second one few times). It's pretty simple language to learn if you know JS and IDE like Netbeans helps a lot. So can be made quickly with that.
You can use PhantomJS to create some job files and create shell/batch code to run them on some files. You might need to write a generator for job files (like taking a list of files, creating job files for each and running them).
You can use Node.js which isn't much overkill, I'm sure any solution won't be trivial.
You can create an ETL for processing with for example Pentaho ETL (which has JS embedded as one of two scripting languages... but without DOM parser - for that one you would need to use a bit of Java there and some library in way similar to this article).
You can also do that with PHP with Simple HTML DOM Parser - so you can make a service online (or on local server) that takes those html files and throws out processed ones.
First I think you underestimate the complexity. The statement
"It would be trivial to use Go for this (read the file into memory,
regex, save to disk) but I am the only member of the project that's
familiar with Go."
is probably false. Parsing HTML with RegExp is just a bad idea. (Google it and you will see why)
Second, if you can trivially write the code using RegExps in Go, you can just as easily write the same thing in Javascript. They both support RegExp and file operations. If you are unsure about the Javascript/Node.js details, I suggest writing the trivial solution in Go and then translate the thing into Javascript with a colleague.
Since Javascript is a script language, writing command line utilities in Node.js is straight forward.
Some pointers to get you started
RegExp in Javascript
Building command line apps in Node.js
I'm fairly new to JS development and trying to figure out some best practices for developing and using AMD libraries. Suppose I'm developing a javascript library which depends on jquery, underscore, and whatever else. Furthermore I want to make this library an AMD module and optimize it into a big monolithic file. But the question is, how monolithic? Should it also pull in jquery and underscore so that it's completely self-contained? It seems like the pros and cons of this approach are:
Pro: it's easy to use
as an app developer using this library you can just get it and add a dependency on it, without needing to know that you need jquery, underscore, etc
no having to configure requirejs with the paths to those things
no worrying about the case where one library needs jquery 1.x while another library needs 2.x
Con: it's bloated
if the main application or another library also needs to use jquery, which seems likely, it will essentially get downloaded twice (or n times)
Anything I'm missing here? So which is the right way to do this, or is the answer "it depends", or "make versions of both"? It seems like in general you'd like to share code where possible, but it puts the onus on the consumer of libraries which have non-included dependencies, and necessitates a tool which solves the constraints to find a version of a given library which is compatible with all dependent components. Is there something out there that does something like this?
I can't think of any good reason to include a third party library (such as jQuery or Underscore) with your own library. It's rare to see this technique employed anywhere, if at all, as it restricts the consumer of your code too much.
Not only would it add bloat as you say, but what if I wanted to use Zepto or Lo Dash, or a different version of jQuery? If your library simply lists jQuery and Underscore as a dependency then I could easily map those to load alternate versions or libraries.
Users of AMD (and RequireJS) are typically very comfortable with configuring paths, maps and shims as it necessary in nearly all instances, so I wouldn't worry about that.
Keeping everything separate will also allow flexibility when it comes to optimising the JS for production. For example, I often like the build jQuery into a main module that is loaded on all pages and set other modules to exclude it.
An example of what I mean with that can be seen here:
https://github.com/simonsmith/modular-html-requirejs
I would say you should provide an unoptimized version and an optimized one. If for some reason you can't do both then just provide the unoptimized version. Why the unoptimized version?
Your code is probably not bug-free. It is easier for someone using your library to track down a bug and maybe contribute a patch if there is a 1-for-1 mapping between the original source and what they observed in their debugging environment. (I've tried source maps. They were useful but produced funky results.)
You've said it yourself: libraries like jQuery could end up being loaded n times in the final application. If you provide a way to let the developers use just your library, they can run tests to determine whether they can replace different versions of jquery with just one. (The majority of cases where a library mentions or ships a specific version of jQuery, it's just because it happened to be the version that was current when the library was made, and not because of a hard dependency.)
Provide the optimized version so that someone who just wants to try our library can do it fast.
You ask:
It seems like in general you'd like to share code where possible, but it puts the onus on the consumer of libraries which have non-included dependencies, and necessitates a tool which solves the constraints to find a version of a given library which is compatible with all dependent components. Is there something out there that does something like this?
Yes. A test suite. As a consumer of libraries, I'm unlikely to use one that does not have a substantial test suite. As a producer of software, I don't produce software without a substantial test suite. As I've said above, most often a library that depends on something like jQuery or underscore or what-have-you will list whatever version that happened to be around when the library was developed.
I like the ideas presented by Hedger Wang in his post "Coding Better Object-Oriented JavaScript with Closure Compiler" http://calendar.perfplanet.com/2010/coding-better-object-oriented-javascript-with-closure-compiler/, but his examples don't cover everything, and some examples seem to use a different style than other examples. I have been searching the web for solutions to specific problems, and I have found some, but each solution seems to be incompatible with some other piece of the puzzle.
Can anyone provide a complete working example that covers all of the following SIMULTANEOUSLY:
Uses Google's Closure Compiler with Advanced Optimizations on
Uses annotations, including #type, #constructor, #enum...
Uses externs files for external library (jQuery for example)
Exports a user defined library "class" and all its "public functions" (and includes the externs file for this class)
Has another "class", in its own file, that uses the library without having to recompile that library
Avoids present and future naming collisions (namespacing?)
Avoids globals as much as possible (1 per file seems like a reasonable target to me. The global name can appear multiple times - I don't mind doing one search and replace per file, but I wouldn't want to do more than one such operation)
Includes command lines to use to compile the whole thing
Doesn't have errors or warnings
Example of inheritance, interface,... would be nice, but I can live without these for now
Okay, I know that is a bit of a list, which is why I am having trouble getting everything to work together, but that seems to me to be the basic requirements of a medium to large project. I will continue to bang my head against the wall for a while, but if someone has already done such a project, I would be eternally grateful for a peek.
Check out these videos.
http://www.youtube.com/watch?v=M3uWx-fhjUc
http://www.youtube.com/watch?v=OJ-vTq4lp10
All are about google Closure.
You can also check out this book. It rocks
http://shop.oreilly.com/product/0636920001416.do
My Closure Compiler + KnockoutJS boilerplate covers most of your bullets. Check it out.
There is a GNU indent for styling C sources, are there any equivalents for JavaScript?
I want it to have options for coding style, indention style, etc. just like indent.
I will be using it for a pretty large project on *NIX platform, so I will not like Windows-only utilities or online tools.
I haven't used it, but I bookmarked js-beautify a while back, and a quick check seems to indicate it might satisfy your requirements. (And, being written in JavaScript, you probably can improve on it easily.)
You have a few options:
jsbeautifier
Google Closure Linter
Google Closure Compiler Service (w/ pretty printing option)
Some editors also do this for you:
Emacs
vi(m)
Eclipse
...
EDITS:
Another online tool, JavaScript Indent claims it uses Indent in the background itself. Maybe the author would share the settings. Not so great, but a start.
the JS Beautifier page also mentions that a Python version if being developed as we speak. Let's check again later. In the meantime you can use it with Rhino as mentioned on their page.
Finally, there are already a few SO questions answering this which you can find by searching (some of the results point to formatters to display code online, which is a different thing, though you could use that as well):
Best Source Code Formatter for JavaScript
Formatting JavaScript source code
There's jsBeautifier, which can be run from the command line via Rhino in a Java-enabled environment or run via V8 (or a couple of others, check out the github page). Apparently they're working on a Python command-line version.
Apparently someone's made a start (at least) on updating indent itself to understand JavaScript. The joy of open source! Even if incomplete, the syntaxes are so similar... (No, apparently it's just a web page front-end to indent — not helpful at all.) So rephrasing: I wonder how hard it would be to modify indent to support JavaScript? The syntaxes are so similar...
There is Javascript Tidy, which uses the browser itself to reformat Javascript code. So the results depend on the browser you use.
You cannot determine the style, but once the Javascript has been reformatted to a standard format, it's easier to modify the sourcecode to match your own style.
libjavascript-beautifier-perl package has got /usr/bin/js_beautify, which does the trick for me.
I was recently tasked to document a large JavaScript application I have been maintaining for some time. So I do have a good knowledge of the system.
But due the sheer size of the application, it will probably take a lot of time even with prior knowledge around the code and the source code itself in uncompressed form.
So I'm looking for tools that would help me explore classes and methods and their relationships in JavaScript and if possible, document them along the way, is there one available?
Something like object browser in VS would be nice, but any tools that help me get things done faster will do.
Thanks!
Firebug's DOM tab lets you browse the contents of the global window object, and you can inspect a particular object by entering inspect(whatever) in the command line.
You won't be able to use it to detect relationships unless an instance of one object holds an instance of a related object, but it's a start.
You can also use the Options menu on the DOM tab to restrict what's shown to user-defined functions and properties, which should help reduce clutter.
Take a look at Aptana, they have an outline that can help you to determine what are the objects and somtetimes their relationship.
Firebug + uneval(obj) is a simple trick that is often helpful.
I see a lot of people talking about examining the DOM within Firebug. However, from your question it looks like you want something like jsdoc? just add type and class information through comments and jsdoc generates documentation including class relationships. http://jsdoc.sourceforge.net/
Google has a fork of it with added functionality http://code.google.com/p/jsdoc-toolkit/
UPDATE: It's not a fork, it's a rewrite by the developer that wrote jsdoc originally as a perl script. It aims at being more adaptable so you can use whatever js inheritance/events/properties style you'd like. Another feature is that it lets you modify the templates used to generate the HTML in a much simpler way.
We don't know if this JS application is designed to run in a Web browser...
If yes, as advised, Firebug (a Firefox extension) is excellent at debugging JS and exploring Dom.
On the IE side, you have some tools like IEDocMon, Web Accessibility Toolbar (it does more than its name) or Fiddler (unrelated to your question, but still a good tool to have).
Firebug (Firefox) / Dragonfly (Opera) can help you with viewing objects in realtime
Aptana / JS/UML(Eclipse) can help with relationships of objects
This is an old question, but let me answer it anyway.
Use an IDE. Integrated Development Environments were made for jumping around rapidly among the code. The key features you will exercise during exploration are viewing the file structure or outline, jumping to a declaration or usage, and searching the entire project for all instances of a string. If you are using WebStorm, set up a custom scope for files except generated files and node.js to aid in searching.
Run 'npm la | less' which lists all your dependent modules with one line descriptions. You may have never seen moment.js and never need to read the documentation, but taking the time to read a one line summary of it is worthwhile. If you need more information on a tool than one line summary, search for the term on SlideShare. Slides are faster than ReadTheDocs.
Document a little as you go. I'm a fan of forcing people to use notebooks constantly rather than scratch paper. Also, I find adding a one line comment to each JavaScript file is worthwhile. You want to know what should be in each directory of your project. I also recommend building a glossary of the exact meaning of domain terms in your system, e.g., what does "job" in your system.
Finally, you may need to just fire up the application in a debugger and start stepping through parts of it. Most large projects have accreted worth from programmers of various skill levels and motivations.
You are aiming for a level of "conceptual integrity" (to quote Yourdon) or to "grok" the software (to quote Heinlien). It does take some time, cannot be bypassed, and can be done efficiently.