Importing a Javascript File Into Another Javascript File

Importing a Javascript File Into Another Javascript File

With modern Javascript (ES6 + ES7 + ES8 + ES9), it is possible to import one javascript file into another.

First create the second file. I will call mine get-data.js and I will make it a sibling of my index.js file. inside get-data.js I will wrap my code inside of an export function like this:

export function get_data() {
     ...
}

Then I will move the function from my index file into this wrapper, also including the d3 dependency I need:

import * as d3 from 'd3';

export function get_data() {
    d3.json("./data/MOCK_DATA.json").then(function(data) {
        data.forEach(function(item) {
            document.write(item.first_name + '<br>');
          });
    });
}

Then in the index.js file, I will import the export function of this new file with bracket syntax, and then call the function:

import * as d3 from 'd3';
import {get_data} from './get-data';

get_data();

That’s it! If you have been continuing with the d3 and json tutorial project I started, The folder structure at this point might look something like this:

Leave a Comment