change absolute path to relative using gulp

2019-07-25 05:53发布

问题:

In my gulp workflow I have a task that uses npm browser-sync module to serve static files. One of the options of this module is able to set a base directory to let me call js/css/img files etc, and include it using an absolute path like this:

<img src="/imgs/label.png">

this feature let me call this file from any subdirectory I want

/public
---/imgs
------label.png
---/catalog
------list.html   <--- here
---index.html   <--- and here, this image called using the same path /imgs/label.png

this works fine. Otherwise, I have a task that builds the final compressed and minified version of static files. The problem is, that when gulp building a dist folder with that files that located in the public folder, in html files, there's still absolute path in attributes like href/src. I need to convert the absolute path into relative with keeping a folder structure. I mean that in index.html src has to be imgs/label.png, and in catalog/list.html the same src attribute has to be ../imgs/label.png. Question: is there any module that able to do this for me, or maybe there's some another way to do that, instead of replacing the paths with own hands? Any advice would be appreciated.