Updating css / js file in html file with grunt

I have a folder structure, when I create a build folder using grunt, the hash must be prefixed with a .css file, and this name needs to be updated in the link tag in index.php.

sitename/css/main.css    
sitename/index.php

After running the grunt build command, create the following structure

build/sitename/css/2ed6bccd.main.css
build/sitename/index.php

In index.php

<link rel="stylesheet" href="main.css">

must be replaced by

<link rel="stylesheet" href="2ed6bccd.main.css">

How can i achieve this?

+4
source share
1 answer

You can use grunt-rev or grunt-filerev tasks together with grunt-usemin to iterate over the cache of static files in index.php

Example:

grunt.initConfig({
config: {
  app: 'sitename',
  dist: 'build/sitename'
},
clean: {
  dist: {
    files: [{
      dot: true,
      src: [
        '.tmp',
        '<%= config.dist %>/*',
        '!<%= config.dist %>/.git*'
      ]
    }]
  }
},
rev: {
  dist: {
    files: {
      src: [
        '<%= config.dist %>/scripts/{,*/}*.js',
        '<%= config.dist %>/styles/{,*/}*.css'
      ]
    }
  }
},
useminPrepare: {
  html: '<%= config.app %>/index.php',
  options: {
    dest: '<%= config.dist %>'
  }
},
usemin: {
  html: ['<%= config.dist %>/{,*/}*.php'],
  css: ['<%= config.dist %>/styles/{,*/}*.css'],
  js: '<%= config.dist %>/scripts/*.js',
  options: {
    dirs: [
      '<%= config.dist %>', 
      '<%= config.dist %>/styles'
    ]      
  }
},
htmlmin: {
  dist: {
    options: {
    },
    files: [{
      expand: true,
      cwd: '<%= config.dist %>',
      src: ['*.html', 'views/*.html'],
      dest: '<%= config.dist %>'
    }]
  }
},
copy: {
  dist: {
    files: [{
      expand: true,
      dot: true,
      cwd: '<%= config.app %>',
      dest: '<%= config.dist %>',
      src: [
        '{,*/}*.php',
        '*.{ico,png,txt}',
        '.htaccess',
        'bower_components/**/*',
        'images/{,*/}*.{gif,webp}',
        'fonts/*',
        'data/*'
      ]
    }, {
      expand: true,
      cwd: '.tmp/images',
      dest: '<%= config.dist %>/images',
      src: [
        'generated/*'
      ]
    }]
  },
  styles: {
    expand: true,
    cwd: '<%= config.app %>/styles',
    dest: '.tmp/styles/',
    src: '{,*/}*.css'
  }
}});

Assembly task:

grunt.registerTask('build', [
     'clean:dist',
     'useminPrepare',
     'concat:generated',
     'cssmin:generated',
     //'uglify:generated',
     'copy:dist',
     'rev',
     'usemin'
  ]);

And then in your index.phpplace your cssref in the next block

  <!-- build:css styles/main.css -->
  <link rel="stylesheet" href="styles/main.css">
  <!-- endbuild -->

sitename/css/main.css 8- . sitename/css/9becff3a.main.css

+3

All Articles