Reputation: 53
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 :)
Upvotes: 1
Views: 1006
Reputation: 35714
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">
Upvotes: 2