Set Env variables based on grunt task

I have webapp (emberjs) that I need to set env variables based on grunt task. Therefore, when I start grunt server , it selects development , and the url will be set to localhost:5000 . But when I do grunt build , it selects production , and the url will be installed on production.com .

The main problem for me is how to read these variables from ember. Or how to make grunt look for a variable and change it based on the task

Is it possible to do something like this?

+2
source share
2 answers

After long searches and good examples, here's what I did.

Assuming you are using yoman using the forest using the yo ember generator and using grunt build to create dist.

Yo ember-generator v0.8 uses grunt-replace. Update this version. In short, I use grunt-replace to add global vars to index.html. Here is how.

Add this script tag to app / index.html before the combined scripts.js block:

 #app/index.html <script> /* simplify grunt-replace strategy by placing env vars here. */ window.MYCOMPANYCOM_ENV = { env: '@@env', apiHost: '@@apiHost' }; </script> /* ADD THE ABOVE BEFORE THIS SECTION */ <!-- build:js(.tmp) scripts/main.js --> <script src="scripts/combined-scripts.js"></script> <!-- endbuild --> 

And change the replacement configuration in the Gruntfile.js file to the following:

 module.exports = function (grunt) { var appConfig = grunt.file.readJSON('app_config.json'); replace: { app: { options: { patterns: [ { json: appConfig['app'] } ] }, files: [ {src: '<%= yeoman.app %>/index.html', dest: '.tmp/index.html'} ] }, dist: { options: { patterns: [ { json: appConfig['dist'] } ] }, files: [ {src: '<%= yeoman.dist %>/index.html', dest: '<%= yeoman.dist %>/index.html'} ] } } 

Create a new file in. / app _config.json

 { "app": { "env": "development", "apiHost": "http://localhost:8080" }, "dist": { "env": "dist", "apiHost": "/" } } 

Your application scripts now have access to the global vars defined in app_config.json.

I will not go into details, but it works great in development. For grunt build I moved the replace:dist step to the end of the build steps and replaced the @@ ember variable in index.html with the path to the bower component.

+1
source

Yes it is possible. Using grunt-env to specify your environment in conjunction with something like grunt-usemin to expose environment variables in your application code.

According to this SO thread, you need to make sure that the environment variables are loaded before Ember.js.

+2
source

Source: https://habr.com/ru/post/982152/


All Articles