why does meteor 0.6.0 wrap everything into (function(){ … })

匿名 (未验证) 提交于 2019-12-03 08:42:37

问题:

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!