Google Closure Compiler Documentation
repository·master·Indexed 27 days ago
https://github.com/google/closure-compilerA high-performance JavaScript optimizer and compiler that performs dead-code removal, minification, and type checking. It transforms JavaScript into smaller, faster-running code and provides syntax checking and variable reference validation. The tool supports SIMPLE and ADVANCED optimization modes, utilizes goog.module() and goog.require() for module systems, and can be installed via NPM, Yarn, or Maven.
What's inside Google Closure Compiler
- Google Closure Compiler is a tool designed to make JavaScript download and run faster. It acts as a true compiler that parses JavaScript, analyzes it, removes dead code, and rewrites/minimizes the remaining code. Beyond optimization, it provides syntax checking, variable reference validation, type checking, and warnings for common JavaScript pitfalls.
Use the Closure Compiler in Interactive Mode
masterAfter installation, you can run the compiler in interactive mode by simply typing the command. This allows you to type JavaScript code directly and see the compiled output.
- Run
google-closure-compiler. - Type your JavaScript code (e.g.,
var x = 17 + 25;). - Hit
Enter. - Signal end of input:
Ctrl+Zon Windows, orCtrl+Don Mac/Linux. - Hit
Enteragain to see the output.
google-closure-compiler- Run
Build the Closure Compiler from Source
masterTo build the compiler yourself, you need Java 21+, NodeJS, Git, and Bazelisk. Bazelisk is recommended as it manages the appropriate Bazel version for the repository.
Build commands:
# Build the compiler uberjar bazelisk build //:compiler_uberjar_deploy.jar # Build everything bazelisk build //:allRunning the built JAR:
# Using java directly java -jar bazel-bin/compiler_uberjar_deploy.jar [...args] # Using the package.json script yarn compile [...args]Install the Closure Compiler via NPM or Yarn
masterThe easiest way to install the compiler is using a package manager. Note that the NPM packages are an Open Source contribution by ChadKillingsworth and are not distributed directly by Google.
To install globally, use one of the following commands:
yarn global add google-closure-compiler # OR npm i -g google-closure-compilerSupported Uses and Best Practices
masterGoogle Closure Compiler is used for:
- Reducing code size for large JavaScript applications.
- Checking JS code for errors and best practices.
- Defining user-visible messages for localization.
- Transpiling newer JS features for older browsers.
- Breaking applications into loadable chunks (note: these chunks are plain JS and do not use ES6
import/export).
To achieve these goals, follow these requirements:
- Module Declaration: Use
goog.module()andgoog.require(). - Type Annotations: Use comment annotations to declare type information and provide instructions to the compiler (e.g.,
@nocollapseand@noinline). - Property Access: Stick to either dot-access (
object.property) or dynamic access (object[propertyName]) for any given object type. - Compilation Scope: Aim to compile the entire application as a single unit so the compiler can see all variable/property uses.
- Externs: Use externs files to inform the compiler about variables or properties it must not remove or rename (e.g., standard JS/DOM APIs or external third-party libraries).
Compile Multiple Scripts and Use Globs
masterTo manage dependencies between scripts, compile them all together in a single command. The compiler concatenates files in the order they are passed. You can use minimatch-style globs to include or exclude files.
Note: When using globs in bash, use single quotes to prevent the shell from expanding characters like
!.# Compile multiple specific files google-closure-compiler in1.js in2.js in3.js --js_output_file out.js # Recursively include all js files in subdirs google-closure-compiler 'src/**.js' --js_output_file out.js # Recursively include all js files in subdirs, excluding test files google-closure-compiler 'src/**.js' '!**_test.js' --js_output_file out.jsImportant Caveats for using Closure Compiler
masterTo use Closure Compiler effectively, especially in
ADVANCEDmode, you must be aware of several critical constraints:ADVANCEDMode Requirement: The compiler is optimized forADVANCEDmode. Input code must be written specifically with the compiler in mind to function correctly.- Whole-World Optimization: The compiler expects to see every possible use of every global/exported variable and property. If uses are hidden, the compiler may aggressively rename or remove them, breaking your code. Use externs files to protect names that must remain unchanged.
- Property Access Consistency: You must consistently use either dot-access (
obj.propName) or dynamic access (obj[p]) for a specific object type. Mixing these patterns can lead to broken output because the compiler cannot reliably track property renames. - Global Variable Inlining: The compiler aggressively inlines global variables and flattens property chains (e.g.,
myFoo.some.sub.propertybecomesmyFoo$some$sub$property). - Environment Assumptions: The compiler and its default externs assume a web browser environment. While WebWorkers are supported, NodeJS support is not actively maintained.
- Module System: The compiler is primarily designed for the
goog.module()andgoog.require()module system frombase.js. While it has limited support for ECMAScript modules (import/export), this is not actively maintained and is not the recommended way to define modules.
Download the Closure Compiler via Maven
masterA pre-compiled release of the compiler is available via the Maven repository atcom.google.javascript/closure-compiler.Use ADVANCED Optimizations
masterTo get the most benefit from the compiler, provide all of your source code at once and use the
-O ADVANCEDflag. This allows the compiler to perform more aggressive optimizations across your entire codebase.google-closure-compiler -O ADVANCED rollup.js --js_output_file rollup.min.jsBasic CLI Usage for Compiling JS Files
masterYou can compress a single JavaScript file using the
--jsand--js_output_fileflags. By default, the compiler usesSIMPLEmode.google-closure-compiler --js file.js --js_output_file file.out.jsUse the Closure Compiler NodeJS API
masterYou can access the compiler programmatically in a JavaScript project by importing
google-closure-compiler. This package provides access to the native Graal binary where possible, falling back to the Java version otherwise.import closureCompiler from 'google-closure-compiler'; const { compiler } = closureCompiler; new compiler({ js: 'file-one.js', compilation_level: 'ADVANCED' });Reference: Closure Compiler CLI Flags and Options
masterThe following flags are used to configure the compiler's behavior. Use
google-closure-compiler --helpto see the full list.--compilation_level (-O) Specifies the compilation level to use. Options: BUNDLE, WHITESPACE_ONLY, SIMPLE (default), ADVANCED --env Determines the set of builtin externs to load. Options: BROWSER, CUSTOM. Defaults to BROWSER. --externs The file containing JavaScript externs. You may specify multiple. --js The JavaScript filename. You may specify multiple. The flag name is optional, because args are interpreted as files by default. You may also use minimatch-style glob patterns. --js_output_file Primary output filename. If not specified, output is written to stdout. --language_in Sets the language spec to which input sources should conform. Options: ECMASCRIPT3, ECMASCRIPT5, ECMASCRIPT5_STRICT, ECMASCRIPT_2015, ECMASCRIPT_2016, ECMASCRIPT_2017, ECMASCRIPT_2018, ECMASCRIPT_2019, STABLE, ECMASCRIPT_NEXT --language_out Sets the language spec to which output should conform. Options: ECMASCRIPT3, ECMASCRIPT5, ECMASCRIPT5_STRICT, ECMASCRIPT_2015, ECMASCRIPT_2016, ECMASCRIPT_2017, ECMASCRIPT_2018, STABLE --warning_level (-W) Specifies the warning level to use. Options: QUIET, DEFAULT, VERBOSE