Search code examples
javascriptgoogle-closuregoogle-closure-libraryconvention-over-configur

Any way to use goog.require in development with convention-over-configuration?


Is there any way I can use Google Closure goog.require to manage JS dependencies, without having to register each namespace explicitly in a dependencies.js file?

I like the idea of the compiler for production, but for development, I'd like some kind of convention-over-configuration translation of namespace to JS folder/path such that something like goog.require('myapp.module') automatically imports myapp/module.js in development mode (if not already imported), while in production it all gets compiled into a single file.

I seem to remember old versions of dojo.require worked this way. Any idea if Google Closure can do the same thing?


Solution

  • Is there any way I can use Google Closure goog.require to manage JS dependencies, without having to register each namespace explicitly in a dependencies.js file?

    The short answer is no. In uncompiled JavaScript code, goog.require() relies on a dependency graph generated by calls to goog.addDependency(relativePath, provides, requires).

    From the DepsWriter documentation:

    But how does Closure Library know which files provide which namespaces? Included in Closure Library is a default dependency file named deps.js. This file contains one line for every JavaScript file in the library, each specifying the file location (relative to base.js), the namespaces it provides, and the namespace it requires.

    In debug mode, a goog.require() statement looks to see if the require namespace was specified and, if so, fetch the files that provide it and all of its dependencies.

    However, Closure Library only comes with a dependency file for the namespaces in the library. If you plan to write your own namespaces (and you likely will), you can use depswriter.py to make a dependency file for the namespaces you create.

    That being said, you could use a tool such as plovr, which provides a "RAW" mode to concatenate your JavaScript sources without compilation. This avoids the need to generate a deps file, but it also means that when debugging code in the browser, it is more challenging to determine the original file containing the code.