Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable scope when writing meteor package

When I was writing a js file in a meteor package, I had following codes:

A = 1;
console.log(A);
console.log(window.A);

I'm wondering why the first console.log prints 1 but the second prints undefined.

like image 674
waitingkuo Avatar asked Mar 19 '23 21:03

waitingkuo


1 Answers

This happens because the bundler is inteligent enough to parse your package source code looking for global variables. After all, the (generated) code of your package (i.e. the one that actually gets loaded to the browser) is preceeded by something like:

/* Package-scope variables */
var A;

which should explaing everything ;)

If you really want to export your variables to be available outside your package do as @sbking told you, so in package.js write:

// was Package.on_use in older Meteor versions
Package.onUse(function (api) {
  api.export('A');
});

Edit

One thing to keep in mind is that when you put use strict statement at the beginning of your file, Meteor will no longer detect the implicit global variables unless their explicitly exported with api.export. So this is only problematic when you want to have private global variables across your package code.

Note that when strict mode is active and those variables are not put into the package "preamble", trying to assing value to an undefined variable will result in runtime error, so this is in fact a deal breaker. Look here for more details about this problem.

A simple workaround is to put all the private globals in a single file, with no use strict statement at the beginning:

// globals.js
// no "use strict" statement here ...
MyPrivateVariable1 = null;
MyPrivateVariable2 = null;
like image 90
Tomasz Lenarcik Avatar answered Mar 28 '23 05:03

Tomasz Lenarcik