Grunt-manifest:将源路径放到子目录中

时间:2014-07-02 16:30:56

标签: javascript gruntjs manifest

我创建了一个离线工作站点,我使用grunt来运行任务。我从本地存储构建静态站点,然后运行这些文件的清单,并将它们复制到服务器。但我必须将它们存储在服务器的子目录中。以某种方式,清单文件中的列表应该具有该子目录名称的前缀。

我在Gruntfile.js

中使用此配置
grunt.initConfig({
    manifest: {
        generate: {
            options: {
                basePath: '<%= yeoman.dist %>/',
                network: ['*'],
                preferOnline: false,
                verbose: false,
                timestamp: true
            },
            src: [
                'fonts/*',
                'images/*',
                'scripts/*.js',
                'styles/*.css'
            ],
            dest: '<%= yeoman.dist %>/manifest.appcache'
        }
    }
});

(我使用yeoman来存储目录值,但这并不重要。)

结果是:

CACHE MANIFEST
# Time: Wed Jul 02 2014 18:26:02 GMT+0200 (Romance Daylight Time)

CACHE:
fonts/glyphicons-halflings-regular.eot
images/test.png
images/test2.png
scripts/05dd5665.scripts.js
.
.
.

NETWORK:
*

但我需要这样:

CACHE MANIFEST
# Time: Wed Jul 02 2014 18:26:02 GMT+0200 (Romance Daylight Time)

CACHE:
subDir/fonts/glyphicons-halflings-regular.eot
subDir/images/test.png
subDir/images/test2.png
subDir/scripts/05dd5665.scripts.js
.
.
.

NETWORK:
*

任何提示?提前谢谢!

1 个答案:

答案 0 :(得分:2)

您可以尝试将basePath指定为类似''的内容。然后,您可以将<%= yeoman.dist %>/附加到src

中的每个条目
grunt.initConfig({
    manifest: {
        generate: {
            options: {
                basePath: '.',
                network: ['*'],
                preferOnline: false,
                verbose: false,
                timestamp: true
            },
            src: [
                '<%= yeoman.dist %>/fonts/*',
                '<%= yeoman.dist %>/images/*',
                '<%= yeoman.dist %>/scripts/*.js',
                '<%= yeoman.dist %>/styles/*.css'
            ],
            dest: '<%= yeoman.dist %>/manifest.appcache'
        }
    },
    replace :{
            key: '<%= yeoman.dist %>'
    }
});

这会将<%= yeoman.dist %>的值附加到CACHE部分中每个条目的前面。您可以使用搜索和替换工具(即sed)将<%= yeoman.dist %>的值替换为您想要的子目录。执行此操作的繁重任务看起来像

var String = require('string'); // pull this dependency with npm install string --save-dev
grunt.registerMultiTask('replace', 'A task to search and replace', function () {
    var bufferJs = grunt.file.read(this.data+'/manifest.appcache');
    var mainManifest = String(bufferJs.toString());
    mainManifest = mainManifest.replaceAll(this.data, 'mySubdir');
    grunt.file.write(this.data+'/manifest.appcache', mainManifest);
});

为了创建清单文件然后执行搜索和替换操作,您可以创建一个单独的grunt任务来调用这两个子任务。以下任务将首先运行manifest,然后运行replace

grunt.registerTask('create_manifest', ['manifest', 'replace:key']);

最后,要运行复合任务,请从命令行运行以下命令

grunt create_manifest