简体   繁体   中英

How to include partial html file into another html file using gulp?

I have two folders, dist and partials , the 'dist' folder contains the index.html file and the 'partials' folder contains header.html, navbar.html, and footer.html files. I want to include these partial files into index.html. I tried the gulp-file-include plugin, It works fine but I want that whenever I perform any changes into any partial file, The index.html file should be updated. I'm not able to do this with the gulp-file-include plugin, Please any other solution...?

gulpfile.js

'use strict'

const fileinclude = require('gulp-file-include');
const gulp = require('gulp');
 
gulp.task('fileinclude', function() {
  return gulp.src(['dist/index.html'])
    .pipe(fileinclude({
      prefix: '@@',
      basepath: '@file'
    }))
    .pipe(gulp.dest('dist'));
});

index.html

@@include('../partials/header.html')
@@include('../partials/navbar.html')
@@include('../partials/footer.html')

Use gulp.watch(...) to track all changes, it's not just for html. Any files in gulp are tracked using this method.

const gulp = require('gulp');
const include_file = require('gulp-file-include');

gulp.task('include', () => {
  return gulp.src('./res/*.html')
    .pipe(include({
      prefix: "@@",
      basepath: "@file"
    }))
    .pipe(gulp.dest('./public'));
});

gulp.task('watch', () => {
  gulp.watch('./res/*.html', gulp.series('include'));
})

also my variant:

const { src, dest, watch } = require('gulp'),
 include_file = require('gulp-file-include');

function include() {
  return src('./res/*.html')
    .pipe(file_include({
      prefix: '@',
      basepath: '@file'
    }))
    .pipe(dest('./public/'));
}

function watching() {
  watch('./res/*.html', include);
}

exports.watch = watching;

then:

gulp watch

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