since095 since095 - 5 months ago 19
Javascript Question

Load external javascript functions in one function inside main.ts (typescript)

I'm using d3.js, and was hoping anyone could suggest a way to have typescript work like this;

import {loadbarchart} from "./javascript/charts/barchart";
import {loadscatterchart} from "./javascript/charts/scatterchart";

d3.json("data.json", function(error, data) {
loadbarchart();
loadscatterchart();
})


What I'm hoping to do is create several charts in separate files, then just call all of the functions inside the d3.json function inside the main.ts.

When I tried doing this, the
loadbarchart
and
loadscatterchart
are loaded outside of the d3.json function.

From further reading, as I understand it may not be in the scope of typescript to import functions this way?

I was hoping someone could offer some advice on how this can be achieved, if possible?

Thanks

Answer

The concept of modules as a way of organizing the JavaScript-code existed for a long time.Modules in the ECMAScript standard provides a convenient means to do so.

You can put the keyword export:

1.before declaring variables, functions and classes.
2.separately, while in braces indicates that it is exported.

export.file.js

export let one = 1;
export let two = 2;

or

let one = 1;
let two = 2;
export {one, two};

or

export class User {
    constructor(name) {
    this.name = name;
  }
};

export function sayHi() {
  alert("Hello!");
};

import

import {one, two} from "export.file";//it is not necessary to specify extension js
alert( `${one} and ${two}` ); // 1 and 2

When you use

import {loadbarchart} from "./javascript/charts/barchart";
you must be sure that the file javascript/charts/barchart 

 exporte {loadbarchart,loadscatterchart,...};

and only then

 d3.json("data.json", function(error, data) {
    loadbarchart();
    loadscatterchart();
})