Javascript 读取Grunt任务中的文件名

Javascript 读取Grunt任务中的文件名,javascript,html,coffeescript,gruntjs,rename,Javascript,Html,Coffeescript,Gruntjs,Rename,我已经将Grunt设置为使用Grunt替换,这样我就可以在几百个HTML页面中找到一个div,并将div中的文本替换为它所在的HTML文件的当前文件名。然而,我不知道该怎么做。我尝试使用window.loacation.href,但这只是在我运行任务时产生了一个错误 这是我的Gruntile.coffee: module.exports = (grunt) -> grunt.initConfig pkg: grunt.file.readJSON "package.json"

我已经将Grunt设置为使用Grunt替换,这样我就可以在几百个HTML页面中找到一个div,并将div中的文本替换为它所在的HTML文件的当前文件名。然而,我不知道该怎么做。我尝试使用window.loacation.href,但这只是在我运行任务时产生了一个错误

这是我的Gruntile.coffee:

module.exports = (grunt) ->
grunt.initConfig
    pkg: grunt.file.readJSON "package.json"
    gruntfile: "Gruntfile.coffee"

    replace:
        dist:
            options:
                patterns: [
                    match: "<div id'name_goes_here'></div>"
                    replacement: ->
                        "<div id'name_goes_here'>Filename: #{window.location.href}</div>"
                ]
            usePrefix: false
            files: [
                expand: true
                flatten: true
                src: [
                    "src/*.html"
                ],
                dest: "output/"
            ]

grunt.loadNpmTasks "grunt-replace";
grunt.registerTask "default", ["replace"];
作为旁注,我试着将一个包含简单字符串的变量传递到替换字符串中,这可以工作并替换所有HTML页面,因此Grunt任务肯定可以工作。替换是一个函数的原因也是因为我计划在以后添加一些额外的东西,但现在只想让它工作

任何帮助都将不胜感激。

编辑:更新Gruntfile.js中的regex,以处理除id之外还可能包含属性的标记。例如:

... 首先grunt运行,因此调用window.location.href会产生错误,因为要处理的.html文件没有加载到web浏览器中。window.location.href是的约定,通常仅适用于浏览器环境

标准任务配置不提供获取正在处理的文件名的机制。但是,由于grunt replace是一个插件,因此可以通过使用自定义函数动态创建replace任务对象来满足您的需求

以下说明了如何实现这一点:

Grunfile.js

module.exports=函数grunt{ grunt.initConfig{ 替换:{}//