1

I'm having a hard time linking an external script to a single file component in Vue. My application is structured like this:

enter image description here

So the file I want to link to is components/Sshy and the destination file (I believe) would be ../javascripts/

This isn't my first time doing that, and I have other scripts connected that I have successfully referenced in other single file components as either:

../javascripts/<name>
@/javascripts/<name> (Src is aliased) 

Like so:

enter image description here

I'm trying to do the equivalent on a compiled file that isn't well suited to being exported as a module and imported like that. The suggestion I found on a way I could attach this script to a single file component is here.

I tried to copy this method like this:

  mounted () {
     let testScript = document.createElement('script');
     testScript.async = true;
     testScript.type = "text/javascript";
     testScript.setAttribute('src','../javascripts/test.js');
     document.head.appendChild(testScript);
 },

But keep getting an error that seems to indicate it isn't picking up the file right. The error found is

uncaught syntax error: Unexpected token < 

And devtools reports it like it is occurring in the index.html where my vue files get injected. In searches, it looked like the real cause may be the file not being connected properly (Here)

I haven't managed to identify what the issue is still though.

tony19
  • 125,647
  • 18
  • 229
  • 307
JTK
  • 101
  • 3
  • 14

1 Answers1

0

An invalid src path (i.e., ../javascripts/test.js) is likely the problem. Your server is probably configured with an index.html fallback, which is returned for files not found. You can confirm this in your browser's developer tools (find test.js in Network Panel). Since the HTML file (which probably begins with <head>) is sourced into the <script>, you get a JavaScript syntax error for the < character of <head>.

You'll need to update the src path to be relative to the root document and not to the directory of the component.

tony19
  • 125,647
  • 18
  • 229
  • 307