### Example Conformance Configuration Source: https://github.com/google/closure-compiler/wiki/JS-Conformance-Framework This example configuration demonstrates how to set up conformance checks for BanUnknownThis, BanUnresolvedType, and BanUnknownTypedClassPropsReferences. It includes specific error messages and requirements for each rule. ```textproto requirement { type: CUSTOM java_class: 'com.google.javascript.jscomp.ConformanceRules$BanUnknownThis' error_message: 'References to "this" that are typed as "unknown" are not allowed. See http://go/closure-js-conformance#unknownThis' } requirement { type: CUSTOM java_class: 'com.google.javascript.jscomp.ConformanceRules$BanUnresolvedType' error_message: 'Forward-declared types must be included in the compilation.' } requirement { type: CUSTOM java_class: 'com.google.javascript.jscomp.ConformanceRules$BanUnknownTypedClassPropsReferences' error_message: 'References to object props that are typed as "unknown" are discouraged.' } ``` -------------------------------- ### NODE Resolution Mode Import Examples Source: https://github.com/google/closure-compiler/wiki/JS-Modules Provides examples of import statements that work with the NODE resolution mode. Modules not starting with '.' or '/' are looked up from node_modules folders. ```javascript import foo from './folder/source.js' ``` ```javascript import foo from '../folder/source.js' ``` ```javascript import foo from '/folder/source' ``` ```javascript import foo from 'folder/source' ``` ```javascript require('./folder/source') ``` ```javascript require('/folder/source') ``` ```javascript require('folder/source') ``` -------------------------------- ### Browser Mode Module Import Examples Source: https://github.com/google/closure-compiler/wiki/JS-Modules These are example import statements for BROWSER mode. Module paths must not begin with '.' or '/', and file extensions are required. ```JavaScript import foo from './folder/source.js' ``` ```JavaScript import foo from '../folder/source.js' ``` ```JavaScript import foo from '/folder/source.js' ``` ```JavaScript require('./folder/source.js') ``` ```JavaScript require('/folder/source.js') ``` ```JavaScript require('../folder/source.js') ``` -------------------------------- ### Install Closure Compiler with NPM or Yarn Source: https://github.com/google/closure-compiler/blob/master/README.md Install the Closure Compiler globally using either NPM or Yarn package managers. ```bash yarn global add google-closure-compiler ``` ```bash npm i -g google-closure-compiler ``` -------------------------------- ### Run Closure Compiler with Conformance Configs Source: https://github.com/google/closure-compiler/wiki/JS-Conformance-Framework Example of invoking the Closure Compiler from the command line with a conformance configuration file. ```bash java -jar build/compiler.jar --conformance_configs my_conformance_config.textproto ``` -------------------------------- ### Basic Compilation Example Source: https://github.com/google/closure-compiler/blob/master/debian/closure-compiler.1.txt This command compiles a JavaScript file and outputs the compiled code to a new file. ```bash --js hello.js --js_output_file hello-compiled.js ``` -------------------------------- ### Protobuf Conformance Requirement Example Source: https://github.com/google/closure-compiler/wiki/JS-Conformance-Framework An example of a conformance requirement defined in a .textproto file, specifying a banned property write with a whitelist. ```protobuf requirement: { type: BANNED_PROPERTY_WRITE value: 'Location.prototype.href' error_message: 'Assignment to Location.prototype.href ' 'is not allowed. Use ' 'goog.dom.safe.setLocationHref instead.' whitelist: 'javascript/closure/dom/safe.js' } ``` -------------------------------- ### Specify Example Text and Original Code for Message Placeholders Source: https://github.com/google/closure-compiler/wiki/Releases Use `original_code` and `example` options in `goog.getMsg` to provide context for message placeholders. This is useful for automatically generated code where meaningful placeholder names are not available. ```javascript const MSG_WELCOME = goog.getMsg( // message template // // This example represents automatically-generated code where // meaningful placeholder names cannot be generated. 'Hi {$interpolation_0}! Welcome to {$interpolation_1}.', // values object { // Also, for the sake of this example, suppose a runtime system is // responsible for transforming these magic strings into the real // values, so the compiler doesn't even have access to any // meaningful source code here it could stick into the XMB file as // a clue to translators. 'interpolation_0': 'magic-string-0', 'interpolation_1': 'magic-string-1' }, // options bag containing the 2 new fields { // These new fields are entirely ignored at runtime. // Both contain object literals whose keys are placeholder names. // Both have values that are string literals. original_code: { // Text indicating how the value is obtained. // Typically this is expected to be a snippet of source code. // Used as the contents of the `` tag in the XMB file. // Default is `-` for historical reasons. // // Human-written code should use meaningful placeholder names // instead of this field. 'interpolation_0': 'foo.getUserName()', 'interpolation_1': 'bar.getProductName()' }, example: { // Example value for the placeholder. // Used as the contents of the `` tag in the XMB file. // Default is `-` for historical reasons. 'interpolation_0': "Yosemite Sam", 'interpolation_1': "Google Six Shooters" } }); ``` -------------------------------- ### HTML Setup for Uncompiled Closure Library Code Source: https://github.com/google/closure-compiler/wiki/Debugging-Uncompiled-Source-Code This HTML structure loads Closure Library's base.js, a dependency file, and then defines and requires your project's main application class. Ensure paths to closure-library and build directories are correct for your setup. ```html ``` -------------------------------- ### JSDoc Configuration File Example Source: https://github.com/google/closure-compiler/wiki/Create-HTML-Docs-using-JSDoc A sample `jsdoc_configure.json` file demonstrating how to configure JSDoc for Closure Compiler projects, including specifying dictionaries, source inclusion patterns, and template options. ```json { "tags": { "allowUnknownTags": true, "dictionaries": ["jsdoc","closure"] }, "source": { "include": [ "src/" ], "includePattern": ".+\.js(doc)?$" }, "plugins": ["plugins/markdown"], "templates": { "cleverLinks": true, "monospaceLinks": false, "default": { "outputSourceFiles": true, "layoutFile": "src/docs/layout.tmpl" } } } ``` -------------------------------- ### Build Closure Compiler with Bazelisk Source: https://github.com/google/closure-compiler/blob/master/README.md Build the compiler's uberjar or all targets using Bazelisk. Ensure Java 21+, NodeJS, Git, and Bazelisk are installed. ```bash bazelisk build //:compiler_uberjar_deploy.jar ``` ```bash bazelisk build //:all ``` -------------------------------- ### Example JavaScript Output Source: https://github.com/google/closure-compiler/wiki/Writing-Compiler-Pass The output JavaScript after the custom compiler pass has been applied, demonstrating the insertion of 'print("Hello World!")' calls. ```javascript var print;print("Hello World!");var x;print("Hello World!"); ``` -------------------------------- ### Example Closure Compiler Message Extraction Command Source: https://github.com/google/closure-compiler/wiki/Translations This command line demonstrates how to run the Java message extractor program. Ensure 'compiler.jar' is in your classpath. ```bash java -classpath .:compiler.jar ExtractMessages MyMessages messages.js ``` -------------------------------- ### Example JavaScript Input Source: https://github.com/google/closure-compiler/wiki/Writing-Compiler-Pass A simple JavaScript snippet with variable declarations, used to test the custom compiler pass. ```javascript var print; var x; ``` -------------------------------- ### Implement IArrayLike for ArrayLikeOfFoo Source: https://github.com/google/closure-compiler/wiki/Special-types-in-the-Closure-Type-System Example of implementing IArrayLike to create an array-like structure of Foo values. It includes a length property and demonstrates type checking for key access. ```javascript /** @constructor @implements IArrayLike */ function ArrayLikeOfFoo() { this.length = 0; } (new ArrayLikeOfFoo())['bar'] // type warning here. (new ArrayLikeOfFoo())[0] // OK, the expression is of type Foo ``` -------------------------------- ### Structural Interface Example Source: https://github.com/google/closure-compiler/wiki/Structural-Interfaces-in-Closure-Compiler Illustrates structural interfaces using @record, where subtyping is based on matching properties without explicit @implements. ```javascript /** @record */ function PNumI() {}; /** @type {number} */ PNumI.prototype.p; /** @constructor */ function Foo() {}; /** @type {number} */ Foo.prototype.p = 5; ``` -------------------------------- ### Implement IObject for MapStringToFoo Source: https://github.com/google/closure-compiler/wiki/Special-types-in-the-Closure-Type-System Example of implementing IObject to create a map from string keys to Foo values. Note the type warning for numeric key access. ```javascript /** @constructor @implements IObject */ function MapStringToFoo() {} (new MapStringToFoo())[0] // type warning here. (new MapStringToFoo())['bar'] // OK, the expression is of type Foo ``` -------------------------------- ### Record Type Object Literal Example Source: https://github.com/google/closure-compiler/wiki/Structural-Interfaces-in-Closure-Compiler Shows how to define and use a record type with an object literal, specifying property types. ```javascript /** * @param {{size: number}} opts */ */ function f(opts) {} f({size: 42}); ``` -------------------------------- ### Example JavaScript Code for Instrumentation Source: https://github.com/google/closure-compiler/wiki/Production-instrumentation This is a sample JavaScript function that will be compiled with production instrumentation enabled. It includes a recursive Fibonacci function and a main function to call it. ```javascript function fib(n) { if (n <= 1) { return 1; } return fib(n - 1) + fib(n - 2); } function main() { const n = 4; console.log(fib(4)); } main(); ``` -------------------------------- ### Dynamic Import Expression Example Source: https://github.com/google/closure-compiler/wiki/JS-Modules Demonstrates a dynamic import expression that Closure Compiler can statically resolve. The compiler will update the specifier to reference the correct output bundle. ```javascript import('./my-module.js') ``` -------------------------------- ### Reexporting goog.module namespaces in goog.provide files Source: https://github.com/google/closure-compiler/wiki/Releases Allows reexporting `goog.module` namespaces in `goog.provide` files to simplify migrations to `goog.module`. This example shows how to alias a module. ```javascript goog.provide('a.b.c'); a.b.c = goog.module.get('c') ``` ```javascript goog.provide('a.b.c'); a.b.c = goog.module.get('other').c; ``` -------------------------------- ### Example Chunk Output Wrapper with Namespace Source: https://github.com/google/closure-compiler/wiki/Chunk-output-for-dynamic-loading This wrapper is used with the `--rename_prefix_namespace` flag to isolate code within chunks and manage cross-chunk references by converting symbols to properties of a specified namespace. ```text (function(NS){%output%}).call(this, window.NS = window.NS || {}) ``` -------------------------------- ### Translation Bundle XML Format Source: https://github.com/google/closure-compiler/wiki/Translations An example of a translation bundle file in XML format for the French language. It maps translation IDs to translated strings. ```xml Dupliquer ``` -------------------------------- ### Dict Annotation Example Source: https://github.com/google/closure-compiler/wiki/@struct-and-@dict-Annotations Use @dict to allow flexible property access using bracket notation. Accessing properties with dot notation will trigger a warning. ```javascript /** * @constructor * @dict */ function Foo(x) { this['x'] = x; } var obj = new Foo(123); var n1 = obj.x; // warning var n2 = obj['x']; // OK ``` -------------------------------- ### Transpiled Async/Await Code Example Source: https://github.com/google/closure-compiler/wiki/FAQ This code demonstrates how an `await` expression within a `goog.asserts.assertString` call is transpiled into multiple statements to preserve evaluation order. This transformation can sometimes lead to property flattening issues. ```javascript const tmpGoogAsserts = goog.asserts; const tmpAssertString = tmpGoogAsserts.assertString; const tmpYieldResult = yield x; tmpAssertString.call(tmpX, tmpYieldResult); ``` -------------------------------- ### Use a Mixin and Introduce Type Errors Source: https://github.com/google/closure-compiler/wiki/Mixins This example demonstrates using the 'helloMixin' with a 'GoodbyeSayer' class and instantiating the resulting 'SocialButterfly'. It intentionally calls methods with missing arguments to highlight potential type checking issues. ```javascript class GoodbyeSayer { goodbye(name) { console.log(`Good bye, ${name}.`); } } const SocialButterfly = helloMixin(GoodbyeSayer); const butterfly = new SocialButterfly(); // Oops - we forgot that both hello and goodbye expect a name.utterfly.hello(); // "Hello, undefined."utterfly.goodbye(); // "Good bye, undefined." ``` -------------------------------- ### HTML Setup for Compiled Closure Compiler Code Source: https://github.com/google/closure-compiler/wiki/Debugging-Uncompiled-Source-Code This HTML structure is used for compiled code, where all necessary code is bundled into a single script file. The script tag simply points to the compiled output file. ```html ``` -------------------------------- ### Closure Compiler: Union Types - Better Example Source: https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System Presents a better way to define union types in Closure Compiler, combining parameters and return types for improved accuracy. ```js /** @typedef {function(string|number):(string|number)} */ let MyType; ``` -------------------------------- ### Run Closure Compiler in Interactive Mode Source: https://github.com/google/closure-compiler/blob/master/README.md Start the Closure Compiler in interactive mode to compile JavaScript code directly. Use Ctrl+Z (Windows) or Ctrl+D (Mac/Linux) followed by Enter to submit the code. ```javascript var x = 17 + 25; ``` -------------------------------- ### Display All Compiler Options Source: https://github.com/google/closure-compiler/blob/master/README.md View a comprehensive list of all available command-line flags and options for the Closure Compiler. ```bash google-closure-compiler --help ``` -------------------------------- ### Closure Compiler: Union Types - Bad Example Source: https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System Shows an example of a poorly formed union type in Closure Compiler, which can lead to inaccurate typechecking for function types. ```js /** @typedef {function(string): string|function(number): number} */ let MyType; ``` -------------------------------- ### Define ice.cream.Shop with dependencies Source: https://github.com/google/closure-compiler/wiki/Managing-Dependencies This code defines the 'ice.cream.Shop' namespace and declares dependencies on 'ice.cream' and 'waffle.cone' using `goog.require`. Ensure the required namespaces are provided in separate files. ```javascript // File 3 - shop.js goog.provide('ice.cream.Shop'); goog.require('ice.cream'); goog.require('waffle.cone'); ``` -------------------------------- ### Older Nullable Type Declarations in Closure Source: https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System Examples of older syntax for declaring nullable types, which are equivalent to modern syntax. ```javascript @type {Object?} ``` ```javascript @type {Object|null} ``` -------------------------------- ### Nominal Interface Example Source: https://github.com/google/closure-compiler/wiki/Structural-Interfaces-in-Closure-Compiler Demonstrates nominal interfaces where explicit @implements is required for subtyping. Without it, type checking will fail. ```javascript /** @interface */ function PNumI() {}; /** @type {number} */ PNumI.prototype.p; /** @constructor */ function Foo() {}; /** @type {number} */ Foo.prototype.p = 5; ``` ```javascript WARNING - initializing variable found : Foo required: PNumI var /** !PNumI */ x = new Foo; ^ ``` -------------------------------- ### Enable Production Instrumentation Flags Source: https://github.com/google/closure-compiler/wiki/Production-instrumentation Use these command-line arguments to enable production instrumentation and specify output file names and array names. ```bash --instrument_for_coverage_option PRODUCTION \ --instrument_mapping_report instrumentationMapping.txt \ --production_instrumentation_array_name ist_arr ``` -------------------------------- ### Closure Compiler Warnings for Mixin Usage Source: https://github.com/google/closure-compiler/wiki/Mixins Example of warnings generated by Closure Compiler when mixin methods are called with incorrect arguments. ```text input0:29: WARNING - [JSC_WRONG_ARGUMENT_COUNT] Function SocialButterfly.prototype.hello: called with 0 argument(s). Function requires at least 1 argument(s) and no more than 1 argument(s). butterfly.hello(); ^^^^^^^^^^^^^^^^^ input0:30: WARNING - [JSC_WRONG_ARGUMENT_COUNT] Function GoodbyeSayer.prototype.goodbye: called with 0 argument(s). Function requires at least 1 argument(s) and no more than 1 argument(s). butterfly.goodbye(); ^^^^^^^^^^^^^^^^^^^ ``` -------------------------------- ### Build Graal Native Image for Closure Compiler Source: https://github.com/google/closure-compiler/wiki/Graal-native-image-notes Use this command to build a static native-image for Closure Compiler. It includes resource bundles and specifies reflection configuration. ```bash native-image --static --no-server \ -H:+ReportUnsupportedElementsAtRuntime \ -H:IncludeResourceBundles=com.google.javascript.rhino.Messages \ -H:IncludeResourceBundles=com.google.javascript.jscomp.CompilerConfig \ -H:IncludeResourceBundles=com.google.javascript.jscomp.parsing.ParserConfig \ -H:ReflectionConfigurationFiles="${PWD}/reflectconfig" \ -H:IncludeResources='.*(js|txt)' -H:EnableURLProtocols=jar \ -jar default_deploy.jar ``` -------------------------------- ### Test Closure Compiler with Bazelisk Source: https://github.com/google/closure-compiler/blob/master/README.md Run all tests in the repository or specify individual test files using Bazelisk. This process may take several minutes. ```bash bazelisk test //:all ``` ```bash bazelisk test //:$path_to_test_file ``` -------------------------------- ### Run Production Instrumentation Reporter Source: https://github.com/google/closure-compiler/wiki/Production-instrumentation Execute the reporting tool with the specified flags to process instrumentation data. Adjust paths and filenames as needed. ```bash java -cp ".;.jarFilesLocation" com.google.javascript.jscomp.instrumentation.ProductionInstrumentationReporter --mapping_file instrument_mapping_report // Location of mapping generated by compiler --reports_directory location_of_reports // The location of the directory which contains all the generated reports --result_output finalResult.json // The name of the JSON which contains the detailed instrumentation data breakdown ``` -------------------------------- ### Enum Definition Source: https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System Defines an enumerated type with a set of named constants. JSDoc comments on enum values are optional. The example shows an enum where values are strings. ```javascript /** @enum {string} */ project.MyEnum = { /** The color blue. */ BLUE: '#0000dd', /** The color red. */ RED: '#dd0000' }; ``` -------------------------------- ### Covariant Record Type Example Source: https://github.com/google/closure-compiler/wiki/Structural-Interfaces-in-Closure-Compiler Illustrates the covariance of record types, allowing a narrower record type to be assigned to a variable expecting a wider record type. ```javascript function f(/** { p : number } */ x) { var /** { p : (number|string) } */ y = x; } ``` -------------------------------- ### Migrating Closure Module with Default Exports (Step 1) Source: https://github.com/google/closure-compiler/wiki/Migrating-from-goog.modules-to-ES6-modules Edit the implementation file to be an ES6 module, call `goog.declareModuleId` with a new namespace, and create a `_shim.js` file. The shim file should be a Closure module that requires the ES6 module and forwards its exports. ```javascript // Example for Step 1 of migrating Closure modules with default exports. // This snippet is illustrative and not directly executable without context. // In the main implementation file (e.g., my/module.js): goog.declareModuleId('my.new.namespace'); // ... ES6 module implementation ... // In the shim file (e.g., my/module_shim.js): goog.module('my.old.namespace'); const myModule = goog.require('my.new.namespace'); exports = myModule.default; // Forwarding the default export ``` -------------------------------- ### Java VM Command-Line Options for Closure Compiler Source: https://github.com/google/closure-compiler/wiki/FAQ These command-line options can significantly improve compilation time for most Closure Compiler jobs. Try one of these configurations when running the compiler. ```bash java -client -d32 -jar compiler.jar ``` ```bash java -server -XX:+TieredCompilation -jar compiler.jar ``` -------------------------------- ### Debugging Dependencies with --output_manifest Source: https://github.com/google/closure-compiler/wiki/Managing-Dependencies Use the --output_manifest flag to generate a list of all input files processed by the compiler, in sorted order. This helps in understanding which files were included in the compilation. ```bash java -jar compiler.jar --js shop-app.js --js shop.js --js icecream.js --js cone.js \ --dependency_mode=PRUNE_LEGACY --output_manifest manifest.MF ``` ```bash cat manifest.MF ``` ```text icecream.js cone.js shop.js shop-app.js ``` -------------------------------- ### Unsupported Syntax Example: Legacy Generator Function Source: https://github.com/google/closure-compiler/wiki/FAQ Closure Compiler adheres to ECMAScript standards and does not support syntax not included in the standard, such as legacy generator functions. ```javascript function* foo() { yield 1; } ``` -------------------------------- ### Compile using Java glob patterns Source: https://github.com/google/closure-compiler/wiki/Managing-Dependencies For projects with many source files, use Java-style glob patterns with the `--js` flag to specify source files recursively. This simplifies the command line when dealing with numerous files. ```bash java -jar compiler.jar --js **.js ``` -------------------------------- ### Function Type Definition Source: https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System Represents a function type, specifying the types of its parameters and its return type. This example shows a function that takes two numbers and returns a number. ```javascript function(x, y) { return x * y; } ``` -------------------------------- ### Generate deps.js using depswriter.py Source: https://github.com/google/closure-compiler/wiki/Debugging-Uncompiled-Source-Code Use this bash command to generate the deps.js file, which maps Closure Library classes to their required dependencies. Adjust the root_with_prefix path to match your project structure. ```bash python ../javascript/closure-library/closure/bin/build/depswriter.py \ --root_with_prefix="src ../../../../myProject/src" > deps.js ``` -------------------------------- ### Struct Annotation Example Source: https://github.com/google/closure-compiler/wiki/@struct-and-@dict-Annotations Use @struct to enforce fixed properties and dot notation access. Accessing properties with brackets or adding new properties will trigger a warning. ```javascript /** * @constructor * @struct */ function Foo(x) { this.x = x; } var obj = new Foo(123); var n1 = obj['x']; // warning var n2 = obj.x; // OK obj.y = "asdf"; // warning ``` -------------------------------- ### Closure Compiler: JSDoc Type Declarations Source: https://github.com/google/closure-compiler/wiki/Types-in-the-Closure-Type-System Provides examples of various JSDoc type declarations used in Closure Compiler, including type, param, enum, and constructor annotations. ```js /** @type {number} */ let x = 0; // Note that @export or @const also work /** @param {string} */ let fn = createStringFn(); /** @enum {string} */ const COLORS = {RED: 0, BLUE: 1}; /** @constructor */ function Klazz() {} // The pre-ES6 style of declaring classes /** @constructor */ let MyCtor = mixin(BaseCtor); // @constructor works even if not assigning a function literal ``` -------------------------------- ### Compile with explicit file order (error) Source: https://github.com/google/closure-compiler/wiki/Managing-Dependencies Attempting to compile a file without explicitly including its dependencies can lead to 'namespace never provided' errors. The compiler requires all necessary files to be passed. ```bash java -jar compiler.jar --js shop.js ``` -------------------------------- ### Elide Function Name on Inlining (JavaScript) Source: https://github.com/google/closure-compiler/wiki/Releases This JavaScript example illustrates how the Closure Compiler now elides the function name when inlining function declaration variables, leading to more concise code. ```javascript function foo() { /* function impl not using foo */ } exports.bar = foo; ``` ```javascript exports.bar = function() {...} ``` -------------------------------- ### Interface Implementation Error with Different Template Types Source: https://github.com/google/closure-compiler/wiki/Generic-Types A class cannot implement the same generic interface multiple times with different template types, as this leads to type conflicts. This example shows an error. ```javascript /** * @interface * @template T */ class Foo { /** @return {T} */ get() {} } /** * @implements {Foo} * @implements {Foo} */ class FooImpl { ... }; // Error - implements the same interface twice ``` -------------------------------- ### Compile JavaScript Files with Closure Compiler Source: https://github.com/google/closure-compiler/blob/master/README.md Use this command to compile JavaScript files, specifying input files and an output file. Globs are supported for input files. ```bash google-closure-compiler 'src/**.js' '!**_test.js' --js_output_file out.js ``` -------------------------------- ### Basic JS Compression Source: https://github.com/google/closure-compiler/blob/master/README.md Compress a single JavaScript file to an output file using default settings. ```bash google-closure-compiler --js file.js --js_output_file file.out.js ``` -------------------------------- ### Generic Class with Typed Methods Source: https://github.com/google/closure-compiler/wiki/Generic-Types Define methods within a generic class that use the template type parameter. The 'get' method returns type T, and 'set' accepts type T. ```javascript /** @template T */ class Foo { /** @return {T} */ get() { ... }; /** @param {T} t */ set(t) { ... }; } ``` -------------------------------- ### Exclude test files using glob patterns Source: https://github.com/google/closure-compiler/wiki/Managing-Dependencies When using glob patterns, you can exclude specific files or patterns using the `!` prefix. This example excludes all files ending in 'test.js' from the compilation process. ```bash java -jar compiler.jar --js !src/**test.js ``` -------------------------------- ### Register a Custom Compiler Pass Source: https://github.com/google/closure-compiler/wiki/Writing-Compiler-Pass This Java code snippet shows how to register the custom 'HelloWorld' compiler pass within the DefaultPassConfig.java file, specifying its name, factory, and feature set. ```java // Collapsing properties can undo constant inlining, so we do this before // the main optimization loop. if (options.getPropertyCollapseLevel() != PropertyCollapseLevel.NONE) { passes.add(collapseProperties); } /////////////////// NEW CODE STARTS ////////////////////////// passes.add( PassFactory.builder() .setName("helloWorld") .setInternalFactory(HelloWorld::new) .setFeatureSet(FeatureSet.ES2019_MODULES) .build()); /////////////////// NEW CODE ENDS //////////////////////////// // ReplaceStrings runs after CollapseProperties in order to simplify // pulling in values of constants defined in enums structures. if (!options.replaceStringsFunctionDescriptions.isEmpty()) { passes.add(replaceStrings); } ``` -------------------------------- ### Compile JS Files with Glob Patterns (Excluding Tests) Source: https://github.com/google/closure-compiler/blob/master/README.md Recursively include all JavaScript files from subdirectories, excluding files that end with '_test.js'. ```bash # 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. ``` -------------------------------- ### NodeJS API Initialization Source: https://github.com/google/closure-compiler/blob/master/README.md Initialize the Closure Compiler programmatically within a NodeJS application. Requires the 'google-closure-compiler' package. ```javascript import closureCompiler from 'google-closure-compiler'; const { compiler } = closureCompiler; new compiler({ js: 'file-one.js', compilation_level: 'ADVANCED' }); ``` -------------------------------- ### Compile Standalone Java Program Source: https://github.com/google/closure-compiler/wiki/Production-instrumentation Use this command to compile the standalone Java reporting tool. Ensure 'jarFilesLocation' and 'location.of.java.files' are correctly specified. ```bash javac -cp "jarFilesLocation" location.of.java.files (To change when reporter has been added) ```