[javascript] Import functions from another js file. Javascript

I have a question about including a file in javascript. I have a very simple example:

--> index.html
--> models
      --> course.js
      --> student.js

course.js:

function Course() {
    this.id = '';
    this.name = '';
}

A student has a course property. like this:

import './course';

function Student() {
    this.firstName = '';
    this.lastName = '';
    this.course = new Course();
}

and the index.html is like:

<html>
    <head>
        <script src="./models/student.js" type="text/javascript"></script>
    </head>
    <body>
        <div id="myDiv">
        </div>
        <script>
        window.onload= function() {
            var x = new Student();
            x.course.id = 1;
            document.getElementById('myDiv').innerHTML = x.course.id;
        }
        </script>
    </body>
</html>

But I am getting an error on the line "var x = new Student();":

Student is not defined

When I remove the import from Student, I don't receive the error anymore. I have tried to use (require, import, include, create a custom function, export) and none has worked for me.

Anybody knows why? and how to fix that?

P.S. the path is correct, it comes from the autocomplete in VS Code

This question is related to javascript import

The answer is


From a quick glance on MDN I think you may need to include the .js at the end of your file name so the import would read import './course.js' instead of import './course'

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import


You can try as follows:

//------ js/functions.js ------
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}

//------ js/main.js ------
import { square, diag } from './functions.js';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5

You can also import completely:

//------ js/main.js ------
import * as lib from './functions.js';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5

Normally we use ./fileName.js for importing own js file/module and fileName.js is used for importing package/library module

When you will include the main.js file to your webpage you must set the type="module" attribute as follows:

<script type="module" src="js/main.js"></script>

For more details please check ES6 modules


//In module.js add below code

export function multiply() {
    return 2 * 3;
}

// Consume the module in calc.js

import { multiply } from './modules.js';

const result = multiply();

console.log(`Result: ${result}`);

// Module.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Module</title>
</head>
<body>

  <script type="module" src="./calc.js"></script>
</body>
</html>

Its a design pattern same code can be found below, please use a live server to test it else you will get CORS error

https://github.com/rohan12patil/JSDesignPatterns/tree/master/Structural%20Patterns/module


By default, scripts can't handle imports like that directly. You're probably getting another error about not being able to get Course or not doing the import.

If you add type="module" to your <script> tag, and change the import to ./course.js (because browsers won't auto-append the .js portion), then the browser will pull down course for you and it'll probably work.

import './course.js';

function Student() {
    this.firstName = '';
    this.lastName = '';
    this.course = new Course();
}

<html>
    <head>
        <script src="./models/student.js" type="module"></script>
    </head>
    <body>
        <div id="myDiv">
        </div>
        <script>
        window.onload= function() {
            var x = new Student();
            x.course.id = 1;
            document.getElementById('myDiv').innerHTML = x.course.id;
        }
        </script>
    </body>
</html>

If you're serving files over file://, it likely won't work. Some IDEs have a way to run a quick sever.

You can also write a quick express server to serve your files (install Node if you don't have it):

//package.json
{
  "scripts": { "start": "node server" },
  "dependencies": { "express": "latest" }
}

// server/index.js
const express = require('express');
const app = express();

app.use('/', express.static('PATH_TO_YOUR_FILES_HERE');
app.listen(8000);

With those two files, run npm install, then npm start and you'll have a server running over http://localhost:8000 which should point to your files.