16 A real application (1) App skeleton

 The application is for the simple management of a cemetery.

1. The basics. Installation

Install VS Code, npm and nodejs. 

Install "Live Server" in VS Code. Press Control-P and copy "ext install ritwickdey.LiveServer"

Open VS Code and execute these commands in the terminal window as mentioned in a previous post

# create the project folder
mkdir webpack-jq

cd webpack-jq

# create the package.json and ask for project basic info 
npm init -y

# install webpack and cli (opt -D is equivalent to --save-dev )
npm i -D webpack webpack-cli
# create the folder src (sources folder) mkdir src #create the index.js empty file touch src/index.js

# execute webpack (and complains about no mode selected (development or production)
npx webpack 

# install the ts compiler and ts-loader for webpack
npm i --save-dev typescript ts-loader

# create the file tsconfig.json
npx tsc --init

# import the jquery modules from the node repo
npm i -D jquery @types/jquery

# import the jquery-ui modules from node repo
npm i -D jquery-ui @types/jqueryui

# import the webpack copy plugin
npm i -D copy-webpack-plugin


# import bootstrap and styles modules from the node repo
npm i -D bootstrap @types/bootstrap @popperjs/core css-loader style-loader sass sass-loader


1.1 File webpack.config.js

Create the file webpack.config.js in the project folder with this code

module.exports = {
mode: process.env.NODE_ENV || 'production',
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
use: {
loader: 'ts-loader'
},
{
test: /\.(sc|c)ss$/i,
use: ["style-loader", "css-loader"],
},
]
},

devtool: false,

resolve: {
extensions: ['.ts', '.js']
}
}

the mode may be development or production

By default, the src folder is for the sources, and the main module is main.ts as typescript has been selected.

The devtool:false is for not generating so much "stuff code"

1.2 Other files (tsconfig.json and package.json, yet existing)

The file tsconfig.json file will not be edited at least for now

The file package.json indicates the plugins that have been installed.

{
  "name": "cm01",
  "version": "1.0.0",
  "description": "cementeri",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "NODE_ENV=production webpack && mkdir -p dist && cp src/*.html dist && cp src/*.css dist && cp -r src/images dist && cp -r src/json dist"
}, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@types/jquery": "^3.5.14", "jquery": "^3.6.0", "ts-loader": "^9.3.0", "typescript": "^4.7.3", "webpack": "^5.73.0", "webpack-cli": "^4.9.2" } }

the scripts part

"build": "NODE_ENV=production webpack && mkdir -p dist && cp src/*.html dist && cp src/*.css dist && cp -r src/images dist && cp -r src/json dist"

 is very important as copies folders and files to "dist" folder.

2. tsconfig.json

This file is important, and  in this case, "json" files have been used. Note "resolveJsonModule": true ,

{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */

/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */

/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */

/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
"resolveJsonModule": true, /* Enable importing .json files. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */

/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */

/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}




3. Hands-on

Create three folders in the src folder (class, images and json)

3.1 Create the class src/class/Tram.ts

Tram represents a "section".  The attributes are:

tram: the number of the section

nv: "N" for new and "V" for old

point1: Upper left coordinates (x,y)

point2 : Lower right coordinates (x,y)

export class Tram {
    tram: number
    nv: string
    bis: string
    point1: number[]
    point2: number[]

    public constructor (tram: number, nv: string, bis: string, point1: number[], point2: number[]) {
        this.tram=tram
        this.nv=nv
        this.bis=bis
        this.point1=point1
        this.point2=point2
    }
}

3.2 Create the file src/json 

The content of the file has all the section (Trams) values in json format: 

