Conditional Processing in HTML / JS with Grunt

青春壹個敷衍的年華 提交于 2019-12-11 09:57:41

问题


I'm working on an AngularJS app. I'm building this app with Grunt. I have three Grunt tasks: dev, test, and release. I would like to conditionally reference some JavaScript files in each case. For instance, I'd like to do something like this:

index.html

<!-- if task === 'dev' -->
<script type="text/javascript" src="/js/script.dev.js"></script>
<!-- else if task === 'test' -->
<script type="text/javascript" src="/js/script.test.js"></script>
<!-- else -->
<script type="text/javascript" src="/js/script.min.js"></script>

The above is psedocode. Its the idea of conditionally referencing a file at build time with Grunt. In addition, I would like to do something similar in my JavaScript. I would like to do something like:

#IF RELEASE
var app = angular.module('myApp', ['service', 'otherModule']);
#ELSE
var app = angular.module('myApp', ['serviceMocks', 'otherModule']);
#ENDIF

Once again, the above is pseudocode. I'm in pursuit of the idea of preprocessing my JavaScript with Grunt. Thank you so much!


回答1:


another option is to use grunt-replace, and only replace Variables:

grunt.initConfig({
  replace: {
    dev: {
      options: {
        patterns: [{
          json: {
            "script_src": "/js/script.dev.js",
            "service": "service"
          }
        }]
      },
      files: [{
        expand: true, 
        src: ['index.html', 'your-file.js']
      }]
    },
    test: {
      options: {
        patterns: [{
          json: {
            "script_src": "/js/script.test.js",
            "service": "serviceMock"
          }
        }]
      },
      files: [{
        expand: true, 
        src: ['index.html', 'your-file.js']
      }]
    },
    prod: {
      patterns: [{
          json: {
            "script_src": "/js/script.min.js",
            "service": "service"
          }
      }],
      files: [{
        expand: true, 
        src: ['index.html', 'your-file.js']
      }]
    }
  }
});

in your html/js files just prepare the vars, e.g.:

<script type="text/javascript" src="@@srcipt_src"></script>

or

var app = angular.module('myApp', ['@@service', 'otherModule']);

if your replacements will get large, you could just put it in some target-specific json files:

// e.g. content of dev.json
{
  "script_src": "/js/script.dev.js",
  "service": "service"
}

and in your dev-subtask:

dev: {
  options: {
    patterns: [{
      json: grunt.file.readJSON('dev.json')
    }],
    files: [{
      expand: true, 
      src: ['index.html', 'your-file.js']
    }]
  }
}

this would make sense if your target-specific configurations get large.



来源:https://stackoverflow.com/questions/25246780/conditional-processing-in-html-js-with-grunt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!