可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Since version 0.6.0, meteor wraps each javascript file into (function() { ... }). This makes perfect sense for my own javascript files. But not for third party libraries. E.g. I am using sha3.js from crypto-js. This. located at client/lib. This was perfect till 0.5.9. But now, the functions from sha3 are not available anymore.
Can this wrapping be switched off?
回答1:
Function closures were first introduced on the server side (and only on the server) for two main reasons :
- Scoped variables are a great way to avoid variables collisions while keeping simple variables names
- It was technically needed for the
Npm.require
feature
One of the Node/Meteor key feature is the ability to run the same file on the client and on the server. That's why variable scoping need to have the same behavior on both client and server, and why Meteor now includes functions closures on client as well.
It's not possible to switch off the wrapping (without changing the Meteor/tools
code).
This behavior will be improved soon with the work on the linker branch that will automatically solve your files dependencies (based on variables names) and then 1. include javascript files in the right order 2. export in the global scope the variables that need to.
For now you will have to manually exports the objects that need to be in the global scope.
回答2:
You can use the undocumented bare
option (formerly raw
) to add_files
:
api.add_files([ 'sha3.js' ], 'client', {bare: true});
And it will not wrap the added file(s).
回答3:
Meteor 0.6.0 introduces NPM compatibility, so one can finally officially use NPM Modules which are added though meteor packages. The issue is that with globalized scoping there are conflicts when it comes to variable declarations as the package is basically counted as if it were a file in your project
This only affects server side code but then if the server side code was scoped then client side code wouldn't be compatible anymore so the client side code is also scoped for consistency.
The solution is to globalize variables as you suggested, in coffeescript by adding @
or by removing the var
in javascript.
While I too find this frustrating with a couple of client side libs (like x-editable & ace editor) a good solution is being worked on with the linker
branch on meteor to allow files to automatically be scanned for dependencies then scope them correctly automatically.
There is a bit more discussion on this at : https://groups.google.com/forum/?fromgroups=#!topic/meteor-talk/gYgYhv88nB4