简体   繁体   中英

Access environment variables in handlebar template

I need to access environment variables from a handlebar template. I can use my environment variable elsewhere so I know it's set properly. But after I run browserify my index.html page just shows g.src = process.env.MTM; instead of g.src = myEnvironmentVariable

This is the relevant code within my template:

    <script type="text/javascript">           
        var _mtm = _mtm || [];
        _mtm.push(
        {
            'mtm.startTime': (new Date().getTime()),
            'event': 'mtm.Start'
        });
        var d = document,
            g = d.createElement('script'),
            s = d.getElementsByTagName('script')[0];
        g.type = 'text/javascript';
        g.async = true;
        g.defer = true;
        g.src = process.env.MTM;
        s.parentNode.insertBefore(g, s);
    </script>

I get an error saying process not defined.

(index):28 Uncaught ReferenceError: process is not defined

Is there a way to do this? Am I going about this the wrong way? I need g.src to be set to different URLs depending on what environment I am compiling for.

I figured it out. I just had to pipe it via gulp to the template.

return gulp

    .pipe(hb()            
        .data({
            version: pkg.version,
            date: new Date().toISOString(),
            env: process.env.NODE_ENV,
            mtmUrl: process.env.MTM,
            serverData,
        })           

And then I was a ble to access it like this:

g.src= {{mtmUrl}};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM