简体   繁体   中英

Grunt - html minifier task fails

I am using grunt-contrib-htmlmin for my HTML files.

I added an exception for node_modules directory, so my Gruntfile.js looks like this:

module.exports = function(grunt) {

    grunt.initConfig({
      pkg: grunt.file.readJSON('package.json'),

      htmlmin: {
        prod: {
          options: {
            removeComments: true,
            collapseWhitespace: true
          },
          files: {
            src: ['**/*.html', '!node_modules/'],
            dest: 'prod/'
          }
        }
      }
    });

    grunt.loadNpmTasks('grunt-contrib-htmlmin');

When I run grunt build what I get as a result in console is:

Running "htmlmin:prod" (htmlmin) task
Minified 1 files (1 failed)
Done, without errors.

I have 4 HTML files and none of them are minified and I can't even see the error. What I am missing here?

I cannot reproduce your specific error, but I do see problems with your grunt config.

First, when using the Files Object Format , you specify a src-dest mapping with the destination path as the key and the source path (or array of source paths) as the value. For example:

files: {
    'prod/minified.html': 'src/unminified.html'
}

With your current configuration, src is interpreted as a destination file path.

In order for you to use the src and dest properties in the way you are intending, you must use the Files Array Format .

files: [{
    src: ['**/*.html', '!node_modules/'],
    dest: 'prod/'
}]

Unfortunately, this will not yet get us to our expected output. There are a few problems we need to fix:

prod/ is interpreted as a single destination path, rather than as a prefix as intended. We need to tell grunt to build our files object dynamically by setting expand: true on our files object.

Next, we will need to set flatten: true in our files config to tell grunt to strip the paths of our source file paths when computing the destination file paths.

Thirdly, the pattern !node_modules/ will exempt only an exact match, literally "node_modules/". To exempt all files under the node_modules folder, we must use the globstar matching pattern, !node_modules/** .

Our result is the following:

files: [{
    expand: true,
    flatten: true,
    src: ['**/*.html', '!node_modules/**'],
    dest: 'prod/'
}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM