Skip to content Skip to sidebar Skip to footer

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: f

Solution 1:

The following works for me in Firefox and Chrome. In Firefox it even works from file:///

models/course.js

exportfunctionCourse() {
    this.id = '';
    this.name = '';
};

models/student.js

import { Course } from'./course.js';

exportfunctionStudent() {
    this.firstName = '';
    this.lastName = '';
    this.course = newCourse();
};

index.html

<divid="myDiv"></div><scripttype="module">import { Student } from'./models/student.js';

    window.onload = function () {
        var x = newStudent();
        x.course.id = 1;
        document.getElementById('myDiv').innerHTML = x.course.id;
    }
</script>

Solution 2:

You can try as follows:

//------ js/functions.js ------exportfunctionsquare(x) {
    return x * x;
}
exportfunctiondiag(x, y) {
    returnsqrt(square(x) + square(y));
}

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

You can also import completely:

//------ js/main.js ------import * as lib from'./functions.js';
console.log(lib.square(11)); // 121console.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:

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

For more details please check ES6 modules

Solution 3:

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';

functionStudent() {
    this.firstName = '';
    this.lastName = '';
    this.course = newCourse();
}

<html><head><scriptsrc="./models/student.js"type="module"></script></head><body><divid="myDiv"></div><script>window.onload= function() {
            var x = newStudent();
            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.jsconst 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.

Solution 4:

//In module.js add below codeexportfunctionmultiply() {
    return2 * 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><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><metahttp-equiv="X-UA-Compatible"content="ie=edge"><title>Module</title></head><body><scripttype="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

Solution 5:

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

Post a Comment for "Import Functions From Another Js File. Javascript"