Search code examples
javascriptember.jsconfigurationplaid

How can I vendor a 3rd party js lib via a script tag in Ember?


I'm trying to integrate Plaid with an Ember app and am following the instructions on their site. It should be simple, the instructions say to just add

<script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js" />

and it'll give you a Plaid class that can be used to interface with Plaid.

That works fine, but ideally I'd like to vendor this script and import it in a service where I can do my work on it. This does not work out of the box. Unfortunately, this script relies on being embedded with a script tag. If you unminify the thing, there's a line where it very explicitly tries to find the script tag that embedded it, and it throws an error if it can't find it.

From the unminified code:

findScriptTag: function() {
  for (var t = document.getElementsByTagName("script"), n = 0, e = t.length; n < e; n += 1)
    if (/link-initialize(\..*?)?\.js$/.test(t[n].src)) return t[n];
  throw new Error("Failed to find script")

My question is, can I configure ember to load certain vendored scripts separately from everything else, in its own script tag? I'd also need to control the name of the file, since the above expects the name to be link-initialize.js. Or is there another way around this?

My current workaround is to just add the script tag to index.html, but I'd really like to be able to say import Plaid from 'plaid';, or something close to that... Unit testing is impossible without this.


To clarify: As far as I know, there is no npm package for this. https://www.npmjs.com/package/plaid is a backend lib that does not handle embedding Plaid on the page. It is entirely different from the link-initialize.js script the plaid docs say to embed.


Solution

  • You can put it in the public folder. This will ensure ember-cli will copy it into your build output 1:1. Then add the script tag like <script src="/link-initialize.js" /> to your index.html and it should work.

    If you insist to keep the file in the vendor folder you can use broccoli Funnel and MergeTrees inside ember-cli-build.js to copy it to the dist folder and use the same script tag.


    about the import: you can create a vendor-shim. Just do ember generate vendor-shim plain. In the vendor shim just return the global variable provided by link-initialize.js. Then you can import this.