How to access module exported function in html <script>

116 views
Skip to first unread message

Yucun Li

unread,
Jun 17, 2016, 10:39:01 AM6/17/16
to Closure Library Discuss
Hi everyone,

Thanks for coming! I just start to use Closure Library, and i am a bit confused about how it works. As a simple example, I am trying to access a compiled js module function. Please find my attached code below.
---------------hello.js--------------
goog.module('hhh');

goog.require('goog.dom');
var h111 = goog.require('h111')

function sayHi() {
  var newHeader = goog.dom.createDom('h1', {'style': 'background-color:#EEE'},
    'Hello world!');
  goog.dom.appendChild(document.body, newHeader);
  h111.sayHi1();
}

exports.sayHi = sayHi;
---------------------------------------
---------------hello1.js-------------
goog.module('h111');

goog.require('goog.dom');

function sayHi1() {
  var newHeader = goog.dom.createDom('h1', {'style': 'background-color:#EEE'},
    'Hello world1111111111!');
  goog.dom.appendChild(document.body, newHeader);
}

exports.sayHi1 = sayHi1;
---------------------------------------
--------------hello.html------------
<html>
  <head>
    <script src="closure-library/closure/goog/base.js"></script>
    <script src="hhh-compiled.js"></script>
  </head>
  <body>
  <script>
  // Here I need to access module function
  </script>
  </body>
</html>
______________________


The simple logic here is hello.js will hello1.js exported function, and it will then be called from html script.

Thanks a lot in advance! ;)


Joel Martinez

unread,
Jun 20, 2016, 4:59:22 PM6/20/16
to Closure Library Discuss
To access compiled symbols in external resources (e.g., in HTML or other scripts), use goog.exportSymbol (https://github.com/google/closure-library/blob/master/closure/goog/base.js#L2326) to export the public symbol you want to use.


So, in your case, in hello1.js:

goog.exportSymbol('sayHi', sayHi1);

and in hello.html:

<script>
sayHi();
</script>


--

---
You received this message because you are subscribed to the Google Groups "Closure Library Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to closure-library-d...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Jorge Davila

unread,
Mar 12, 2018, 11:30:39 AM3/12/18
to Closure Library Discuss
Hi,

I just tried running this example using Webpack, and i got the following error when trying to build: goog.module() call must be the first statement in a module.

Any idea?

Thanks
To unsubscribe from this group and stop receiving emails from it, send an email to closure-library-discuss+unsub...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages