Skip to content
Advertisement

How to import functions from different js file in a Vue+webpack+vue-loader project

(See end for why this is not a dupe of How do I include a JavaScript file in another JavaScript file?)

Javascipt + Vue + webpack + vue-loader noob… stumbling on the simplest of things!

I have App.vue which has a template:

    <template>
     <div id="app">
         <login v-if="isTokenAvailable()"></login>
     </div>
    </template>

I’ve declared the isTokenAvailable method in the normal way for Vue inside methods. It uses a function that I wrote in a separate js file:

<script>
    import * as mylib from './mylib';

    export default {
      ....
        methods:{
            isTokenAvailable: () => {
                return mylib.myfunc();
            }
        }
    }
</script>

mylib starts like this:

    import models from './model/models'
    import axois from 'axios'

    export default function() {
        // functions and constants
    }

When I run the project, I get this below warning:

    export 'myfunc' (imported as 'mylib') was not found in './mylib'

I gather I’m not importing or declaring a javascript module correctly… but there seem to be so many ways to do it, added with the complexity of the scoping in Vue, I’m not sure what is the right way to do it?

Thanks in advance.

Why this isn’t a dupe of: How do I include a JavaScript file in another JavaScript file?

Doesn’t seem to fix the problem, specifically in the context of vuejs.

I have tried this:

<script>
    const mylib = require('./mylib');
    ...
</script>

With the function modified to: exports.myfunc = function()

Should I have some other dependency for this to work? Because I get a different error:

    [Vue warn]: Error in render function:
    TypeError: mylib.myfunc is not a function

Advertisement

Answer

Say I want to import data into a component from src/mylib.js:

var test = {
  foo () { console.log('foo') },
  bar () { console.log('bar') },
  baz () { console.log('baz') }
}

export default test

In my .Vue file I simply imported test from src/mylib.js:

<script> 
  import test from '@/mylib'

  console.log(test.foo())
  ...
</script>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement