Importing javascript file for use within vue component
Asked Answered
K

5

52

I am working on a project that requires using a js plugin. Now that we're using vue and we have a component to handle the plugin based logic, I need to import the js plugin file within the vue component in order to initialize the plugin.

Previously, this was handled within the markup as follows:

<script src="//api.myplugincom/widget/mykey.js
"></script>

This is what I tried, but I am getting a compile time error:

MyComponent.vue

import Vue from 'vue';
import * from  '//api.myplugincom/widget/mykey.js';

export default {
    data: {

My question is, what is the proper way to import this javascript file so I can use it within my vue component? ...

Kimber answered 24/1, 2018 at 16:13 Comment(4)
Can you be more precise on the tooling you are using npm / webpack ... ? And which lib do you require, internal / external ?Antigorite
Its an external lib and I am using laravel-mix for compiling. If possible, I'd like whatever import logic to be vue component specific :)Kimber
import something from path. Path is resolve at compile time so you need to reference a file in your local directory. Not the end of an URI.Antigorite
what error message? if you want to use methods included in the library you need named type of import developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… import * as myModule from '//api.myplugincom/widget/mykey.js'; also, your path is wrongLavern
P
78

Include an external JavaScript file

Try including your (external) JavaScript into the mounted hook of your Vue component.

<script>
export default {
  mounted() {
    const plugin = document.createElement("script");
    plugin.setAttribute(
      "src",
      "//api.myplugincom/widget/mykey.js"
    );
    plugin.async = true;
    document.head.appendChild(plugin);
  }
};
</script>

Reference: How to include a tag on a Vue component

Import a local JavaScript file

In the case that you would like to import a local JavaScript in your Vue component, you can import it this way:

MyComponent.vue

<script>
import * as mykey from '../assets/js/mykey.js'

export default {
  data() {
    return {
      message: `Hello ${mykey.MY_CONST}!` // Hello Vue.js!
    }
  }
}
</script>

Suppose your project structure looks like:

src
- assets
    - js
      - mykey.js
- components
    MyComponent.vue

And you can export variables or functions in mykey.js:

export let myVariable = {};
export const MY_CONST = 'Vue.js';
export function myFoo(a, b) {
    return a + b;
}

Note: checked with Vue.js version 2.6.10

Pussyfoot answered 3/5, 2018 at 15:58 Comment(5)
Thanks. It was helpful. Worked well. Also the reference helped a lot.Fortyish
best copy past from SO to date !Azeotrope
The MyComponent.vue code looks faulty. An import inside an export?Demean
@Demean Yes, you're right. import should be put outside export. I updated accordingly. Thanks.Pussyfoot
How would I access the external JavaScript file in the methods property if it is defined as const plugin inside the mounted hook?Bookout
M
2

try to download this script
import * from '{path}/mykey.js'.
or import script
<script src="//api.myplugincom/widget/mykey.js"></script> in <head>, use global variable in your component.

Marrilee answered 24/1, 2018 at 16:51 Comment(0)
G
0

For scripts you bring in the browser way (i.e., with tags), they generally make some variable available globally.

For these, you don't have to import anything. They'll just be available.

If you are using something like Webstorm (or any of the related JetBrains IDEs), you can add /* global globalValueHere */ to let it know that "hey, this isn't defined in my file, but it exists." It isn't required, but it'll make the "undefined" squiggly lines go away.

For example:

/* global Vue */

is what I use when I am pulling Vue down from a CDN (instead of using it directly).

Beyond that, you just use it as you normally would.

Gravure answered 24/1, 2018 at 16:24 Comment(4)
I appreciate the help. This doesn't work however. I am currently importing the script the 'browser way' and the script code isn't able to initialize within the vue component.Kimber
It should be. Without knowing exactly what you're using, it's hard to say, but can you access whatever-the-thing-is from the browser console? Also, load-order matters. You have to make sure what it is is loaded before you try to run your Vue code. Just having it's script tag above the one with Vue code should be enough.Gravure
Also you can just add external libraries into PHPStorm / WebStorm in settings -> Languages & Frameworks -> JavaScript -> Libraries. Then you get code hinting :) i.imgur.com/DVNXDpF.pngKeven
Indeed. Webstorm and friends will also give a squiggly on the <script> itself saying there isn't a local version. You can hit Alt+Enter on that to do the same.Gravure
I
0

I wanted to embed a script on my component and tried everything mentioned above, but the script contains document.write. Then I found a short article on Medium about using postscribe which was an easy fix and resolved the matter.

npm i postscribe --save

Then I was able to go from there. I disabled the useless escape from eslint and used #gist as the template's single root element id:

import postscribe from 'postscribe';
export default {
    name: "MyTemplate",
    mounted: function() {
        postscribe(
          "#gist",
          /* eslint-disable-next-line */
          `<script src='...'><\/script>`
        );
      },

The article is here for reference: https://medium.com/@gaute.meek/how-to-add-a-script-tag-in-a-vue-component-34f57b2fe9bd

Irons answered 7/5, 2020 at 16:9 Comment(0)
F
0

For anyone including an external JS file and having trouble accessing the jQuery prototype method(s) inside of the loaded script.

Sample projects I saw in vanilla JS, React and Angular were simply using:

$("#someId").somePlugin(options) or window.$("#someId").somePlugin(options)

But when I try either of those in my VueJS component I receive:

Error: _webpack_provided_window_dot$(...).somePluginis not a function

I examined the window object after the resources had loaded I was able to find the jQuery prototype method in the window.self read-only property that returns the window itself:

window.self.$("#someId").somePlugin(options)

Many examples show how to load the external JS file in VueJS but not actually using the jQuery prototype methods within the component.

Francinefrancis answered 18/12, 2021 at 0:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.