1

I'm trying to integrate Heap's snippet to my VueJS app. But I have a staging and a production environment so the key must be dynamic using .env which is impossible when loading it in index.html. So, I tried to make it a Vue plugin:

//main.js    
import heap from "./plugins/heap";
Vue.use(heap, {key: process.env.VUE_APP_HEAP_ID});

// heap.js
export const heapinit = (e, t) => { [...] } // heap's init script

export default {
    install(Vue, options) {
        heapinit(options.key);
    }
}

This seemed to work as I saw 200s responses from Heap in the network tab showing successful calls. But in the Live data screen on Heap the event's were not captured. I also tried this NPM package called vue-heap that attempts to solve it, but it also has the same issue.

So more generally, what are the best practices for a VueJS app for integrating JS snippets which should not live in index.html but in main.js and that don't have an NPM package? Another example: HubSpot tracking code

I'm learning Vue so feel free to correct any of the above logic if it's wrong! Thank you :)

Fredow
  • 53
  • 4
  • I found also https://stackoverflow.com/questions/46673000/sending-appropriate-data-to-production-or-development-with-heap-analytics-web helpful – ppt Jun 21 '23 at 09:44

1 Answers1

2

You should be able to inject the variables into the index page too. See the docs at: html-and-static-assets

Interpolation

Since the index file is used as a template, you can use the lodash template

syntax to interpolate values in it:

<%= VALUE %> for unescaped interpolation;
<%- VALUE %> for HTML-escaped interpolation;
<% expression %> for JavaScript control flows.

In addition to the default values exposed by html-webpack-plugin, all client-side env variables are also available directly. For example, to use the BASE_URL value:

<link rel="icon" href="<%= BASE_URL %>favicon.ico">
Daniel
  • 34,125
  • 17
  • 102
  • 150
  • Thanks for your answer! Interpolation works well, but is this best way of managing snippets, e.g. would it be better to port them in main.js with Vue.use()? – Fredow Apr 12 '21 at 12:24
  • in short, _it depends_. If what you're making is a _widget_ and will possibly used in other apps and the variable is to be supplied by someone that is implementing the app, this might just be the best way, but usually that's not the case, and having the env variables in js is more common. – Daniel Apr 12 '21 at 16:54
  • Make sense for widgets. I guess I was wondering if transforming the snippet into a Vue plugin had any value rather then having code in index.html using Interpolation. A another option using main.js could be with https://www.npmjs.com/package/vue-plugin-load-script – Fredow Apr 18 '21 at 16:28