Bes Ley
Bes Ley

Reputation: 1797

How to import an external js file in Quasar project

In early javascript project, we have created a file named kresource.js, its code is below

//kresource file, contains some functions
var kresource = (function () {
    function kresource () {
    }
    kresource.getLang = function () {
      console.log('en')    //it's only a sample...
    }
    return kresource
})()

When in a html page, we can access the function by kresource.getLang(), but in a Quasar vue page, how can I import this file, and access the function?

//index.vue file
import kresource from '../js/kresource.js'

[Vue warn]: Error in created hook: "TypeError: _js_kresource_js__WEBPACK_IMPORTED_MODULE_0___default.a.getLang is not a function"

Upvotes: 0

Views: 4095

Answers (1)

Roberto Langarica
Roberto Langarica

Reputation: 729

It isn't working because you need to use that code as a module instead of relying on var being global.

You need to add an export to your file. At the end of the file you need to put:

export default kresource

And in the file where you plan to use it:

import kresource from 'path to the file'

Notes: You can read more about modules in JS so you can understand better what is hapening, and also instead of var use const, since that variable is never reasigned and it is better to maintain the global scope cleaner.

Upvotes: 2

Related Questions