selvam
selvam

Reputation: 1197

How to access preprocess in angularjs

I am working on web application Angularjs with gulp.

Using gulp I am created one environment variable like below

var env = process.env.NODE_ENV  || 'test';

gulp.task('preprocess', function() {
    log('Preprocess..');
    log(env)
    // Minify and copy all JavaScript (except vendor scripts)
    return gulp.src(source.scripts)
        .pipe(preprocess({context:{target:env}}))
});

And this is my gulp output

[11:23:02] Starting 'preprocess'...
[11:23:02] Preprocess..
[11:23:02] test
[11:23:02] Finished 'preprocess' after 370 ms

But I can't access this environment variable inside my angular code. I don't know need to include any plugins are not?

This is my js code for access environment variable

//@ifdef  env='test'
    alert('Environment variable test');
//@endif

//@ifdef  env='local'
alert('Environment variable local');
//@endif    

//@ifdef  env='dev'
alert('Environment variable dev');
//@endif

How can I access the environment variable created by gulp.

Please help me.

Upvotes: 0

Views: 280

Answers (1)

danday74
danday74

Reputation: 57126

I assume you are developing an SPA that serves up index.html.

If so then use a server side HTML templating library to pre-process your HTML. We personally are using jade.

You essentially convert index.html to Jade - giving you index.jade. Create a gulp task to write your Jade to HTML. In the gulp task you can set variables that Jade will use to write the index.html.

In your index.jade do something like ...

<html class="VARIABLE_FROM_GULP_TASK"> <!-- this would be written in Jade -->

your gulp task would do the HTML conversion

then you can check if the class exists or not inside your JavaScript or in your CSS do something like ...

.var_exist .body { color:red }
.var_not_exist .body { color:blue }

note that the value of the variable will be written into the HTML file at build time.

Hope that helps.

Upvotes: 0

Related Questions