2013-02-26 63 views
4

我正在开发一个基于主代码的项目,这个项目应该由一群不同的客户端使用。所以我们有一个requirejs项目,我最初的想法是有简单的bootstrap.js文件,这将需要一个app.js文件,每个客户端都不相同。用requirejs和grunt构建多客户端项目

bootstrap.js

requirejs(['app'],function(app){ 
    //some initial code here 
    app.start(); 
} 

因此该项目结构将是这个样子:

|_bootstrap.js 
|_commonModules 
    |_someModule.js 
|_client1 
    |_app.js 
    |_modules 
    |_module.js 
|_client2 
    |_app.js 
    |_modules 
    |_module.js 

所以我的想法是使用requirejs' R编译器来编译为每个客户端应用程序和在每次编译到clientX/app.js时,通过为每个步骤创建一个新的build.js来设置应用程序的路径,如下所示:

({  
    paths: { 
    "app": "client1/app" 
    } 
}) 

所以目前我有一个咕噜的构建任务,它使用了许多其他任务,如uglify,usemin,md5等。我可以创建一个使用此任务的新任务,但为每个客户端更改requireJs设置?还是有更好的方法来实现我的目标?

回答

6

所以毕竟它不那么难。最酷的是,您可以更改实际运行任务的配置,并且您可以在正在运行的任务中调用先前定义的任务。

//this was the old task to build one distribution 
grunt.registerTask('build', ['clean:build', 'copy:build', 'useminPrepare', 'usemin', 'requirejs', 'concat', 'uglify', 'mincss', 'md5', 'manifest', 'copy:toClientFolder']); 

grunt.registerTask('buildAll', function() { 
    ['client1', 'client2'].forEach(function(client) { 
    //before every build task run a task to change the config 
    grunt.task.run('updateConfig:' + client, 'build'); 
    }); 
}); 

    //we need to change the config in a separate task, 
    //otherwise, change the config just in the forEach, would result in the same 
    //config for both task, using the client2 settings 
    grunt.registerTask('updateConfig', function(client) { 
    var requireJsName = 'requirejs.compile.options.name'; 
    var clientFolder = 'copy.toClientFolder.files'; 
    grunt.config(requireJsName, 'clients/' + client + '/Bootstrap'); 
    grunt.config(clientFolder, [ 
     {expand: true, cwd: 'dist', src: '**', dest: 'dist_' + client} 
    ]); 
    }); 

而对于客户端的app.js文件是这样的:

requirejs.config({ 
    paths: { 
    'commonModules/someModule': 'clients1/modules/module' 
    } 
}); 

requirejs(['boootstrap', 
    'commonModules/someModule1'], 

    function(boootstrap, someModule1) { 
    $(function() { 
     boootstrap(); 
     someModule1(); 
    }); 
    });