Home > database >  Importing Objects from different files in JavaScript Project
Importing Objects from different files in JavaScript Project

Time:05-21

I am complete beginner in JavaScript and web-dev. Most of my programming experience comes from Python and so I am very comfortable with the way python files can be arranged in different folders as modules and can play sort of a plug and play role. So far I am unable to discover that flexibility in JS.

Here is my current project structure:

-root
 |-index.html
 |-app.js
 |-modules
   |-test.js

Here is my index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>My Project</title>

  </head>

  <body>
    <script src="app.js"></script>
  </body>
</html>

My app.js:

let hello = Hello()

Finally my modules/test.js:

class Hello(){
  constructor(){
    console.log('Hello World');
  }
}

When I run it I get the error message: Uncaught ReferenceError: Hello is not defined at app.js:1:1

What do I do to achieve my desired results? Regards.

CodePudding user response:

You need to export the function from test.js and import it in app.js

CodePudding user response:

Have you tried:

modules/test.js:

export class Hello(){
  constructor(){
    console.log('Hello World');
  }
}

app.js:

import { Hello } from './modules'

let hello = new Hello()

Or, if you use the expor default, do not need the curly braces, as you do not need to secify what you are exporting. Like so:

modules/test.js:

export default class Hello(){
  constructor(){
    console.log('Hello World');
  }
}

app.js:

import Hello from './modules'

let hello = new Hello()
  • Related