importing js file code example

Example 1: node import all functions from file

//we are in ./utils/dbHelper.js, here we have some helper functions
function connect() {
  // connect do db...
}

function closeConnection() {
  // close connection to DB...
}

//let's export this function to show them to the world outside
module.exports = {
  connect(),
    closeConnection()
};

// now we are in ./main.js and we want use helper functions from dbHelper.js
const DbHelper = require ('./utils/dbHelper'); // import all file and name it DbHelper
DbHelper.connect(); // use function from './utils/dbHelper' using dot(.)

// or we can import only chosen function(s)
const { connect, closeConnection } = require ('./utils/dbHelper');
connect(); // use function from class without dot

Example 2: javascript using another js file

// module.js
export function hello() {
  return "Hello";
}

// main.js
import {hello} from 'module'; // or './module'
let val = hello(); // val is "Hello";

Example 3: How to add js file to a site through url

var jsFile = document.createElement("script");
jsFile.src = "homePage.js";  // it can be path also  "{themes('/scripts/homePage.js')}"
document.body.appendChild(jsFile);  //append it as src to body