[
 "1;V;;839;772;867;846",
 "2;V;;839;846;868;921",
 "3;V;;840;922;867;996",
 "4;V;;840;998;867;1071",
 "5;V;;839;1072;867;1147",
 "6;V;;838;1148;867;1223",
 "7;V;;838;1223;868;1299",
 "8;V;;839;1297;868;1372",
 "9;V;;839;1373;898;1405",
"10;V;;781;1469;868;1497",
"11;V;;694;1467;780;1496",
"12;V;;608;1467;692;1496",
"13;V;;383;1467;450;1498",
"14;V;;317;1467;384;1497",
"15;V;;250;1467;316;1498",
"16;V;;182;1467;248;1498",
"7;V;;150;1397;181;1467",
"18;V;;150;1329;180;1397",
"19;V;;150;1258;181;1328",
"20;V;;247;1377;316;1407",
"21;V;;316;1378;384;1408",
"22;V;;323;1378;692;1407",
"23;V;;557;1380;622;1406",
"24;V;;623;1379;692;1408",
"25;V;;692;1379;760;1407",
"26;V;;692;1349;759;1377",
"27;V;;622;1349;690;1377",
"28;V;;554;1348;622;1378",
"29;V;;384;1350;451;1379",
"30;V;;316;1350;383;1377",
"31;V;;247;1349;316;1378",
"32;V;;248;1272;315;1301",
"33;V;;315;1272;383;1300",
"34;V;;385;1273;452;1301",
"35;V;;555;1273;622;1301",
"36;V;;624;1273;691;1300",
"37;V;;693;1273;759;1301",
"38;V;;690;1243;760;1272",
"39;V;;624;1243;691;1271",
"40;V;;555;1243;622;1271",
"41;V;;384;1243;451;1271",
"42;V;;315;1243;384;1271",
"43;V;;248;1243;315;1272",
"44;V;;149;1189;180;1258",
"45;V;;150;1120;181;1188",
"46;V;;150;1051;180;1120",
"47;V;;150;981;180;1050",
"48;V;;152;912;179;982",
"49;V;;151;844;178;911",
"50;V;;150;772;181;842",
"51;V;;149;705;181;773",
"52;V;;149;633;180;703",
"53;V;;150;565;180;635",
"54;V;;149;495;180;565",
"55;V;;150;425;179;494",
"56;V;;150;355;180;426",
"57;V;;150;286;180;354",
"58;V;;181;245;252;286",
"59;V;;253;245;324;286",
"60;V;;324;244;396;285",
"61;V;;398;246;468;286",
"62;V;;468;244;540;286",
"63;V;;542;245;612;285",
"64;V;;216;1160;325;1194",
"65;V;;326;1160;435;1194",
"66;V;;590;1160;696;1195",
"67;V;;696;1160;801;1196",
"68;V;;612;245;685;285",
"69;V;;684;244;756;286",
"70;V;A1;760;1350;790;1407",
"70;V;A2;760;1243;790;1301",
"70;V;A3;216;1348;247;1407",
"70;V;A4;217;1243;246;1302",
"71;V;;757;245;828;286",
"72;V;;216;317;302;346",
"73;V;;216;346;302;376",
"74;V;;216;422;302;452",
"75;V;;216;452;303;482",
"76;V;;216;530;302;560",
"77;V;;217;559;304;588",
"78;V;;839;597;867;681",
"79;V;;869;1306;897;1371",
"80;V;;839;422;868;509",
"81;V;;839;336;867;421",
"1;N;;868;1304;898;1372",
"2;N;;869;1236;898;1304",
"3;N;;869;1167;896;1233",
"4;N;;869;1099;897;1166",
"5;N;;869;1030;896;1097",
"6;N;;868;960;896;1028",
"7;N;;868;892;896;959",
"8;N;;869;824;896;890",
"9;N;;867;773;896;822",
"10;N;;948;246;1019;286",
"11;N;;1019;245;1093;285",
"12;N;;1095;247;1165;285",
"13;N;;869;624;897;682",
"14;N;;869;567;899;625",
"15;N;;868;509;898;567",
"16;N;;869;451;896;507",
"17;N;;869;392;897;449",
"18;N;;869;336;897;393",
"19;N;;956;335;984;420",
"20;N;;985;335;1014;420",
"21;N;;956;422;984;508",
"22;N;;986;423;1013;508",
"23;N;;956;509;986;596",
"24;N;;985;507;1016;596",
"25;N;;957;596;984;682",
"26;N;;986;599;1014;683",
"27;N;;1073;334;1102;422",
"28;N;;1102;334;1130;421",
"29;N;;1074;422;1102;507",
"30;N;;1104;423;1131;508",
"31;N;;1073;508;1103;593",
"32;N;;1103;509;1131;594",
"33;N;;1074;597;1102;683",
"34;N;;1102;596;1132;683",
"35;N;;1198;334;1226;403",
"36;N;;1229;337;1255;404",
"37;N;;1200;405;1227;474",
"38;N;;1228;405;1257;474",
"39;N;;1199;476;1227;546",
"40;N;;1228;475;1257;547",
"41;N;;1198;547;1227;616",
"42;N;;1230;549;1256;616",
"43;N;;1323;336;1350;421",
"44;N;;1350;334;1380;422",
"45;N;;1324;422;1351;509",
"46;N;;1352;423;1380;508",
"47;N;;1323;512;1352;596",
"48;N;;1351;509;1380;595",
"49;N;;1323;597;1351;682",
"50;N;;1351;596;1380;682",
"51;N;;956;772;985;847",
"52;N;;985;773;1017;848",
"53;N;;1080;773;1156;814",
"54;N;;1080;814;1195;845",
"55;N;A;1930;262;2030;290",
"55;N;B;2069;260;2114;290",
"56;N;A;1930;335;2030;364",
"56;N;B;2068;334;2114;362",
"57;N;;1;428;773;1458;846",
"58;N;;1508;246;1562;287",
"59;N;;1440;248;1509;288",
"60;N;;1323;247;1439;287",
"61;N;;1251;813;1365;844",
"62;N;;1428;772;1459;846",
"63;N;;1459;774;1489;846",
"64;N;;1288;773;1366;813",
"65;N;A;2227;262;2333;291",
"65;N;B;2148;263;2193;290",
"66;N;A;2229;336;2333;364",
"66;N;B;2146;334;2191;362",
"67;N;;2367;263;2398;334",
"68;N;;1167;247;1321;285",
"69;N;;956;848;985;1098",
"70;N;;1079;1062;1207;1096",
"71;N;;1079;1025;1207;1059",
"72;N;;986;847;1017;1096",
"73;N;;1930;365;1960;482",
"74;N;;1930;482;2131;512",
"75;N;;1929;555;2130;585",
"76;N;;1863;335;1893;584",
"77;N;;955;1465;1011;1497",
"78;N;;1011;1466;1068;1498",
"79;N;;1068;1465;1126;1497",
"80;N;;1238;1024;1366;1061",
"81;N;;1238;1060;1365;1095",
"82;N;;1430;848;1459;1096",
"83;N;;1459;847;1489;1096",
"84;N;;2132;484;2333;511",
"85;N;;2128;555;2331;585",
"86;N;;2366;334;2397;585",
"87;N;;2300;365;2332;482",
"88;N;;1436;335;1463;509",
"89;N;;1462;335;1488;508",
"90;N;;1437;509;1462;683",
"91;N;;1463;509;1489;683",
"92;N;;957;1371;1192;1402",
"93;N;;956;1340;1192;1371",
"94;N;;1547;337;1586;509",
"95;N;;1546;509;1585;683",
"96;N;;1249;1144;1284;1403",
"97;N;;1283;1145;1317;1403",
"98;N;;1425;1144;1456;1402",
"99;N;;1458;1144;1489;1403",
"100;N;;1544;773;1585;1095",
"101;N;;1548;1143;1585;1403",
"102;N;;1295;1463;1585;1497",
"103;N;;1355;1192;1389;1290",
"104;N;;1354;1289;1389;1402",
"105;N;;1593;246;1683;279",
"106;N;;1587;339;1688;374",
"107;N;;954;1498;1193;1529"
]


