grunt-usemin + grunt-rev,在构建时指向CDN url但保留修订版号?

时间:2015-07-31 14:39:24

标签: javascript gruntjs grunt-usemin

我正在使用grunt-usemingrunt-rev结合使用单个连接脚本替换对非优化脚本的引用,并在每个版本上添加修订版。

需要这样:

    <!-- build:js({.tmp,app}) scripts/main.js -->
    <script src="scripts/custom_script1.js"></script>
    <script src="scripts/custom_script2.js"></script>
    <script src="scripts/models/custom_model.js"></script>
    <!-- endbuild -->

并在grunt build之后输出:

<script src="scripts/b7197f7b.main.js"></script>

现在我的问题出现了:

我需要构建输出src不要相对于项目目录,而是指向外部URL,因为我的脚本将托管在CDN上。

// build should produce THIS instead:
<script src="www.my-cdn-url.com/scripts/b7197f7b.main.js"></script>

我尝试使用usemin任务中的blockReplacement配置对象执行此操作:

// this is what I've tried (note the blockReplacement):
usemin: {
    html: ['<%= yeoman.dist %>/{,*/}*.html'],
    css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
    options: {
        dirs: ['<%= yeoman.dist %>'],
        blockReplacements: {
            js: function (block) {
                return '<script type="text/javascript" src="www.my-cdn-url.com/scripts/'+block.dest+'"></script>';
            }
        }
    }
},

虽然这可用于将src属性更改为指向我的CDN,但未应用修订号

我的问题:我如何将我的usemin构建指向外部端点,同时保持构建期间创建的修订版号?

供参考,这是我完整的usemin和rev任务(取自自耕农骨干样板):

usemin: {
    html: ['<%= yeoman.dist %>/{,*/}*.html'],
    css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
    options: {
        dirs: ['<%= yeoman.dist %>'],
        blockReplacements: {
            js: function (block) {
                return '<script type="text/javascript" src="www.my-cdn-url.com/scripts/'+block.dest+'"></script>';
            },
            css: function(block) {
                return '<link rel="stylesheet" href="www.my-cdn-url.com/styles/'+block.dest+'">';
            }
        }
    }
},

rev: {
    dist: {
        files: {
            src: [
                '<%= yeoman.dist %>/scripts/{,*/}*.js',
                '<%= yeoman.dist %>/styles/{,*/}*.css',
                '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}',
                '/styles/fonts/{,*/}*.*',
            ]
        }
    }
}

2 个答案:

答案 0 :(得分:0)

所以我发现只有grunt-revgrunt-usemin无法做到这一点,我需要引入一个额外的grunt插件:grunt-cdnify

以下是Cdnify任务配置如何获得我想要的结果:

cdnify: {
    dist: {
        options: {
            base: '//my-cdn-url.com',
            cc: true
        },
        files: [{
            expand: true,
            cwd: 'dist',
            src: 'index.html',
            dest: 'dist'
        }]
    }
}

/scripts//styles/自然会附加到基本网址。不幸的是,我需要一个额外的插件来做一些如此简单的事情,但是嘿它有效!

答案 1 :(得分:0)

实际上,您可以通过grunt.filerev.summary访问加速文件名。您可以在此处找到一个示例:blockReplacements run before filerev linking