You can use ECMAscript6 and the import
statement is used to import functions that have been exported from an external module. (It means variables too).
Syntax
import defaultExport from "module-name";
import * as name from "module-name";
import { export } from "module-name";
import { export as alias } from "module-name";
import { export1 , export2 } from "module-name";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";
Imports a single member of a module.
Given an object or value named myExport that has been exported from the module my-module either implicitly (because the entire module has been exported) or explicitly (using the export statement), this inserts myExport in the current scope.
import {myExport} from '/modules/my-module.js';
I hope you help greetings.
Note: to use import and to work in all browsers you can use Webpack and Babel since it does not yet have support in all the Browsers
Examples
Import a secondary file to assist in processing an AJAX JSON request.
The module: file.js
function getJSON(url, callback) {
let xhr = new XMLHttpRequest();
xhr.onload = function () {
callback(this.responseText)
};
xhr.open('GET', url, true);
xhr.send();
}
export function getUsefulContents(url, callback) {
getJSON(url, data => callback(JSON.parse(data)));
}
The main program: main.js
import { getUsefulContents } from '/modules/file.js';
getUsefulContents('http://www.example.com',
data => { doSomethingUseful(data); });
Source: MDN