简体   繁体   中英

ember js access environment from ember-cli-build in the vendor file

In my ember-cli-build.js file I'm importing a vendor library called new-relic by using app.import('vendor/new-relic.js') , I would like to pass a parameter called env to the new-relic vendor file and use it in the new-relic.js file. I tried doing

app.import('vendor/new-relic.js', { env: 'production' });

When I try to console log env in the vendor file, it says undefined . Is there any way to pass the env to the vendor file?

When you app.import a vendor file, it does not get executed in the same node environment as ember-cli-build.js at build time, but rather on your user's browser at run time, so there is no way to pass the environment as a parameter.

However, Ember automatically makes the environment available in the browser in the following manner. This is how you can set it on the window object in an initializer:

import ENV from 'config/environment';

export function initialize() {
  window.env = ENV.environment;
}

export default { initialize };

This will make the environment available on the window object as soon as your ember app boots. If your vendor file accesses it then, this will work.

However, this may not be early enough. You may need the env variable to be available as soon as the the new-relic.js file is read by the browser. In order to handle such a use case, you may need to use the contentFor hook in an addon. There is a nice addon already written for you to do this: ember-cli-content-for-config . With it, you can add this to your index.html :

<script>
  window.env = '{{content-for 'config.environment'}}';
</script>

See the README for the addon here: https://github.com/bmac/ember-cli-content-for-config

You will also need to alter new-relic.js to look for the env variable in the global namespace (window object).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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