【问题标题】:Replace all the text with specified replacement using grunt replace使用 grunt replace 将所有文本替换为指定的替换
【发布时间】:2015-04-15 23:13:26
【问题描述】:

我有一个包含 id="fixedtext" 的 .html 文件,我想用 id="uniquetext" 替换所有这些 id

grunt-text-replace 只是替换它找到的第一个 id 而不会解析整个文本。

知道如何制作 grunt-text-replace https://github.com/yoniholmes/grunt-text-replace

或 咕噜替换https://www.npmjs.com/package/grunt-replace 对整个文档执行此操作,而不仅仅是第一次出现。

replace: {
            dist: {
                options:{
                    patterns:[{
                        match:'id="fixedtext"',
                        replacement: 'id="'+something[i++] +'"'
                    }],
                    files:[
                        {
                            expand: true,
                            src:['./source.html'],
                            dest:'./dest.html'
                        }
                    ]
                }
            }
        },

【问题讨论】:

  • 据我研究,通过以下方法添加唯一 id 脚本字段的 id 字段是不可能的。 Grunt 任务如何缓存任务并在递归调用任务时使用它。

标签: gruntjs grunt-contrib-watch grunt-contrib-concat


【解决方案1】:

如果要添加唯一 ID,则可以这样做。 假设您在运行任务时已经有一个包含所有要添加的 id 的数组。

在这种情况下,id 是文件名

创建你自己的包装任务

var path = require('path');
var fs = require('fs');

    grunt.initconfig({
    wrap:{
            html:{
                header:'<script type="text/ng-template" ',
                footer:'</script>',
                src:'./yourPathToFile/',
                dest'./yourPathToDest/'
            }
        }
    });

grunt.registerMultiTask('wrap', 'wrap header and footer with custom id', function(){
 var data = this.data;
 getListOfFiles(data.src);

 function getListOfFiles(expand_path){
       var listOfFiles = fs.readdirSync(expand_path);
            for(var i=0; i<listOfFiles.length; i++){
                var completePath = expand_path + listOfFiles[i];
                var extension = path.extname(completePath);
                if(fs.lstatSync(completePath).isDirectory()){
                    var newDirPath = completePath + '/';
                    console.log('true------ : \n',newDirPath);
                    getListofFiles(newDirPath);
                }
                else if(extension == '.html'){
                    console.log('F:\n', completePath);
                    fullSrcPath = path.resolve(completePath);
                    content = grunt.file.read(fullSrcPath);
                    scriptId = 'id="' + listOfFiles[i]+'">';
                    header = (grunt.template.process(data.header));
                    footer = (grunt.template.process(data.footer));
                    wholeFile = header + scriptId + content + footer;
                    grunt.file.write(fullSrcPath, wholeFile);
                }
            } 
 }

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    相关资源
    最近更新 更多