angulargulp-replacetypescript2.2

Replacing strings in Typescript file with gulp-replace


I'm attempting to insert a build version into my Angular 2 component file, using a gulp-replace task. I'm retrieving the build version from the process variable process.env.npm_package_version. This part is working, as I am able to log the value to the console and get the expected value. However, the gulp-replace portion of my task is not working. I am executing the replace task before anything else.

The task:

const replace = require('gulp-replace');

gulp.task('replace', () => {
    let version = `${process.env.npm_package_version}`;
    gulp.src('src/app/app.component.ts')
        .pipe(replace('buildVersion', version))
        .pipe(gulp.dest('./'));
});

The source:

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl: './app/app.component.html',
    styleUrls: ['./app/app.component.css']
})
export class AppComponent implements OnInit {
    constructor() {}
    ngOnInit() {}
    app = { version: "buildVersion", currentYear: new Date().getFullYear() };
}

Solution

  • gulp dest is wrong. Glad it's fixed.

    By the way, if your intention is:

    1 - to copy to your build folder

    All good, job done, but if your intention is:

    2 - to overwrite original

    then your logic will not work the second time round coz you would have replaced the string "buildVersion" in which case you may need to replace on a regex such as /\d\d.\d\d.\d\d/

    And then the buildVersion in your original file can just be:

    00.00.00

    Then when it is replaced with:

    01.01.44

    the regex will still work the second time round.

    The reason I mentioned it is because you mentioned about the destination being relative to the source which suggests an overwrite to me.