2022年6月21日 星期二

[module, javascript, browser] How to create a javascript module

 How to create a javascript module

井民全, Jing, mqjing@gmail.com


Key

# Usage

File: index.html

...

<script type="module" src="index.js"> <!-- Identify the index.js as an ECMAScript -->



File: index.js

import {var} from 'the-javascript-module' // import the module


// Module

File: ./modules/my-module.js

class myClass {

}

function myFunAbc(){

}

export {myClass, myFunAbc}





Usage

File: index.js

import { myClass, myFunAbc } from './modules/my_module.js'


myFunAbc();

var obj = new myClass();

obj.print();




File: index.html

<!doctype html>

<html lang="en">


<head>

    <link rel="icon" type="image/x-icon" href="/images/favicon.ico">

</head>


<body>

    <h1>Test</h1>


    <!-- using module syntax to identify the source javascript is a ECMAScript that support the import keyword-->


    <script type="module" src="index.js"> 

    </script> 


</body>

</html>


Module

File: ./modules/my_module.js


'use strict';

class myClass {

    constructor() {

        console.log("my_module::myClass::constructor");

    }


    print() {

        console.log("my_module::myClass::print");

    }

}


function myFunAbc() {

    console.log("my_module::myFunAbc()");

}


export {myClass, myFunAbc}



Result


Reference

  1. https://openhome.cc/Gossip/ECMAScript/ScriptModule.html