how to get environment in javascript file in rails app

You dont need to pass it into your javascript file directly. You can do it in the erb view file like this for example:

<script>
  window._rails_env = "<%= Rails.env %>"
</script>

or better this:

<%= javascript_tag do %>
  window._rails_env = "<%= Rails.env %>"
<% end %>

or the best (IMHO) this:

<body data-env="<%= Rails.env %>">
  ...

and then:

var railsEnv = $('body').data('env')

Warning:

Dumping your entire Rails environment in script like this will almost certainly compromise your web app's security! As Michał Zalewski mentions in a comment below, your Rails application has sensitive information in its environment, like database credentials, API keys, application secrets for signing and encrypting cookies etc.


For me, environment.js was located in /config/webpack/environment.js


Rails' asset pipeline will only preprocess assets that you mark for parsing. Whether those assets are going to end up CSS, JS, or whatever else, you can mark files for parsing by adjusting the file extension.

In this case, where you're trying to output an ERB variable, you will need to change the extension of the file to application.js.erb.

There's an extended discussion of the preprocessor here.