Grunt task to optionally include an AMD module for different environment

倖福魔咒の 提交于 2019-12-14 03:59:41

问题


I'm developing a web app using Require.js for AMD and amplify.request to abstract away my AJAX calls. The other advantage to amplify.request is that I've defined an alternative module containing mocked versions of my requests that I can use for testing purposes. Currently, I'm switching between the two versions of my request module by simply commenting/un-commenting the module reference in my main.js file.

What I'd love to do is use Grunt to create different builds of my app depending on which module I wanted included. I could also use it to do things like turn my debug mode on or off. I'm picturing something similar to usemin, only for references inside JavaScript, not HTML.

Anyone know of a plugin that does this, or have a suggestion about how I could do it with Grunt?


回答1:


On our current project we have a few different environments. For each of them, we can specify different configuration settings for the requirejs build. To distinguish between these different environments, I've used a parameter target.

You can simply pass this to grunt by appending it to your call like

grunt --target=debug

And you can access this parameter in the Gruntfile, by using grunt.option, like

var target = (grunt.option('target') || 'debug').toLowerCase();

The line above will default to debug. You could then make use of the paths configuration setting of requirejs to point the build to the correct module. Example code below.

requirejs: {
    compile: {
        options: {  
            paths: {
                "your/path/to/amplify/request": target === "debug" ? "path/to/mock" : "path/to/real",
                }   
            }
        }
}


来源:https://stackoverflow.com/questions/17383209/grunt-task-to-optionally-include-an-amd-module-for-different-environment

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