node.jsregexgulpgulp-replace

gulp-replace doesn't use an exact match of the search string


I have these two Gulp tasks:

function changeAPIEnvDirectoryForProd() {
    return src('src/app/modules/models/ApiUrl.ts', { base: "src/app/modules/models/" })
    .pipe(replace('../../../environments/environment', '../environments/environment')).pipe(
        dest('src/app/modules/models/', {overwrite: true})
    );
}

function changeAPIEnvDirectoryForLocal() {
    return src('src/app/modules/models/ApiUrl.ts', { base: "src/app/modules/models/" })
    .pipe(replace('../environments/environment', '../../../environments/environment')).pipe(
        dest('src/app/modules/models/', {overwrite: true})
    );
}

Both run depending on the environment, one for production and the other for local development.

I'm having the issue that if in my file I have:

import { environment } from '../../../environments/environment'

export class Apis {
    static bo = `${environment.boAPIUrl}/api/v1/bo`;
}

When I run the changeAPIEnvDirectoryForLocal task it replace the previous code with:

import { environment } from '../../../../../environments/environment'

This is because based on my code it should remain the same. I think the problem is for the replace search this two strings are the same:

../../../environments/environment

and

../environments/environment

Is there anyway to specify an exact match?


Solution

  • The easiest way is to include the ''s in your search term like so:

    .pipe(replace("'../environments/environment'", '../../../environments/environment'))
    

    Now it will look for the full term only. Escaping the ''s so tone ' is included at the beginning and end of your search term also seems to work:

    .pipe(replace('\'../environments/environment\'', '../../../environments/environment'))
    

    By the way, your results are expected, gulp-replace will find '../environments/environment within ../../../../../environments/environment because it is there.

    Finally, you could use a regex with a positive lookbehind to solve your problem another way. Such as

    .pipe(replace(/(?<=')..\/..\/..\/environments\/environment/g, '../../../environments/environment'))
    

    (in a regex your path separators would have to be escaped)