-
Notifications
You must be signed in to change notification settings - Fork 24
Working with third party libraries
In general, JavaScript libraries cannot be bundled and used directly by Closure Compiler. This because:
- Most JavaScript code does not follow the constraints listed here to be used with ADVANCED_OPTIMIZATIONS
- Closure Compiler currently allows only a single compilation level for the entire bundle.
- Closure Compiler understands only a portion of the conventions in package.json, with which other tools automatically find the right files in an NPM package.
In the future, we hope to provide a compatibility guide to indicate which libraries can be safely used with Closure Compiler. In the meantime, this repo contains some examples to illustrate your options.
TODO(alexeagle): document these examples
Some libraries, including Angular itself, are packaged in a way suitable for direct, optimal consumption by Closure. Such libraries include:
- ES2015 code
- ES2015 modules, ideally a single "flat" module
- Closure type comments
Examples:
- Angular itself
- Angular Material
- Google's Closure library
To use such a library:
TODO(kylecordes): Point out how this is done, in (for example) this repo. TODO: identify any libraries from outside Angular/Google that meet this criteria
Some libraries are compatible with Closure Compiler ADVANCED_OPTMIZATIONS and can be included among the sources you pass to the compiler. These libraries typically:
- Consist of ES5
- Are packaged in CommonJS modules
- Ship with Closure "extern" files
Examples:
- RxJS
We can take the escape route of loading these libraries outside of the Closure Compiled bundle. They can appear as a separate <script>
tag on the page, or they can be concatenated onto the beginning of the bundle file.
However, Closure Compiler will still rename properties where you use these libraries, unless we take care to tell Closure that the names must be preserved. This is done with externs files. See https://developers.google.com/closure/compiler/docs/api-tutorial3#externs.
To do this, include the externs file in the closure.conf
flags, and do not include the third-party library. You should be able to load the library separately and code inside your bundle that calls it should still work. Take the usual caution to avoid negative user experience impact of loading too many scripts, or increasing the total download size of the page.
When consuming code this way it is often necessary to import symbols differently than would would be used with other tooling.
Example:
- Moment
TODO: explain why the different import styles are needed.