Search code examples
node.jsgulp

Create javascript resource file from local files


I'm using gulp and I trying to create a gulp task that combine files in a javascript file.

For example, image I have this:

File template\template1.html :

<h2>some html content</h2>
<p>blah blah blah</p>

File template\template2.html :

<h2>some other html content</h2>
<img src='cat.png'>

I'd like to read and merge these files into a single javascript file like this :

const templates = {
    "template1" : "<h2>some html content</h2>\n<p>blah blah blah</p>",
    "template2" : "<h2>some other html content</h2>\n<img src='cat.png'>"
}

export default templates

However, I'm failing when dealing with gulp plumbing (I'm quite new to gulp I admit).

How to reach my goal ?

Right now I tried to play with gulp-trough, but it fails at execution:

const gulp = require('gulp');
const through = require('gulp-through');

gulp.task('templates', function () {
    var result = {}
    gulp.src('src/templates/**/*.html')
        .pipe(through('readFile', function(){
            console.log(arguments); // not reached!

        }, defaults));
})

gulp.task('default', ['templates'])

Solution

  • It shouldn't be hard to write your own plugin using through2 module (as explained in official docs.)

    // gulpfile.js
    
    const gulp = require('gulp');
    const path = require('path');
    
    const through = require('through2'); // npm install --save-dev through2
    
    const toTemplateModule = obj => {
      return [
        `const template = ${JSON.stringify(obj, null, 2)};`,
        '',
        'export default template;'
      ].join('\n');
    };
    
    const mergeTemplate = file => {
      const results = {};
      let latestFile;
    
      return through.obj(
        function(file, encoding, callback) {
          latestFile = file;
          results[path.basename(file.path)] = file.contents.toString(encoding);
          callback(null, file);
        },
        function(callback) {
          const joinedFile = latestFile.clone({
            contents: false
          });
          joinedFile.path = path.join(latestFile.base, file);
          joinedFile.contents = Buffer.from(toTemplateModule(results), 'utf-8');
          this.push(joinedFile);
          callback();
        });
    };
    
    gulp.task('templates', () => {
      return gulp
        .src('./src/templates/**/*.html')
        .pipe(mergeTemplate('templates.js'))
        .pipe(gulp.dest('./build'))
    });
    
    gulp.task('default', ['templates'])