google / google/closure-compiler

Function hoisting does not happen when function is assigned as a goog.module named export

Open
#2,428 4 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
7.7k
Forks
1.2k
Avg merge
2d 12h
Merged PRs (30d)
6

Description

Starting with the `v20170124` release, exports assignments prevent function hoisting.

file-a.js:
```javascript
goog.provide('test');

goog.require('module');
(() => {
console.log(goog.module.get('module'));
})();
```

file-b.js:
```javascript
goog.module('module');

console.log(foo('a', 'b'))
function foo(a, b = null) {
if (b == null) return `${a}`;
else return `${a}/${b}`;
}
exports.foo = foo;
```

compiler options:
```
--closure_entry_point test
--compilation_level ADVANCED_OPTIMIZATIONS
--language_in ECMASCRIPT6
--language_out ECMASCRIPT5
'file-a.js' 'file-b.js'
```

This outputs a file that looks like:
```javascript
var b={};console.log((0,b.a)());b.a=function(){var a="b",a=void 0===a?null:a;return null==a?"a":"a/"+a};console.log(b);
```

If you try to run this file, you get an error saying `TypeError: (0 , b.a) is not a function`

If you move the `console.log` in `file-b.js` to the end of the file, this error does not happen.

It appears that the `function foo()` definition got changed to `b.a=function()` which does not have the hoisting properties that `function foo()` has.

I'm not sure how to use https://closure-compiler.appspot.com/home with multiple files.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.