I have a folder structure, when I create the build folder using grunt, a hash need to be prefixed with .css file and that name need to be updated in the link tag in index.php.
sitename/css/main.css
sitename/index.php
After executing grunt command build folder need to be created with following structure
build/sitename/css/2ed6bccd.main.css
build/sitename/index.php
In the index.php
<link rel="stylesheet" href="main.css">
need to be replaced with
<link rel="stylesheet" href="2ed6bccd.main.css">
How can I achieve this?
You can use either grunt-rev or grunt-filerev tasks together with grunt-usemin for cache busting of static files in your 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'
}
}});
Your grunt build task:
grunt.registerTask('build', [
'clean:dist',
'useminPrepare',
'concat:generated',
'cssmin:generated',
//'uglify:generated',
'copy:dist',
'rev',
'usemin'
]);
And then in your index.php
, put your css
ref in the following block
<!-- build:css styles/main.css -->
<link rel="stylesheet" href="styles/main.css">
<!-- endbuild -->
This will rename sitename/css/main.css
with an 8 character long hash prefix. For example sitename/css/9becff3a.main.css
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With