javascriptgoogle-closure-compilergoogle-closure-library

how can I use goog.provide and @externs at the same time?


I'm trying to simplify our code a bit by addressing minification issues that tend to make us use something like oVar["stuff"]["things"] rather than oVar.stuff.things

I'm running into an issue using the @externs annotation while also using goog.provide. I've gotten my class to work the way I want if I either manually pass the new file as --externs or I use @externs and pass the new file as --js . The problem with these two solutions is that I'd have to add a --externs or --js for every single "external" class I create.

As soon as I try to add goog.provide or goog.module in the class file (even without using goog.require to load in the file), all externs options that I had working stop working. And just to clarify, using goog.require doesn't help at all in this scenario.

I've added some pseudo code to mimic what I'm doing. Basically, I have a function that an implementer would call with an object that needs to not have any of the parameters be minified.

Here's what I'm trying to do in the class file:

/**
 * @fileoverview
 * @externs
 */

goog.provide("common.classes.newClass");
/**
 *
 * @constructor
 */
common.classes.newClass = function() {};

/**
 * @typedef {*}
 */
common.classes.newClass.prototype.var1;
/**
 * @typedef {*}
 */
common.classes.newClass.prototype.var2;

And here's how I'm trying to use it in another file:

goog.provide("app.namespace");

goog.require("common.classes.newClass");

/**
 * @param {common.classes.newClass} parameter
 * @exports
 */
app.namespace.init = function(parameter)
{
    // do stuff

    /**
     * @type {common.classes.newClass}
     */
    this.passedObject = parameter;

    // do other stuff

    otherFunction(this.passedObject.var1);
};

The problem that I'm running into, is that unless I use this.passedObject['var1'], the 'var1' key gets minified.


Solution

  • You can't. These are for 2 completely separate things. You also don't import an extern or reference it with goog.require. Externs are global.

    To declare a namespace in an extern, just use:

    const common = {};
    /** @const */ common.classes = {};