简体   繁体   English

在ember-cli环境中如何定义全局变量?

[英]How do a define a global variable in the ember-cli environment?

I'm in the process of porting my ember app to ember-cli. 我正在将我的ember应用程序移植到ember-cli。 I have top level function I'm using that's define like var fooBar = function(a) { }; 我有正在使用的顶层函数,其定义类似于var fooBar = function(a) { }; .

I moved that to app/utils/foo-bar.js (it was all in js/app.js), and added export default fooBar; 我将其移至app / utils / foo-bar.js(全部在js / app.js中),并添加了export default fooBar; to the end of the file. 到文件末尾。

I think that would be fine if the place I was using it could do an import, but for reasons I don't want to get into, I need defined as a global variable. 我认为如果我使用的地方可以导入就可以了,但是出于我不想进入的原因,我需要将其定义为全局变量。

But I still want it in app/utils/ and to be able to import it, as I might rewrite the thing causing me to need it to be a global someday. 但是我仍然希望它在app / utils /中并能够导入,因为我可能会重写它,使我有朝一日需要它成为全球性的东西。

Is there some way to maybe have a <script> tag in my index.html that looks up the module and assigns it to a global variable? 有什么方法可以在我的index.html中有一个<script>标记来查找模块并将其分配给全局变量?

Edit: 编辑:

My forBar function that I want to be global needs to reference another variable via an import statement. 我想成为全局函数的forBar函数需要通过import语句引用另一个变量。 But in /vendor I can't use define or import . 但是在/vendor我不能使用defineimport

So just throwing it in /vendor just gives me back the same problem but for a different variable. 因此,将其扔到/vendor只会给我带来同样的问题,只是变量不同。

A hacky workaround is to put it in a file in the /vendor folder and then app.import that file. 一个变通的解决方法是将其放在/vendor文件夹中的文件中,然后app.import该文件。 That will add it to the vendor.js file making the global available in the browser context. 它将添加到vendor.js文件中,从而使全局vendor.js在浏览器上下文中可用。

Ok, I think I found the answer. 好吧,我想我找到了答案。

<script type="text/javascript">
    var fooBar = require(['path/to/foo-bar']).default;
</script>

What I didn't realize is ember-cli is using requirejs, once I figured that out, I realized this is actually a requirejs question. 我没有意识到ember-cli正在使用requirejs,一旦我弄清楚了,我意识到这实际上是一个requirejs问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM