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.
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');
});
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With