3.3 goog.module statement
All goog.module
files must declare exactly one goog.module
name on a singleline: lines containing a goog.module
declaration must not be wrapped, and aretherefore an exception to the 80-column limit.
The entire argument to goog.module is what defines a namespace. It is thepackage name (an identifier that reflects the fragment of the directorystructure where the code lives) plus, optionally, the main class/enum/interfacethat it defines concatenated to the end.
Example
goog.module('search.urlHistory.UrlHistoryService');
3.3.1 Hierarchy
Module namespaces may never be named as a direct child of another module'snamespace.
Disallowed:
goog.module('foo.bar'); // 'foo.bar.qux' would be fine, though
goog.module('foo.bar.baz');
The directory hierarchy reflects the namespace hierarchy, so that deeper-nestedchildren are subdirectories of higher-level parent directories. Note that thisimplies that owners of “parent” namespace groups are necessarily aware of allchild namespaces, since they exist in the same directory.
3.3.2 goog.module.declareLegacyNamespace
The single goog.module
statement may optionally be followed by a call togoog.module.declareLegacyNamespace();
. Avoidgoog.module.declareLegacyNamespace()
when possible.
Example:
goog.module('my.test.helpers');
goog.module.declareLegacyNamespace();
goog.setTestOnly();
goog.module.declareLegacyNamespace
exists to ease the transition fromtraditional object hierarchy-based namespaces but comes with some namingrestrictions. As the child module name must be created after the parentnamespace, this name must not be a child or parent of any othergoog.module
(for example, goog.module('parent');
andgoog.module('parent.child');
cannot both exist safely, nor cangoog.module('parent');
and goog.module('parent.child.grandchild');
).
3.3.3 goog.module Exports
Classes, enums, functions, constants, and other symbols are exported using theexports
object. Exported symbols may be defined directly on the exports
object, or else declared locally and exported separately. Symbols are onlyexported if they are meant to be used outside the module. Non-exportedmodule-local symbols are not declared @private
nor do their names end with anunderscore. There is no prescribed ordering for exported and module-localsymbols.
Examples:
const /** !Array<number> */ exportedArray = [1, 2, 3];
const /** !Array<number> */ moduleLocalArray = [4, 5, 6];
/** @return {number} */
function moduleLocalFunction() {
return moduleLocalArray.length;
}
/** @return {number} */
function exportedFunction() {
return moduleLocalFunction() * 2;
}
exports = {exportedArray, exportedFunction};
/** @const {number} */
exports.CONSTANT_ONE = 1;
/** @const {string} */
exports.CONSTANT_TWO = 'Another constant';
Do not annotate the exports
object as @const
as it is already treated as aconstant by the compiler.
/** @const */
exports = {exportedFunction};