我试图使用Grunt作为我的网络应用程序的构建工具。

我想至少有两个设置:

I.开发设置-从单独的文件加载脚本,没有串联,

所以我的index.html看起来是这样的:

<!DOCTYPE html>
<html>
    <head>
        <script src="js/module1.js" />
        <script src="js/module2.js" />
        <script src="js/module3.js" />
        ...
    </head>
    <body></body>
</html>

2生产设置-加载我的脚本缩小和连接在一个文件,

根据index.html:

<!DOCTYPE html>
<html>
    <head>
        <script src="js/MyApp-all.min.js" />
    </head>
    <body></body>
</html>

问题是,当我运行grunt dev或grunt prod时,我如何让grunt根据配置创建这些index.html ?

或者也许我在错误的方向上挖掘,它会更容易总是生成MyApp-all.min.js,但把它里面要么我所有的脚本(连接)或加载器脚本异步加载这些脚本从单独的文件?

你们是怎么做到的,伙计们?


当前回答

这个名为scriptlinker的任务看起来是在开发模式中添加脚本的简单方法。您可以先运行连接任务,然后以prod模式将其指向连接的文件。

其他回答

考虑processhtml。它允许为构建定义多个“目标”。注释用于有条件地从HTML中包含或排除材料:

<!-- build:js:production js/app.js -->
...
<!-- /build -->

就变成了

<script src="js/app.js"></script>

它甚至声称可以做这样漂亮的事情(参见README):

<!-- build:[class]:dist production -->
<html class="debug_mode">
<!-- /build -->

<!-- class is changed to 'production' only when the 'dist' build is executed -->
<html class="production">

这个答案不适合新手!

使用玉石模板…将变量传递给Jade模板是一个标准的用例

我用的是grunt(咕哝-contrib-jade),但你不必用grunt。只需使用标准的npm jade模块。

如果使用grunt,那么你的gruntfile会像这样…

jade: {
    options: {
      // TODO - Define options here
    },
    dev: {
      options: {
        data: {
          pageTitle: '<%= grunt.file.name %>',
          homePage: '/app',
          liveReloadServer: liveReloadServer,
          cssGruntClassesForHtmlHead: 'grunt-' + '<%= grunt.task.current.target %>'
        },
        pretty: true
      },
      files: [
        {
          expand: true,
          cwd: "src/app",
          src: ["index.jade", "404.jade"],
          dest: "lib/app",
          ext: ".html"
        },
        {
          expand: true,
          flatten: true,
          cwd: "src/app",
          src: ["directives/partials/*.jade"],
          dest: "lib/app/directives/partials",
          ext: ".html"
        }
      ]
    }
  },

现在我们可以很容易地访问Jade模板中grunt传递的数据。

与Modernizr使用的方法非常相似,我根据传递的变量值在HTML标记上设置了一个CSS类,并且可以根据CSS类是否存在从那里使用JavaScript逻辑。

如果使用Angular,这是非常棒的,因为你可以根据类是否存在来在页面中包含元素。

例如,我可能会包含一个脚本,如果类是存在的…

(例如,我可能在开发中包含实时重载脚本,但在生产中不包含)

<script ng-if="controller.isClassPresent()" src="//localhost:35729/livereload.js"></script> 

我一直在问自己同样的问题,我认为这个grunt插件可以配置成你想要的:https://npmjs.org/package/grunt-targethtml。它实现了条件html标记,依赖于grunt目标。

我已经有了自己的解决办法。还没有完善,但我想我会朝着那个方向发展。

从本质上讲,我使用了grunt.template.process()从一个模板生成index.html,该模板分析当前配置,并生成原始源文件列表或到一个带有简化代码的文件的链接。下面的例子是针对js文件的,但同样的方法可以扩展到css和任何其他可能的文本文件。

grunt.js:

/*global module:false*/
module.exports = function(grunt) {
    var   // js files
        jsFiles = [
              'src/module1.js',
              'src/module2.js',
              'src/module3.js',
              'src/awesome.js'
            ];

    // Import custom tasks (see index task below)
    grunt.loadTasks( "build/tasks" );

    // Project configuration.
    grunt.initConfig({
      pkg: '<json:package.json>',
      meta: {
        banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
          '<%= grunt.template.today("yyyy-mm-dd") %> */'
      },

      jsFiles: jsFiles,

      // file name for concatenated js
      concatJsFile: '<%= pkg.name %>-all.js',

      // file name for concatenated & minified js
      concatJsMinFile: '<%= pkg.name %>-all.min.js',

      concat: {
        dist: {
            src: ['<banner:meta.banner>'].concat(jsFiles),
            dest: 'dist/<%= concatJsFile %>'
        }
      },
      min: {
        dist: {
        src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],
        dest: 'dist/<%= concatJsMinFile %>'
        }
      },
      lint: {
        files: ['grunt.js'].concat(jsFiles)
      },
      // options for index.html builder task
      index: {
        src: 'index.tmpl',  // source template file
        dest: 'index.html'  // destination file (usually index.html)
      }
    });


    // Development setup
    grunt.registerTask('dev', 'Development build', function() {
        // set some global flags that all tasks can access
        grunt.config('isDebug', true);
        grunt.config('isConcat', false);
        grunt.config('isMin', false);

        // run tasks
        grunt.task.run('lint index');
    });

    // Production setup
    grunt.registerTask('prod', 'Production build', function() {
        // set some global flags that all tasks can access
        grunt.config('isDebug', false);
        grunt.config('isConcat', true);
        grunt.config('isMin', true);

        // run tasks
        grunt.task.run('lint concat min index');
    });

    // Default task
    grunt.registerTask('default', 'dev');
};

index.js(索引任务):

module.exports = function( grunt ) {
    grunt.registerTask( "index", "Generate index.html depending on configuration", function() {
        var conf = grunt.config('index'),
            tmpl = grunt.file.read(conf.src);

        grunt.file.write(conf.dest, grunt.template.process(tmpl));

        grunt.log.writeln('Generated \'' + conf.dest + '\' from \'' + conf.src + '\'');
    });
}

最后,指数。Tmpl,带有生成逻辑:

<doctype html>
<head>
<%
    var jsFiles = grunt.config('jsFiles'),
        isConcat = grunt.config('isConcat');

    if(isConcat) {
        print('<script type="text/javascript" src="' + grunt.config('concat.dist.dest') + '"></script>\n');
    } else {
        for(var i = 0, len = jsFiles.length; i < len; i++) {
            print('<script type="text/javascript" src="' + jsFiles[i] + '"></script>\n');
        }
    }
%>
</head>
<html>
</html>

乌利希期刊指南。发现Yeoman基于grunt,有一个内置的usemin任务,与Yeoman的构建系统集成。它根据index.html开发版本中的信息以及其他环境设置生成index.html的生产版本。有点复杂,但看起来很有趣。

这个名为scriptlinker的任务看起来是在开发模式中添加脚本的简单方法。您可以先运行连接任务,然后以prod模式将其指向连接的文件。