Search code examples
htmlgulpbuild-system

Referring to built files in html using module bundlers


I'm using the Gulp to build my SCSS, Pug and ES6 assets for my static website. I know it's possible to hash file names and output the files in a different directory.

For my specific example:

  • my Pug markdown are found in the ~/src/pages directory and getting built to the ~/public/ directory.
  • My SCSS stylesheets are found in the ~/src/stylesheets directory. These are getting built to the and getting ~/public/style directory

My problem is, when I'm referring to my stylesheets files from Pug, I have to refer to the already-built folder like this:

link(rel='stylesheet', href='./style/example.css')

For my IDE, this doesn't make sense, because the style directory doesn't exist in the ~/src/pages directory.

What I would find the most useful is that I can refer to my stylesheets like the example below:

link(rel='stylesheet', href='../stylesheets/example.scss')

Is there any way this is possible or am I completely going in the wrong direction? If not, where am I looking for?


Solution

  • Solution to make the file name like hash

    • gulp, for automating our task
    • gulp-rev, for renaming our files with random hashes.
    • gulp-rev-collector, for switching non-hashed references by hashed-references inside our files.
    • rev-del, for deleting non-hashed files in our /dist folder.

    Sample code :

    gulpfile.js

    gulp.task("revision:rename", ["serve"], () =>
      gulp.src(["dist/**/*.html",
                "dist/**/*.css",
                "dist/**/*.js",
                "dist/**/*.{jpg,png,jpeg,gif,svg}"])
      .pipe(rev())
      .pipe(revdel())
      .pipe(gulp.dest("dist"))
      .pipe(rev.manifest({ path: "manifest.json" }))
      .pipe(gulp.dest("dist"))
    );
    

    manifest.json

    {
      style.css: style-ds9udjvci.css,
      main.js: main-dijds9xc9.min.js
    }
    

    For creating our revision update in the file like Rewrite every reference for every key of manifest.json to it’s respective value inside every html/json/css/js file (i.e: <link href="style.css"> would become <link href="style-ds9udjvci.css">)

    gulp.task("revision:updateReferences", ["serve", "revision:rename"], () =>
      gulp.src(["dist/manifest.json","dist/**/*.{html,json,css,js}"])
     .pipe(collect())
     .pipe(gulp.dest("dist"))
    );