使用grunt在html文件中更新css / js文件路径

时间:2015-05-08 09:40:45

标签: gruntjs

我有一个文件夹结构,当我使用grunt创建构建文件夹时,哈希需要以.css文件作为前缀,并且该名称需要在index.php的链接标记中更新。

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

执行grunt命令后,需要使用以下结构

创建构建文件夹
build/sitename/css/2ed6bccd.main.css
build/sitename/index.php

在index.php中

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

需要替换为

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

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:3)

您可以将grunt-revgrunt-filerev任务与grunt-usemin一起用于index.php中静态文件的缓存清除

示例:

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'
  }
}});

你的grunt构建任务:

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

然后在index.php中,将css引用放在下一个区块中

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

这将使用8个字符长的哈希前缀重命名sitename/css/main.css。例如sitename/css/9becff3a.main.css