Add a script tag to index.html only on production build


#1

Hello!

How can I add a script-tag to index.html only when I build my app in production mode? The background to this is:

We want to include a third party library but only when our app is in production mode. The constraint is, that the script needs to be the first script embedded on the page. So I can’t just load it after Ember is ready.

Is there a good way using Broccoli or the Ember-Cli-asset-pipeline to achieve this? Here just some short snippets to get the idea what I need:

In production mode:

<html>
  <head>
   <title>...</title>
   <script src="http://....THIRD-PARTY" />
   ...
   ...

In development mode:

<html>
  <head>
   <title>...</title>
   // NO THIRD PARTY SCRIPT HERE
   ...
   ...

I’m sure there are some neat tricks to do this :wink: Thanks


#2

I wanted to push this thread because I didn’t find a solution but it is very urgent to solve this issue. So if anyone has an idea, please let me know :smile:


#3

If someone has the same problem, here is how I solved it:

Into Brocfile.js

// At the beginning of the file
var replace = require('broccoli-string-replace');
...
...
...
// At the end:
var settings = app.options.getEnvJSON(app.env);
var tree = app.toTree();

tree = replace(tree, {
    files: 'index.html',
    patterns: [{
        match: /\{\{STR_TO_REPLACE\}\}/g,
        replacement: settings.APP.STR_TO_REPLACE
    }]
});

therefore I needed to install broccoli-string-replace via npm. My environment.js looks like follow:

APP: {
    //...
    //...
    STR_TO_REPLACE: ''
    //...
    //...
}

if (environment === 'development') {
    //...
    //...
}
//...
if (environment === 'production') {
   ENV.APP.STR_TO_REPLACE = ...;
}
//...

Works good for me. Don’t know if it is the best solution but I does what I need :smile:


#4

I think the “proper” ember-cli way of doing this is to access the content-for hook. However, you can only access that from an addon so your best option is to create an in-repo addon (scroll down to “In-Repo Addon”). I’m hoping they expose these hooks from within the app someday…