简体   繁体   中英

npm concat a static file to all files in directory using gulp

I have tried using npm-concat but it concats all files from folder. but my requirement is something like this-

I have a single file called "header.html","footer.html" and i have folder called view in which i have raw text of html.

tpl
---- header.html
---- footer.html
view
---- view1.html
---- view2.html

Now i want to prepend header.html to all files under view and I want to append footer.html to all files under view folder. How we can achieve this ?

I think you would do better to consider using a template engine such as handlebars to accomplish this task, rather than concatenating files. But I'll try to answer your question since you asked.

I don't know of any plugin that can do this in an optimal way. However, I have written a plugin called gulp-transform that will let you do this fairly easily.

const gulp = require('gulp');
const transform = require('gulp-transform');
const readFileSync = require('fs').readFileSync;

const HEADER = readFileSync('tpl/header.html');
const FOOTER = readFileSync('tpl/footer.html');

gulp.task('html', () => {
  return gulp.src('view/*.html')
    .pipe(transform(contents => Buffer.concat([HEADER, contents, FOOTER])))
    .pipe(gulp.dest('dist'));
});

This is a bit ugly, and in fact I would only recommend using this plugin for a quick fix when there is no better option. A better solution would be to define a custom plugin that does exactly this. If you think it would be helpful, I can show you how you might do that. This is a bit more involved though. I really think your best option is to use a template engine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM