gulp-html-replace icon indicating copy to clipboard operation
gulp-html-replace copied to clipboard

How to find only file name and replace without modify the entire path

Open claudchan opened this issue 6 years ago • 3 comments

Hi, Is it possible to just replace the file name instead replace the entire path? I have issue that the path is dynamically added.

Example:

  <!-- build:app-css -->
  <link rel="stylesheet" href="{% if rootPath %}{{ rootPath }}{% endif %}{% if subPath %}{{ subPath }}{% endif %}css/app.css">
  <!-- endbuild -->

Is there a way to just replace the file name?

After run build, i only need to rename the 'app.css' with suffix 'app.min.css' without changing the path and directory.

claudchan avatar Jul 13 '18 03:07 claudchan

If it turns out that there isn't a way to do this using this package you might want to give gulp-markers a try. gulp-html-replace was my inspiration but gulp-markers is basically a thin wrapper around JavaScript's regex.

The simplest way to do what your looking at is to define some kind of marker in the file, like

<!-- @css -->app.css where app.css is replaced by whatever filename you want.

But what it looks like is your decision - it just needs to be uniquely identifiable by a regular expression.

Then define the marker object and add it to the markers instance.

var markers = new require('gulp-markers')
markers.addMarker({
  tag: 'css-replacement',           // this is for your context only
  re: /<!-- @css -->(\S+) /,        // this just finds your marker defined above
  // the arguments of the function are context (tag, et al), the match, and the groups
  replace: function (context, match, filename) {
    return filename                    // this is what replaces the matched expression
  }
})

You can get more sophisticated by putting all the expressions in a block but that requires writing a pretty ugly regex or doing replace-function regex processing on each line within the block.

Apologies to Vladimir if this is inappropriate; I'm happy to delete this comment. I don't recall whether what is being asked is easy to do or not but I ended up writing gulp-markers based on your idea because I kept finding odd corner cases I wanted to address.

bmacnaughton avatar Jul 13 '18 05:07 bmacnaughton

Thanks but kind of complicated. Is there any cleaner way or is there a gulp plugin can do such thing easily?

claudchan avatar Jul 18 '18 01:07 claudchan

I think i found a good solutions, using gulp-replace. Now i can find all src '*.html' and find replace 'app.css' with 'app.min.css'.

claudchan avatar Jul 18 '18 01:07 claudchan