17

I want to use a javascript class in may Vue application.

My class looks like:

class className { 
   constructor() { 
       ... 
   }  

   function1() { 
       ... 
   }  

   static funtion2() {
        ... 
   } 
}

I tried to import this class in my application like:

  • import className from './fileName.js';
  • var {className} = require('./fileName.js')

In all cases I receive when I want to call a function of the class (className.function2()): the function is undefined.

8
  • 3
    do not forget to export you "class" from the module where it is declared Commented May 7, 2018 at 13:09
  • Did you spell require right? Commented May 7, 2018 at 13:09
  • you said function2 does not work, does function1 work? Commented May 7, 2018 at 13:09
  • do you use webpack or similar? Commented May 7, 2018 at 13:10
  • @GibboK - did you mean to export the class where I imported? I'm using from the same module. I'm using webpack. Commented May 7, 2018 at 13:11

3 Answers 3

22

You need to export the class to be able to import/require it

//1. For import syntax
export default class className {...}

//2. For require syntax
class className {}
module.exports.className = className
//or
module.exports = {
    className: className
}
Sign up to request clarification or add additional context in comments.

1 Comment

This didn't work for me. I see "module.exports" is undefined for me. Unable to set module.exports.MyClass = MyClass TypeError: Cannot set property 'MyClass' of undefined
9

Using import/export, you'd use

export class className {}

and

import {className} from '<file>';

Comments

0

Compare to @baao answer, I add the default keyword for the export.

export default class className {}

and in the component.vue file:

<script>
import className from '<pathToFile>';
...
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.