-->

How to let grunt usemin update the JS to reference

2019-04-11 08:44发布

问题:

How to let grunt usemin update the JS to reference our revved images ? from the yeoman web app generator, it only rewrite links for css and html, but no js.

What if my JS file have some images need to be compressed, but cannot link :(

Here is my current parts of grunt.js

    useminPrepare: {
        options: {
            dest: '<%= config.dist %>'
        },
        html: ['<%= config.app %>/*.php', '<%= config.app %>/*.html']
    },

    // Performs rewrites based on rev and the useminPrepare configuration
    usemin: {
        options: {
            assetsDirs: ['<%= config.dist %>', '<%= config.dist %>/images']
        },
        html: ['<%= config.dist %>/{,*/}*.php','<%= config.dist %>/{,*/}*.html'],
        css: ['<%= config.dist %>/styles/{,*/}*.css']
    },

    // The following *-min tasks produce minified files in the dist folder
    imagemin: {
        dist: {
            files: [{
                expand: true,
                cwd: '<%= config.app %>/images',
                src: '{,*/}*.{gif,jpeg,jpg,png}',
                dest: '<%= config.dist %>/images'
            }]
        }
    },...

I used to add js: ['<%= config.dist %>/scripts/{,*/}*.js'] after usemin:css, but it gives me Warning: Unsupported pattern: js Use --force to continue.

How can I write a correct format to let grunt usemin rewrite my JS image reference link to correct compressed image?

回答1:

I managed to figure this, the answer came from this thread https://github.com/yeoman/grunt-usemin/issues/235#issuecomment-33266949

My usemin config ended up like this:

    usemin: {
        options: {
            assetsDirs: ['<%= config.dist %>', '<%= config.dist %>/images', '<%= config.dist %>/styles/fonts'],
            patterns: {
                js: [
                    [/(images\/.*?\.(?:gif|jpeg|jpg|png|webp|svg))/gm, 'Update the JS to reference our revved images']
                ]
            }
        },
        html: ['<%= config.dist %>/{,*/}*.html'],
        css: ['<%= config.dist %>/styles/{,*/}*.css'],
        js: ['<%= config.dist %>/scripts/{,*/}*.js']
    },