Replace all the text with specified replacement us

2019-01-29 11:05发布

I have a .html file which contains id="fixedtext", I want to replace all these id with id="uniquetext"

the grunt-text-replace just replaces the first id it finds and doesnot parse the entire text.

Any idea how can I make either grunt-text-replace https://github.com/yoniholmes/grunt-text-replace

or grunt-replace https://www.npmjs.com/package/grunt-replace to do this for the entire document and not just for the first occurrence.

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

1条回答
啃猪蹄的小仙女
2楼-- · 2019-01-29 11:25

this is what can be done if unique ids are to be added. Assuming that you already have an array of all the id you want to add when you run your task.

In this case the id's are the file names

create your own wrapper task

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);
                }
            } 
 }

});
查看更多
登录 后发表回答