Nick Bondarenko
Nick Bondarenko

Reputation: 6381

How to concat js/css files and replace in html using gulp?

Here is a lot of questions and answers how to make assets concatination or replacement in template. Use grunt-concat to merge files, use gulp-html-replace to replace in templates. And i can`t understand how to connect them with each other.

So given template, friends.tpl with special set of css files:

!DOCTYPE html>
<html>
<head>
    <!-- build:css friends.min.css -->
    <link rel="stylesheet" href="css/component1/style.css">
    ...
    <link rel="stylesheet" href="css/componentN/style.css">
    <!-- /build -->
</head>
<body/>

The desired result

!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="css/friends.min.css">
</head>
<body/>

And created friends.min.css file with concatenated files above.

How to achieve this - concat based on template data

Upvotes: 2

Views: 2349

Answers (1)

Thiago Freitas
Thiago Freitas

Reputation: 36

Use gulp-htmlbuild,it does what you want.

gulp.task('build', function () {


gulp.src(['./index.html'])
    .pipe(htmlbuild({
      // build js with preprocessor 
      js: htmlbuild.preprocess.js(function (block) {

    // read paths from the [block] stream and build them 
    // ... 

    // then write the build result path to it 
    block.write('buildresult.js');
    block.end();

  })
}))
.pipe(gulp.dest('./build'));
});

gulp build will take index.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Document</title>
  </head>
  <body>

    <!-- htmlbuild:js -->
    <script src="js/script1.js"></script> 
    <script src="js/script2.js"></script> 
    <!-- endbuild -->

  </body>
</html>

And turn it into:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Document</title>
  </head>
  <body>

    <script src="buildresult.js"></script> 

  </body>
</html>

https://www.npmjs.com/package/gulp-htmlbuild

Upvotes: 2

Related Questions