how to minify html with grunt htmlmin plugin?

2019-08-10 14:53发布

I have generated a angular app with yeoman and now trying to minify my html files with grunt + htmlmin. The htmlmin bit looks like this:

  htmlmin: {
            dist: {
                options: {
                    collapseWhitespace: true,
                    conservativeCollapse: true,
                    collapseBooleanAttributes: true,
                    removeCommentsFromCDATA: true
                },
                files: [{
                    expand: true,
                    cwd: '<%= yeoman.dist %>',
                    src: ['*.html'],
                    dest: '<%= yeoman.dist %>'
                }]
            }
        },

When I run this task then it responds that it has minified 2 files but I cant see them in the dist folder? There is no view folder created at all?

2条回答
不美不萌又怎样
2楼-- · 2019-08-10 15:00

With Yeoman, change your grunt file in both the 'htmlmin" and "copy" sections. This will allow for minification, more than one sub directory down.

Change this line:

src: ['*.html', 'views/{,*/}*.html'],

to this:

src: ['*.html', 'views/**/*.html'],

*Just be sure to change it in the 'htmlmin" and correspondingly in the "copy" section of your same grunt file.

查看更多
欢心
3楼-- · 2019-08-10 15:19

I don't use yeoman, but I do use Gruntjs.

Assuming it's not a yeoman config issue, you can do something similar to what I do. Here is the gist...

First I have a development process I've created that does not uglify, minify, or anything else... this helps speed up my dev process.

Then when I'm ready to publish I run it through a publish process that includes uglify, concats, minify, imagemin, etc...

You really only need to minify the html from the build (output) directory... and since you're publishing you might as well just overwrite the HTML files in the build directory with the htmlmin versions (there is really no sense in having both versions for publishing).

Here is my task to do that... for this case let's assume your output directory is named "_build". It's actually a very easy and clean task. Hope this helps...

htmlmin: {
    site: {
        options: {
            removeComments: true,
            collapseWhitespace: true,
            removeEmptyAttributes: false,
            removeCommentsFromCDATA: false,
            removeRedundantAttributes: false,
            collapseBooleanAttributes: false
        },
        expand: true,
        src: './_build/**/*.html',
    }
}

You can't htmlmin something that doesn't exist yet. You have to build the output directory first and then run htmlmin on those files... I think your src will be more like the following as well...

files: [{
    expand: true,
    src: '<%= yeoman.dist %>/**/*.html'
}]

If this works for you, then please vote-up my answer and mark it as the correct answer.

查看更多
登录 后发表回答