I am using the Google Closure Compiler on a Drupal project right now. My Javascript is structured using the Javascript Module Pattern.
Because of the way Drupal works, I am compiling each JS file individually. Simple Compilation mode works well, but I would like to use Advanced Compilation on each file.
My files are all variations on
var FOO = (function(me, $, Drupal, undefined) {
function init (context, settings) {
do_sutff();
};
Drupal.behaviors['FOO'] = {
attach: init
};
return me;
}(FOO || {}, jQuery, Drupal));
My problem is that Drupal.behaviors is a specific object in Drupal, and the attach property also is a specific property. When a Drupal page renders, Drupal.behaviors gets looped through, and all of the attach functions are called with the proper arguments. In other words, I don't want anything renamed with the Drupal object.
When I use Advanced Compilation mode, I get
var c = function(a, d, b) {
b.b.FOO = {a:function() {
do_stuff()
}};
return a
}(c || {}, jQuery, Drupal);
I have tried many variations on trying to get the compiler to recognize the whole Drupal object as an extern without luck. No matter what I try, .behaviors and .attach always get renamed.
Is there a way to tell the compiler to keep its hands off an entire object?
There is no concept "Don't modify any properties on this object". You can however setup an extern such as:
/** #interface */
function DrupalBehavior() {}
DrupalBehavior.prototype.attach = function(){};
/** #constructor */
function DrupalObject () {}
/** #type {Object.<string, DrupalBehavior>} */
DrupalObject.prototype.behaviors = {};
Then, in your code:
var FOO = (
/**
* #param {Object} me
* #param {jQuery} $
* #param {DrupalObject} Drupal
* #param {*=} undefined
*/
function(me, $, Drupal, undefined) {
function init (context, settings) {
do_sutff();
};
Drupal.behaviors['FOO'] = {
attach: init
};
return me;
}(FOO || {}, jQuery, Drupal));
In this case the Drupal argument will be renamed, but the behaviors property and its associated attach sub-property will not be.
One note on jQuery: You are passing the jQuery namespace object into the function as a
parameter. Closure-compiler does not trace the type well in this object. The annotation I have listed would be for an instace of the jQuery object as opposed to the entire jQuery namespace. This is probably not what you intended. The only type-safe way to handle this in Closure-compiler is NOT to pass namespaces through function closure.
Update: After looking through the JavaScript Module Pattern post you linked, they encourage passing global namespace objects into function closures. This pattern has known problems with Closure-compiler. You will need to choose to either follow the pattern in this regard or opt for full compatibility with ADVANCED_OPTIMIZATIONS.
Related
I'm currently working on a project and have seen the below code used to store each "Module" (as such) in the window object. I've done a fair amount of Javascript over the years and from my understanding of best practices is that you want to avoid polluting the global namespace. Would this be considered polluting the global namespace?
(function (global) {
"use strict";
// Public methods.
var exports = {};
/*
* Some other configuration / members
*
*/
global.Helper = exports.members;
return exports;
}(window));
I'm accustom to using module pattern to structure my Javascript.
Example below.
var module = (function () {
var defaultOptions = {
//some options
};
var init = function (options) {
defaultOptions = $.extend(defaultOptions, options, false);
};
/*
* More code
*
*/
//public functions
return {
init: init
}
})();
From a best practice stand point am I right in my understanding or have I completely missed the boat?
Is it acceptable practice to store each module in the window object?
I think it's better to put module in global space, because everyone who will use your module would be forced to use it only with a window variable.
Another reason - do window object will always be defined?
All of the famous JavaScript modules are defined in global scope: jquery, prototype, yii etc.
I'm working on a product which needs to conditionally expose an API to the end user. We're using the Closure Compiler for minification. The part of the API that I'm trying to expose is a function that calls a callback with a Result whose value is an object with certain properties.
Specifically, the function I'm trying to expose looks like this (in pseudo-jsdoc notation):
/**
* #type DocumentRenderResult {status: String, image?: HTMLImageElement|HTMLCanvasElement}
* #param {function(Result<DocumentRenderResult>)} callback
**/
function renderDocument (url, page, callback) {
}
And the Result class looks like this:
/**
* #template T
* #param {Boolean} ok
* #param {T} val
* #param {Error} err
**/
function Result (ok, val, err) {
this.ok = ok;
this.val = val;
this.err = err;
}
What I'd like is to expose both the Result object API - that is, the fact that there are ok, val, and err properties, and expose the renderDocument interface so that users providing a callback will be able to access the status and image properties.
One solution (possibly) is to use bracket notation everywhere, but since this is supposed to be only conditionally exposed (for certain end users), I'd like to separate the concept of whether it's minified or not from the code.
I think some combination of #implements and #export and an externs file can accomplish this, but I haven't figured it out.
Is what I'm trying to do possible?
There are 2 primary ways to handle this situation:
Without Closure-Library
Store all of your exports in a separate file that becomes the main entry point for the api exposed library. This methodology has no dependencies on external libraries. For an example of this, see my GeolocationMarker library.
With Closure-Library (or at least a part of it)
If you are willing to utilize a very small part of closure-library code in your project, you can use the #export annotation. #export annotations do nothing unless the compilation flag --generate_exports is specified.
When --generate_exports is used, the compiler will add the appropriate call to either closure-library's goog.exportProperty or goog.exportSymbol method.
/** #const */
var mynamespace = {};
/** #export */
mynamespace.maybeExposedMethod = function() {};
With the --generate_exports flag, the compiler will generate the code:
var mynamespace = {maybeExposedMethod:function() {}};
goog.exportSymbol("mynamespace.maybeExposedMethod",
mynamespace.maybeExposedMethod);
Instead of having to depend on all of closure-library. You can copy the definition for those 2 methods into your source. All that's needed is that they exist as those names.
Conditionally Renaming Record Types
Functions which return anonymous objects must be treated differently to prevent renaming. The best option here would be to define a record type in its own file. For the public api to block renaming, include the record definition as an extern. When you want the record properties to be renamed, include the definition as source.
my_typedefs.js
/** #typedef {{image: string, status: number}} */
var my_record_type;
my_method_def.js
/** #return {my_record_type} */
function my_method() {
return {
image: 'some_image.jpg',
status: 200
};
}
If my_typedefs.js is included in the compilation with the --js flag, the record properties will be renamed, but if it is included with the --externs flag, they will not be renamed.
I'm beginning a fairly large JavaScript project. The project will have everything exist within one or more namespaces, so only a sparse number of things will exist in the global scope (at the moment, there is only one thing).
In order to keep things organized, I would like to keep each class in its own file (much like you would other many other languages) instead of in "modules".
I built a little compilation script (with NodeJS) which will compile all of the files in to a single JavaScript file at the end of the day.
I thought I had a good method, but I'm trying to get JSDoc(3) to cooperate with me and not having a lot of luck, so I'm wondering if I'm maybe tackling this in the wrong way, or if there is some trick with JSDoc I'm missing.
In the source, each namespace is a folder and each class is a file of the same name.
Each class file looks something like this:
var BaseNS = BaseNS || {};
BaseNS.SubNS = BaseNS.SubNS || {};
BaseNS.SubNS.MyClass = (function() {
function MyClass() {
}
Object.defineProperties(MyClass.prototype, {
'someProp', {
getter: function() { return this._someProp = this._someProp || 0; },
setter: function(val) { this._someProp = val; }
}
// ... more
});
MyClass.prototype.someMethod = function() {};
// ... more
return MyClass;
}}());
When compiled together, my compilation script handles dependencies to get the classes in the correct order and also removed duplicate namespace declaration lines.
I think this method is relatively clean and straight-forward. The catch is, I can't figure out how to write the JSDoc documentation in a way which gives me things as I think they should be.
I would like to go with a "class-like" method for things. This is actually for an application which is largely removed from the DOM. Also, I'd like the entire project to be vanilla, modern JavaScript (i.e., no RequireJS, etc.)
Any ideas how to get this documented, or a better way to arrange things?
Thanks.
After playing around with various things for about four hours yesterday, I think I've figured out the optimal format, which combines nice efficent form while allowing for minimal comments to get things to parse properly.
"use strict";
/** #namespace */
var NS = NS || {};
/** #namespace */
NS.Sub = NS.Sub || {};
/**
* #class
*/
NS.Sub.SomeClass = (function(NS) {
/**
* #constructor
* #lends NS.Sub.SomeClass
*/
var SomeClass = function() {
/** #method */
this.someFunc = function(cookie) {
};
Object.defineProperties(this, /** #lends NS.Sub.SomeClass */ {
/**
* #type {number}
* #instance
*/
somePublicProp: {
getter: function() { return this._somePublicProp || 24; },
setter: function(val) { this._somePublicProp = val; }
}
});
};
return SomeClass;
})(NS);
If anyone has any recommendations on how to make this better, I'd love to hear them. In particular, I can't figure out a way to get rid of the need for var SomeClass; ... return SomeClass. I'd like to just return it directly (preferably without any name), but then JSDoc loses track of my method, which means more comments, which isn't cool.
When I put a comment above my variable or function with #private in it what is it actually doing? I have looked at the documentation but I'm still not sure.
goog.provide('myproject');
/** #private */
myproject.foo = "bar";
I can still access it when I open up chrome's development tools (myproject.foo). And...
goog.require('myproject');
window.addEventListener('load', function() {
//this works.
document.body.textContent = myproject.foo;
});
The above code still set's the bodies textContent to equal "bar", even when compiled. So what does #private actually do?
The access control annotations #private, #protected, and #public are
directives for the Closure Compiler that help developers enforce the
desired level of visibility for properties and functions.
To emit warnings for access violations use the Compiler flag:
--jscomp_warning=visibility
To emit errors for access violations use the Compiler flag:
--jscomp_error=visibility
Access control annotations are enforced on a per file basis,
meaning that any properties annotated #private or #protected may be
accessed anywhere within the same file. Also note that the compiler removes
these annotations from the compiled code since they are not part of the
JavaScript language.
Example
file1.js
goog.provide('ns1');
/**
* Global private variable.
* #private
*/
ns1.global = 'foo';
alert('ns1.global = ' + ns1.global); // OK in same file.
/** #constructor */
ns1.Constructor = function() {
/** #private */
this.secret_ = ns1.global;
};
ns1.instance = new ns1.Constructor();
alert(ns1.instance.secret_); // No warning in same file.
file2.js
goog.provide('ns2');
goog.require('ns1');
alert('ns1.global = ' + ns1.global); // Not allowed.
ns2.instance2 = new ns1.Constructor();
alert(ns2.instance2.secret_); // Not allowed.
With the flag --jscomp_error=visibility set, Closure Compiler emits the
following errors.
ERROR - Access to private property global of ns1 not allowed here.
alert('ns1.global = ' + ns1.global);
^
ERROR - Access to private property secret_ of ns1.Constructor not allowed here.
alert(ns2.instance2.secret_);
^
See Visibility (private and protected fields) in the Google JavaScript
Style Guide.
cpeisert implied this in his answer, but just to be explicit: these visibility annotations don't modify your output at all.
Marking a function as #private does not hide it or make it any less accessible in the resulting code than the Compiler normally would, and any third-party code that you introduce at runtime will be able to invoke such functions.
The only access protection offered by these annotations is against code that you compile in with them.
Closure Compiler documentation clearly states: "Don't use Externs instead of Exports". Because Externs are very handy to use, I came down with a problem:
function Lib(){
//some initialization
}
Lib.prototype = {
invoke : function(str){
//this function is called from outside to invoke some of Lib's events
}
}
When using Closure Compiler with ADVANCED_OPTIMIZATIONS, function invoke is removed from the source. This could be prevented in two ways:
Adding the line after prototype definition:
Lib.prototype['invoke'] = Lib.prototype.invoke;
But this adds an ugly peace of code at the end of the output code:
Lib.prototype.invoke = Lib.prototype.g;
I managed to get rid of this by adding this line to the constructor:
this.invoke = this.invoke;
And this line to the externs file:
/**
* #param {String} str
*/
Lib.prototype.invoke = function(str){};
This way, Closure Compiler can't remove invoke function from the output code, because it is assigned by itself in the constructor, and also, it can't rename it, because it is defined in the externs file.
So witch method is better?
If you use JSDoc consistently, you could use the #export tag:
/**
* #param {String} str
* #export
*/
Lib.prototype.invoke = function(str){
//this function is called from outside to invoke some of Lib's events
};
and call the compiler with the --generate_exports flag.
This requires you to either include base.js from the Google Closure library, or to copy goog.exportSymbol and goog.exportProperty to your codebase.
Personally, I like defining interfaces in externs file and having my internal classes implement them.
// Externs
/** #interface */
function IInvoke {};
IInvoke.prototype.invoke;
/**
* #constructor
* #implements {IInvoke}
*/
function Lib(){
//some initialization
}
Lib.prototype = {
invoke : function(str){
//this function is called from outside to invoke some of Lib's events
}
}
You still export the constructor itself, but not the interface methods.