Google Closure Compiler Documentation

repository·master·Indexed 27 days ago

https://github.com/google/closure-compiler

A 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.

Tokens
2.3K
Snippets
7
Records
12
Agent score
43%

What's inside Google Closure Compiler

  1. Overview of Google Closure Compiler

    master
    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.
  2. Use the Closure Compiler in Interactive Mode

    master

    After 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.

    1. Run google-closure-compiler.
    2. Type your JavaScript code (e.g., var x = 17 + 25;).
    3. Hit Enter.
    4. Signal end of input: Ctrl+Z on Windows, or Ctrl+D on Mac/Linux.
    5. Hit Enter again to see the output.
    google-closure-compiler
  3. Build the Closure Compiler from Source

    master

    To 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 //:all

    Running the built JAR:

    # Using java directly
    java -jar bazel-bin/compiler_uberjar_deploy.jar [...args]
    
    # Using the package.json script
    yarn compile [...args]
  4. Install the Closure Compiler via NPM or Yarn

    master

    The 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-compiler
  5. Supported Uses and Best Practices

    master

    Google 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() and goog.require().
    • Type Annotations: Use comment annotations to declare type information and provide instructions to the compiler (e.g., @nocollapse and @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).
  6. Compile Multiple Scripts and Use Globs

    master

    To 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.js
  7. Important Caveats for using Closure Compiler

    master

    To use Closure Compiler effectively, especially in ADVANCED mode, you must be aware of several critical constraints:

    • ADVANCED Mode Requirement: The compiler is optimized for ADVANCED mode. 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.property becomes myFoo$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() and goog.require() module system from base.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.
  8. Use ADVANCED Optimizations

    master

    To get the most benefit from the compiler, provide all of your source code at once and use the -O ADVANCED flag. 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.js
  9. Use the Closure Compiler NodeJS API

    master

    You 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'
    });
  10. Reference: Closure Compiler CLI Flags and Options

    master

    The following flags are used to configure the compiler's behavior. Use google-closure-compiler --help to 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