Search code examples
htmlgulpnunjucks

How do I configure a static HTML page for different environments?


I'm using Nunjucks for HTML templating and gulp to compile the page. It's just a static one page site but now I found I need to have different values for analytics and such for each environment. What's the best way to do this?

I was thinking about having a config json file and writing different gulp tasks for each environment to change the values but I'd like to see if there's a better way to do this.


Solution

  • Since you are using Nunjucks, you can specify if statement blocks. You can also specify assets paths using variables.

    {% if env == "dev" %}
      <div>dev code</div>
      <img src="{{img_path}}placeholder.png" />
    {% else %}
      <div>prod code</div>
      <img src="{{img_path}}placeholder.png" />
    {% endif %}
    

    You can create a config file for your environments.

    // file: config.js
    module.exports = {
      'dev': {
        env: 'dev',
        img_path: '/path/to/dev/img/'
      },
      'prod': {
        env: 'prod',
        img_path: '/path/to/prod/img/'
      }
    };
    

    Then you could create separate tasks for dev and prod.

    const nunjucks = require('gulp-nunjucks');
    var Config = require('config');
    
    gulp.task('dev', function() {
      return gulp.src('index.html')
        .pipe(nunjucks.compile(Config.envs.dev))
        .pipe(gulp.dest('dist'));
    });
    
    gulp.task('prod', function() {
      return gulp.src('index.html')
        .pipe(nunjucks.compile(Config.envs.prod))
        .pipe(gulp.dest('dist'));
    });