export import module

pooyaalamdari

pooyaalamdari

Posted on April 18, 2022

export import module

html file
type="module"

    <script src="Person.js" type="module"></script>
    <script src="helpers.js" type="module"></script>
    <script src="modules.js" type="module"></script>
Enter fullscreen mode Exit fullscreen mode

Person.js

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

    sayHello() {
        console.log(`Hi, this is ${this.name}`);
    }
}
Enter fullscreen mode Exit fullscreen mode

helpers.js

function algoExpert() {
    console.log('AlgoExpert is the best!');
}

export function fronendExpert() {
    console.log('fronendExpert is the best!');
}
Enter fullscreen mode Exit fullscreen mode

module.js

import * as helpers from './helpers.js';
import * as person from './Person.js';

helpers.fronendExpert();

const conner = new person.Person('Conner');
conner.sayHello();
Enter fullscreen mode Exit fullscreen mode

Image description

other way to import

import { fronendExpert, algoExpert } from './helpers.js';
import {Person} from './Person.js';

fronendExpert();
algoExpert();

const conner = new Person('Conner');
conner.sayHello();
Enter fullscreen mode Exit fullscreen mode

Image description

use as for change

import { fronendExpert, algoExpert as algo } from './helpers.js';
import {Person} from './Person.js';

fronendExpert();
algo();

const conner = new Person('Conner');
conner.sayHello();
Enter fullscreen mode Exit fullscreen mode

another way to export

function algoExpert() {
    console.log('AlgoExpert is the best!');
}

function fronendExpert() {
    console.log('fronendExpert is the best!');
}

export {algoExpert, fronendExpert};
Enter fullscreen mode Exit fullscreen mode

export default

export default function algoExpert() {
    console.log('AlgoExpert is the best!');
}

export function fronendExpert() {
    console.log('fronendExpert is the best!');
}
Enter fullscreen mode Exit fullscreen mode
import algoExpert, { fronendExpert } from './helpers.js';
import {Person} from './Person.js';

fronendExpert();
algoExpert();

const conner = new Person('Conner');
conner.sayHello();
Enter fullscreen mode Exit fullscreen mode

other way ( use await keyword )

// we don't need this anymore 
// import { fronendExpert } from './helpers.js';

const shouldSayFrontend = true; 

if (shouldSayFrontend) {
    const { fronendExpert } = await import('./helpers.js')
    fronendExpert();
}
Enter fullscreen mode Exit fullscreen mode

Image description

💖 💪 🙅 🚩
pooyaalamdari
pooyaalamdari

Posted on April 18, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related