Typescript. Modules

Modules also created to group out code. Lets look at example

hi.ts // this will be the module

export default function sayHi() {
    console.log('hi, there');
}

index.ts

import sayHi from "./hi.js";

sayHi();

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Modules!</title>
</head>
<body>

<h2>please look at console</h2>

<script type="module" src="index.js"></script>
</body>
</html>

in tsconfig.js lets define format of modules

{
  "compilerOptions": {
    "module": "esnext", // << --- here
    "target": "es2015",
    "sourceMap": true
  },
  "exclude": [
    "node_modules"
  ]
}

Now lets execute tsc index.ts in terminal, and will get hi.js files and index.js files

Modules are loaded using ajax, so we need simple server, lets use node.js

const http = require("http");
const fs = require("fs");

http.createServer(function (request, response) {

    let filePath = request.url.substr(1);
    if (filePath == "") filePath = "index.html";
    fs.readFile(filePath, function (error, data) {
        if (error) {
            response.statusCode = 404;
            response.end("Resourse not found!");
        } else {
            if (filePath.endsWith(".js")) response.setHeader("Content-Type", "text/javascript");
            response.end(data);
        }
    });
}).listen(3000, function () {
    console.log("Server started at 3000");
});

now lets start the browser with

node server.js

and here we are

HOW ELSE WE CAN IMPORT / EXPORT MODULES ?

export {Device, Phone, call};
import {Phone, call} from "./devices";

import {Phone, call as makeCall} from "./devices.js";

export {Device, Phone, call as makeCall};

import * as dev from "./devices.js"; // import all module

// default export
export default Smth(){}

// import default
import Smthfrom "./something.js";
This entry was posted in Без рубрики. Bookmark the permalink.