javascriptnode.jsbackbone.jsr.js

How to change script tag url automatically on build


I'm running Backbone with node using the following code in index.html

<script src="js/api/require.js"></script>
<script>require(['js/require-cfg'],function(){require(['main'])});</script>

main.js looks like this:

require(['app'], 
  function(App){
    App.initialize();
  }
);

In production, I compile the files using r.js into main-build.js and redirect the link in the index.html file from main to main-build:

<script>require(['js/require-cfg'],function(){require(['main-build'])});</script>

Currently, if I want to deploy my code to production, I have to either manually change from main to main-build in index.html, or keep the link as main-build but change the contents of main-build.js to the same as main.js when I run a local or test environment, then switch back when deploying to production.

Is there a better (automatic) way of having the code use the compiled main-build.js when in production, and the content of main.js when in local or test environment?

eg: using node environment variables to either change the links in index.html (not sure how to change html!) or change the content of main-build.js but the content gets overwritten everytime r.js is run to compile for production


Solution

  • I personally use Gulp to process the index.html file with gulp-html-replace.

    In development, you put the tags you need.

    <script src="js/api/require.js"></script>
    <!-- build:js -->
    <script>require(['js/require-cfg'],function(){require(['main'])});</script>
    <!-- endbuild -->
    

    To make a build for production, create a gulp task which uses the gulp-html-replace plugin :

    var gulp = require('gulp'),
        htmlreplace = require('gulp-html-replace');
    
    gulp.task('build', function() {
    
        return gulp.src("index.html")
            .pipe(htmlreplace({
                js: {
                    src: [['main-build']],
                    tpl: '<script>require(["js/require-cfg"],function(){require(["%s"])});</script>'
                },
            }))
            .pipe(gulp.dest("build/index.html"));
    });
    

    If you go the Gulp route, you could make all the build process through it. For example, here's a simple r.js task:

    var rjs = require('requirejs');
    
    gulp.task('optimize', function(done) {
        rjs.optimize({
            name: "main",
            out: "build/js/main.min.js",
            /* ...other options */
        }, function(buildResponse) {
            done();
        }, done);
    });