node.jsexpresscoffeescriptejsconnect-assets

Adding variables to connect-assets


I am trying to add some variables from my app.js file into the file compiled by connect-assets.

I have a file called file.ejs

<%- js('code.js') %>
<input type="text" value="Doe">

In app.js I have:

 app.locals.url = 'http://123.123.123.123'

In code.js I would like to add some production/development variables depending on the system (<%- url %>). When I try to do this, the variable added is rejected, becuase connect-assets is compiling them as tags. What is the proper way to pass in variables into code.js?


Solution

  • code.js is a treated as a static file, so you cannot pass variables into it from an EJS template. Generally in cases like this where you are passing in data based on an environment, you would set some kind of global config variable that you could read inside code.js.

    Rather than set app.locals globally for values like this, you could have a set of settings somewhere for your different environments. Say somewhere in your code you have this:

    var environments = {
      production: {
        url: 'http://1.1.1.1'
      },
      development: {
        url: 'http://2.2.2.2'
      }
    };
    

    When you render your main page template, or somewhere that will be easily accessible, you can pass in the proper settings whatever environment you are in. When rendering the template, you pass the settings. html = new EJS(...).render({settings: settings['production']});

    <html>
      <head>
        <script type="text/javascript">
          var AppSettings = <%= JSON.stringify(settings); %>;
        </script>
    
        ...
    

    And then inside of your code.js file, you can read AppSettings.url directly.