3.3 Insert this image in the file src/images/cementery.v1.jpg

You can download this image, by clicking on it.




3.4 Insert the file src/index.html

This file has this content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cementeri</title>
</head>
<body>
    <img id="myImg" src="./images/cementeri.v1.jpg" 
    width="2482" height="1755" alt="Cementeri" 
 	title="ea!" usemap="#mymap"> 
 	
   
    <map name="mymap" id="mymap">
        <!--
        <area shape="rect" coords="650,0,978,500" href="somepage.html" alt="rightpart" title="title01">
        <area shape="circle" coords="90,58,3" href="acircle.html" alt="aCircle"title="title02">
        -->
    </map>
    --> 
    <p id="displayArea"></p>
    
    <textarea id="tarea" rows=20 cols=50></textarea>

    <script src="./main.js" ></script>
</body>
</html>


3.5 Insert the file src/index.ts

This file has this content: (take care of the commented code, as can be confusing) but they are important as one can detect

import $ from "jquery"
//import * as fs from "fs" --> No es pot fer ja que no es pot escriure ni al server ni al client
import myarr from "./json/trams.json"
import {Tram} from "./class/Tram"


var aPos: number[]
var tram=79
var nclick=0;
var bis="" //"-B"
var info=""


var trams:Tram[]=[]
for(var i = 0; i < myarr.length; i++)
{ 
    //console.log(myarr[i]); // 
    let ss=myarr[i].split(";")
    let _tram:number=+ss[0].trim()
    let _nv:string=ss[1].trim()
    let _bis:string=ss[2].trim()
    let _point1:number[]=JSON.parse(ss[3].trim())
    let _point2:number[]=JSON.parse(ss[4].trim())
    let tram = new Tram( _tram, _nv, _bis, _point1, _point2)
    //alert(JSON.stringify(tram))
    trams.push(tram)
    //if (++i%10 ==0) var pp = window.prompt("hola" + i +"\n",JSON.stringify(trams))
    //if (++i%10 ==0) var pp = window.prompt("hola" + i +"\n")
    //console.log(""+i+"-->"+JSON.stringify(tram))
    $("#mymap").append(
        "<area shape='rect' coords='"+ 
            tram.point1[0] +"," +tram.point1[1] +"," +
            tram.point2[0] +"," +tram.point2[1] +
            "' title='" + tram.nv +" -"+tram.tram + "-"+tram.bis+"'>\n"
    )        
}


