找到你要的答案

Q:How do I include the filename in an uglify banner in grunt?

Q:我怎么包括在丑化旗帜在咕噜的文件名?

I am using grunt to minify some JS files. It would be nice to include the filename in the banner. I have found several examples how to include the package name in the banner, but I haven't yet managed to get the filename in there. So: What do I have to put in the gruntfile (see below) instead of pkg.name to get the source filename (or the dest filename) in there?

Thanks in advance

module.exports = function(grunt) {

   // Project configuration.
   grunt.initConfig({
      pkg: grunt.file.readJSON('package.json'),
      uglify: {
         options: {
            banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
         },
         build: {
            files: [{
               expand: true,
               src: '**/*.js',
               dest: 'build',
               cwd: 'src',
               ext: '.min.js'
            }]
         }
      }
   });

   // Load the plugin that provides the "uglify" task.
   grunt.loadNpmTasks('grunt-contrib-uglify');

   // Default task(s).
   grunt.registerTask('default', ['uglify']);
};

我用咕噜咕噜地缩小一些JS文件。这将是很好的文件名包括在横幅。我已经找到了几个例子,如何在横幅中包含包名,但我还没有得到文件名在那里。所以:要放在gruntfile什么我(见下文)而不是pkg.name得源文件名(或目标文件名)在那里?

先谢谢了。

module.exports = function(grunt) {

   // Project configuration.
   grunt.initConfig({
      pkg: grunt.file.readJSON('package.json'),
      uglify: {
         options: {
            banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'
         },
         build: {
            files: [{
               expand: true,
               src: '**/*.js',
               dest: 'build',
               cwd: 'src',
               ext: '.min.js'
            }]
         }
      }
   });

   // Load the plugin that provides the "uglify" task.
   grunt.loadNpmTasks('grunt-contrib-uglify');

   // Default task(s).
   grunt.registerTask('default', ['uglify']);
};
answer1: 回答1:

I tried to do the same thing, and couldn't find any reference to the current filename that was exposed to the template. Here's the workaround I finally figured out; it's a custom task that dynamically creates a new target for each file:

grunt.registerMultiTask('minify', function () {
    this.files.forEach(function (file) {
        var path = file.src[0],
            target = path.match(/src\/(.*)\.js/)[1];

        // store some information about this file in config
        grunt.config('ugtargets.' + target, {
            path: path,
            filename: path.split('/').pop()
        });

        // create and run an uglify target for this file
        grunt.config('uglify.' + target + '.files', [{
            src: [path],
            dest: path.replace(/^src\/(.*)\.js$/, 'build/$1.min.js')
        }]);
        grunt.task.run('uglify:' + target);
    });
});

And my uglify config:

uglify: {
    options: {
        banner: 'Filename: <% ugtargets[grunt.task.current.target].filename %>\n'
    }
}
  • For each file in your source directory, we create a target name out of the filename. The exact process will depend on how your files are named; you'll want to strip out any dots or slashes. Here I used a regex; in my app I actually used fs to read some JSDoc data from the files themselves.
  • Then we store that filename in an object in the Grunt configuration, indexed by the target name. Here I used an object with a couple of properties; you could add more stuff here or just use a plain string if you wanted.
  • Finally we add a target configuration to the uglify config. This is just the src and dest for the current file; we have to do our own filename processing but it's not much work. Then we run the uglify task with the new target.

In the banner template, you can now use grunt.task.current.target to grab the data we stored in the config earlier. Presto!

我试图做同样的事情,找不到任何引用的当前文件名被暴露到模板。这里的工作我终于想通了;这是一个自定义任务,动态创建的每个文件的一个新的目标:

grunt.registerMultiTask('minify', function () {
    this.files.forEach(function (file) {
        var path = file.src[0],
            target = path.match(/src\/(.*)\.js/)[1];

        // store some information about this file in config
        grunt.config('ugtargets.' + target, {
            path: path,
            filename: path.split('/').pop()
        });

        // create and run an uglify target for this file
        grunt.config('uglify.' + target + '.files', [{
            src: [path],
            dest: path.replace(/^src\/(.*)\.js$/, 'build/$1.min.js')
        }]);
        grunt.task.run('uglify:' + target);
    });
});

我丑化配置:

uglify: {
    options: {
        banner: 'Filename: <% ugtargets[grunt.task.current.target].filename %>\n'
    }
}
  • For each file in your source directory, we create a target name out of the filename. The exact process will depend on how your files are named; you'll want to strip out any dots or slashes. Here I used a regex; in my app I actually used fs to read some JSDoc data from the files themselves.
  • Then we store that filename in an object in the Grunt configuration, indexed by the target name. Here I used an object with a couple of properties; you could add more stuff here or just use a plain string if you wanted.
  • Finally we add a target configuration to the uglify config. This is just the src and dest for the current file; we have to do our own filename processing but it's not much work. Then we run the uglify task with the new target.

横幅上的模板,你可以使用grunt.task.current.target抢我们存储在配置之前的数据。急板地!

answer2: 回答2:

Documentation is indeed scarse, but <%= pkg.name %> in the banner string implies you can also do <% for ( var s in grunt) { %> \ngrunt.<%=s%><% } %> or even <% for ( var s in this) { %> \nthis.<%=s%><% } %>.

So (after some searching) to get the filename you can do this:

var bannerTemplate = '<%' +' var subtask = uglify[grunt.task.current.target];' +' var file = subtask?subtask.dest:\'\';' +' var filename = file.split(\'/\').pop();' +'%>' +'/*! <%= filename %>' +'\n * version: <%= pkg.version %>' +'\n * author: <%= pkg.author %>' +'\n */\n';

