Search code examples
google-closure-compiler

How to preserve export{my_function} in the output when using the Google closure compiler


I have a simple task. The input is like this:

function my_function()
{
}
export {my_function};

I want to preserve the line in the output:

export {my_function};

The motivation is to use the output in my script later.

<javascript type="module">
    import {my_function} from 'my_compiled.js';
</javascript>

I tried many options, but the output file does not have the "export" statement in it. Could you please help me achieve that?

Thanks.


Solution

  • As explained in Closure Compiler docs, you should set your exports on global object:

    function my_function()
    {
    }
    
    window["my_function"] = my_function;
    
    export {my_function};
    

    And later:

    <javascript type="module">
        var my_function = window.my_function;
    </javascript>
    

    Note that you need to use array accessor when setting export on global object, so that Closure Compiler does not rename it: window["my_function"] = ..