//<area shape="rect" coords="650,0,978,500" href="somepage.html" alt="rightpart" title="title01">
/* FOR getting coordinates
$("#myImg")
    .attr("title",""+(tram+1)+"-"+(nclick+1))
    .on("mousemove", function(e) {
    
        var x:number=0
        var y:number=0
    
        //Positions
        let px =e.clientX 
        let py =e.clientY 
    
        if (px) x+=px
        if (py) y+=py

        //Scroll positions
        let crlx= $(document).scrollLeft()  
        let crly= $(document).scrollTop()

        if (crlx) x+=crlx
        if (crly) y+=crly

        aPos=[ Math.round(x), Math.round(y)]

        /*
        let ee = $(e.target)
        ee.attr("title",""+(tram+1))
        *//*
        
    })

    .on ("click", function (e){
        
        if (nclick==0) info= JSON.stringify(aPos) 
        else {
            info =(++tram) + bis + ";" + info + ";" + JSON.stringify(aPos) + "\n"
             $("#tarea").val($("#tarea").val() + info)
        }
        nclick++
        if (nclick>1) nclick=0

        
        $(e.target).attr("title",""+(tram+1)+"-"+(nclick+1))
         
    })

   */

4. Project structure 



5. Running

if we run in the terminal


# build the project using the script "build" from the package.json
npm run build

but our html file has not been copied to the dist folder. So copy it manually!!!

and execute the html file (dist/index.html) in the "live server"







Comentarios

Entradas populares de este blog

14 Typescript (2) with jquery, bootstrap and other module stuff

05. Resource bundles (i18n)

03. Servlets, Filters and Listeners