文件确实是稀缺的,但& lt;% = pkg.name % & gt;横幅上的字符串意味着你也可以做& lt;%(VAR的咕噜){ % & gt;\ ngrunt。<;% = S % & gt;<;% } % & gt;或甚至<;%(VAR在这){ % & gt;\ n。<;% = S % & gt;<;% } % & gt;。

所以(经过一些搜索)获得文件名,你可以这样做:

var bannerTemplate = '<%' +' var subtask = uglify[grunt.task.current.target];' +' var file = subtask?subtask.dest:\'\';' +' var filename = file.split(\'/\').pop();' +'%>' +'/*! <%= filename %>' +'\n * version: <%= pkg.version %>' +'\n * author: <%= pkg.author %>' +'\n */\n';

answer3: 回答3:

In case you have more scripts to be uglify is convenient to separate it to particular subtasks with custom property as name identifier.

    uglify: {
        options: {
            banner: 
            '<% var subtask = uglify[grunt.task.current.target]; %>' +
            '/* <%= subtask.name %> <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' +
            ' */\n'
        },
        main: {
            name: 'main.min.js',
            files: [{
                src: 'build/files/js/main.min.js',
                dest: 'build/files/js/main.min.js'
            }]
        },
        vendor: {
            name: 'vendor.min.js',
            files: [{
                src: 'build/files/js/vendor.min.js',
                dest: 'build/files/js/vendor.min.js'
            }]
        }
    }

如果你有更多的脚本被丑化便于分离特定的自定义属性名称的子任务。

    uglify: {
        options: {
            banner: 
            '<% var subtask = uglify[grunt.task.current.target]; %>' +
            '/* <%= subtask.name %> <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' +
            ' */\n'
        },
        main: {
            name: 'main.min.js',
            files: [{
                src: 'build/files/js/main.min.js',
                dest: 'build/files/js/main.min.js'
            }]
        },
        vendor: {
            name: 'vendor.min.js',
            files: [{
                src: 'build/files/js/vendor.min.js',
                dest: 'build/files/js/vendor.min.js'
            }]
        }
    }
answer4: 回答4:

Try the following:

banner: grunt.file.read('./folder/file.js'),

http://stackoverflow.com/questions/38854998/dynamic-mapping-and-concat-with-grunt-uglify/

尝试以下:

banner: grunt.file.read('./folder/file.js'),

http://stackoverflow.com/questions/38854998/dynamic-mapping-and-concat-with-grunt-uglify/

answer5: 回答5:

https://github.com/mattstyles/grunt-banner/issues/5#issuecomment-33445038

process: function (src, filepath) {} did the job.

For me, I wanna add "//# sourceUrl=xxx.min.js" at the bottom of each uglified .min.js so that I can debug these dynamically loaded .min.js. The following simple Gruntfile.js works for me:

module.exports = function (grunt) {
    var cwd = "/Branding/Layouts/JS/";
    var src = [
                "file1.js",
                "file2.js",
                "file3.js"
    ];

    var minified_src = [];
    for (i=0;  i< src.length; i++)
        minified_src.push(src[i].replace(/\.js$/g, ".min.js"));

    var config = grunt.initConfig({
        "uglify": {
            options: {
                sourceMap: true
            },
            target: {
                files: [
                    {
                        expand: true,
                        cwd: cwd,
                        src: src,
                        dest: cwd,
                        ext: ".min.js",
                        extDot: "last"
                    }
                ]
            }
        },
        concat: {
            options: {
                process: function (src, filepath) {
                    return src + "\n//# sourceURL=" + filepath.split("/").slice(-1);
                }
            },
            target: {
                files: [
                    {
                        expand: true,
                        cwd: cwd,
                        src: minified_src,
                        dest: cwd
                    }
                ]
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.registerTask('default', ['uglify', 'concat']);
};

Note: uglify can't preserve a comment that is not inside a code block (like //# sourceMap=xxx.js), I have to use concat to append the comment after uglify is done.

Wow, this is my first stackoverflow post.

http:/ / GitHub。COM / mattstyles /咕噜咕噜的旗帜/问题/ 5 # issuecomment-33445038

过程:功能(SRC,文件路径){ }做工作。

对我来说,我想加上“/ # sourceurl=XXX版”在每一个丑化版的底部,这样我可以调试js动态加载。下面简单的Gruntfile.js为我的作品:

module.exports = function (grunt) {
    var cwd = "/Branding/Layouts/JS/";
    var src = [
                "file1.js",
                "file2.js",
                "file3.js"
    ];

    var minified_src = [];
    for (i=0;  i< src.length; i++)
        minified_src.push(src[i].replace(/\.js$/g, ".min.js"));

    var config = grunt.initConfig({
        "uglify": {
            options: {
                sourceMap: true
            },
            target: {
                files: [
                    {
                        expand: true,
                        cwd: cwd,
                        src: src,
                        dest: cwd,
                        ext: ".min.js",
                        extDot: "last"
                    }
                ]
            }
        },
        concat: {
            options: {
                process: function (src, filepath) {
                    return src + "\n//# sourceURL=" + filepath.split("/").slice(-1);
                }
            },
            target: {
                files: [
                    {
                        expand: true,
                        cwd: cwd,
                        src: minified_src,
                        dest: cwd
                    }
                ]
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.registerTask('default', ['uglify', 'concat']);
};

注:丑化不能保存一个评论,是不是在一个代码块(喜欢/ # sourcemap=XXX。JS),我不得不使用concat追加评论后,丑化了。

哇,这是我的第一个计算器后。

gruntjs