Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including gulp-replace-image-src with all npm packages installed. Try it out:

var gulpReplaceImageSrc = require("gulp-replace-image-src")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

gulp-replace-image-src v1.0.1

replace the "src" attribute with specific path of "img" tags in HTML files

gulp-replace-image-src Build Status

Replace the "src" attribute of <img> tags with specific path in HTML files.

It is very easy to replace original "src" with a CDN "src".

Installation

Install package with NPM and add it to your development dependencies:

npm install --save-dev gulp-replace-image-src

Usage

var rep = require('gulp-replace-image-src');
var gulp = require('gulp');

gulp.task('replace', function() {
  gulp.src('*.html')
    .pipe(rep({
      prependSrc : '//github.cdn.com/images/',
      keepOrigin : false
    }))
    .pipe(gulp.dest('dist'));
});

The original HTML is like:

<body>
  <div class="icon1"><img src="/public/icon4.png" /></div>
  <div class="icon1_1"><img src="../icon4-1.png" /></div>
</body>

After replaced, it should be like:

<body>
  <div class="icon1"><img src="//github.cdn.com/images/icon4.png" /></div>
  <div class="icon1_1"><img src="//github.cdn.com/images/icon4-1.png" /></div>
</body>

The plugin only keeps the original file name in the new path.

If you want to keep origin "src", then you can make keepOrigin true.

var rep = require('gulp-replace-image-src');
var gulp = require('gulp');

gulp.task('replace', function() {
  gulp.src('*.html')
    .pipe(rep({
      prependSrc : '//github.cdn.com/images',
      keepOrigin : true
    }))
    .pipe(gulp.dest('dist'));
});

Then you will see the below HTML:

<body>
  <div class="icon1"><img src="//github.cdn.com/images/public/icon4.png" /></div>
  <div class="icon1_1"><img src="//github.cdn.com/images/../icon4-1.png" /></div>
</body>

If the "src" starts with "http:|ftp:|https:|//", then it will NOT be replaced.

API

replace(options)

Options, Type: Object.

options.prependSrc

Type:String

Default: /

Prepend the path string to every "src" attribute of "img" tag.

options.keepOrigin

Type:Boolean

Default:false

If the value is true, then the new "src" is prepended to the origin "src".

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free