Cypher Cypher - 1 year ago 92
Javascript Question

Change some html code into antoher with GULP

Thank you for checking my question. This may sound trivial but I need help here.

I want to learn how to change HTML code with GULP. Or just change some strings with GULP. For example today I need to change this:

<img class="social" src="../symbols/facebook.svg">

to this:

<svg class="social">
<use xlink:href="../symbols/sprite.svg?v201608061556#facebook"></use>

As you can see I am building icon system via symbols and I want to keep my original HTML clean as it can be. So I can work without any watchers and such. Later I just run GULP once and it does the job: create sprite and change HTML to use this sprite.

I tried gulp-replace and it can change one string to another with regex, but it looks too complicated for me with regex. I am not even sure that it is possible to do with regex. And I also want to add timestamp as ?v201608061556. So I want to run some JavaScript that I can write in gulp file.

Next one I tried is gulp-dom and it looks like the thing I need. But I can't make it work due to some errors:

if (node.nodeType === NODE_TYPE.DOCUMENT_NODE) {
TypeError: Cannot read property 'nodeType' of undefined

Error log in terminal:
gulp-dom error output

So the questions is:

  1. Is it possible to make with regex and gulp-replace package?

  2. Does anyone know gulp-dom
    package. Can I make it work somehow? Is it possible to complete my
    task with it?

  3. Is there another way to write JavaScript in Gulp task
    so I can take a string, process it according to my needs with all JavaScript functionality and save?

  4. Can I work with HTML from Gulp the same way
    I work when I code websites? Work with DOM, use
    querySelector and classList for example? Maybe jQuery?


Answer Source

Ok, I found a gulp-change. It gives you file content as a string. You can do everything you want with that string with javascript and then return it back to pipe.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download