├── .DS_Store
├── .editorconfig
├── .eslintignore
├── .eslintrc
├── .gitignore
├── .idea
├── .gitignore
├── jsLibraryMappings.xml
├── misc.xml
├── modules.xml
├── runConfigurations.xml
└── vcs.xml
├── LICENSE
├── READMe.md
├── nodemon.json
├── package.json
├── src
├── main.ts
└── mod
│ └── utils.ts
├── ts-init.sh
├── ts-node-init.iml
├── tsconfig.eslint.json
└── tsconfig.json
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/ts-node-init/e3368c24d4eec6788837554f2ab4d9a1e5234a98/.DS_Store
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | indent_style = space
5 | indent_size = 2
6 | charset = utf-8
7 | trim_trailing_whitespace = true
8 | insert_final_newline = true
9 | end_of_line = lf
10 | # editorconfig-tools is unable to ignore longs strings or urls
11 | max_line_length = 180
12 |
13 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | build
3 |
--------------------------------------------------------------------------------
/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "root": true,
3 | "parser": "@typescript-eslint/parser",
4 | "parserOptions": {
5 | "project": "./tsconfig.eslint.json"
6 | },
7 | "plugins": [
8 | "@typescript-eslint"
9 | ],
10 | "extends": [
11 | "airbnb-typescript/base"
12 | ],
13 | "rules": {
14 | "max-len": [
15 | "error",
16 | {
17 | "code": 180,
18 | "comments": 150
19 | }
20 | ]
21 | }
22 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /node_modules
2 | /package-lock.json
3 | /build
4 | build
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/.idea/jsLibraryMappings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 José Luis González Sánchez
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/READMe.md:
--------------------------------------------------------------------------------
1 | # TypeScript y Node.js
2 | Plantilla de TypeScript para NodeJS, con estilo ESLint y soporte ES6, para usar en VS Code e IntelliJ IDEA (u otros IDEs de Jetbrains).
3 |
4 | [](https://www.typescriptlang.org/)
5 | [](https://airbnb.io/javascript)
6 | [](./LICENSE)
7 | 
8 |
9 |
10 | 
11 |
12 | - [TypeScript y Node.js](#typescript-y-nodejs)
13 | - [Instrucciones](#instrucciones)
14 | - [Uso](#uso)
15 | - [Instalación](#instalación)
16 | - [Ejecución](#ejecución)
17 | - [Ejecución Modo Dev](#ejecución-modo-dev)
18 | - [Ejecución con Nodemon](#ejecución-con-nodemon)
19 | - [Linter](#linter)
20 | - [Extensiones de interés](#extensiones-de-interés)
21 | - [Autor](#autor)
22 | - [Contacto](#contacto)
23 | - [Licencia](#licencia)
24 |
25 | ## Instrucciones
26 | Esta plantilla para uso docente nos servirá para realizar nuestros programas iniciales.
27 |
28 | ### Uso
29 | #### Instalación
30 | ```bash
31 | npm install
32 | ```
33 |
34 | #### Ejecución
35 | ```bash
36 | npm start
37 | ```
38 |
39 | #### Ejecución Modo Dev
40 | ```bash
41 | npm run dev
42 | ```
43 |
44 | #### Ejecución con Nodemon
45 | ```bash
46 | npm run watch
47 | ```
48 |
49 | #### Linter
50 | ```bash
51 | npm run lint
52 | o
53 | npm run lint:fix
54 | ```
55 |
56 | ## Extensiones de interés
57 | - Error Lens: Nos muestra los errores en el mismo editor según nuestro Linter.
58 | - ESLint: Linter para TypeScript/JavaScript.
59 | - Git Graph: Para ver nuestro repositorio en forma de gráfica.
60 | - Tabnine: IA para nuestro código potenciando la codificación del mismo.
61 | - JavaSCript (ES6) code snippets: Snippets para TypeScript/JavaScript.
62 | - Quokka.js: Para ejecutar nuestro código.
63 | - Visual Studio IntelliCode: mejorar el autocompletado de codigo.
64 |
65 |
66 | ## Autor
67 |
68 | Codificado con :sparkling_heart: por [José Luis González Sánchez](https://twitter.com/joseluisgonsan)
69 |
70 | [](https://twitter.com/joseluisgonsan)
71 | [](https://github.com/joseluisgs)
72 |
73 | ### Contacto
74 |
75 | Cualquier cosa que necesites házmelo saber por si puedo ayudarte 💬.
76 |
77 |
78 |
79 |
81 |
82 |
83 |
85 |
86 |
87 |
89 |
90 |
91 |
93 |
94 |
95 |
96 |
97 | ## Licencia
98 |
99 | Este proyecto esta licenciado bajo licencia **MIT**, si desea saber más, visite el fichero
100 | [LICENSE](./LICENSE) para su uso docente y educativo.
101 |
--------------------------------------------------------------------------------
/nodemon.json:
--------------------------------------------------------------------------------
1 | {
2 | "watch": ["src"],
3 | "ext": "ts,json",
4 | "ignore": ["src/**/*.spec.ts"],
5 | "exec": "ts-node ./src/main.ts"
6 | }
7 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ts-node-init",
3 | "version": "1.0.0",
4 | "description": "Plantilla de proyecto para TypeScript",
5 | "main": "/build/main.js",
6 | "scripts": {
7 | "dev": "tsc --watch",
8 | "dev:watch": "nodemon",
9 | "watch": "nodemon",
10 | "build": "rimraf ./build && tsc",
11 | "start": "npm run build && node build/main.js",
12 | "lint": "eslint . --ext .ts",
13 | "lint:fix": "eslint . --ext .ts --fix",
14 | "test": "echo \"Error: no test specified\" && exit 1"
15 | },
16 | "keywords": [
17 | "TypeScript",
18 | "NodeJS"
19 | ],
20 | "author": "joseluisgs",
21 | "license": "MIT",
22 | "devDependencies": {
23 | "@types/node": "^16.9.1",
24 | "@typescript-eslint/eslint-plugin": "^4.31.1",
25 | "@typescript-eslint/parser": "^4.31.1",
26 | "eslint": "^7.32.0",
27 | "eslint-config-airbnb-typescript": "^14.0.0",
28 | "eslint-plugin-import": "^2.24.2",
29 | "nodemon": "^2.0.12",
30 | "rimraf": "^3.0.2",
31 | "ts-node": "^10.2.1",
32 | "typescript": "^4.4.3"
33 | },
34 | "dependencies": {
35 | "@types/readline-sync": "^1.4.4",
36 | "chalk": "^4.1.2",
37 | "readline-sync": "^1.4.10"
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Nombre: José Luis González
3 | * GitHub: joseluisgs
4 | * Fecha: 06/10/2021
5 | * Descripción: Descripción de sistáxis básica de TypeScript
6 | */
7 |
8 | // Zona de declaración de librerías y módulos propios o del sistema
9 | // ers importante que sepas que aunque nos apoyemos en determinadas librerías hay que saber implementar determinadas operaciones
10 | import read from 'readline-sync'; // --> Librería para leer datos por consola. Puedes leer sobre ella y aprender a usarla en: https://github.com/anseki/readline-sync
11 | import chalk from 'chalk'; // --> Podemos obtener colores para decorar nuestra salida. Puedes leer sobre ella y aprender a usarla en: https://github.com/chalk/chalk
12 |
13 | // También podemos importar nuestros propios módulos
14 | import utils from './mod/utils'; // --> funciones o procemientos de utilidad. Lo he querido llamoar así
15 |
16 |
17 | // Zona de declaración de variables y constantes.
18 | // Variables con let y constante con const
19 | // Tipos: number (con signo y sin signo incluyendo decimales), string (cadenas y carácteres) y boolean (true o false)
20 | let edad = 10;
21 | let nombre, apellido: string;
22 | const NUM_PI = 3.14;
23 | let verdadero = true;
24 | let contador = 0;
25 |
26 | // Salida de texto, con comillas simples o dobles
27 | console.log(edad);
28 | console.log("Tu edad es de " + edad + " años");
29 |
30 | // Salida con colores, le decimos a chalk el color
31 | console.log(chalk.blue('Hola') + ' Clase' + chalk.red('!'));
32 |
33 | // Podemos llamar a nuestras funciones y procedimientos
34 | console.log(saludo("Mundo"));
35 |
36 | // Incluso de nuestro módulo importado
37 | utils.presentacion();
38 | console.log("¿Es Primo 4?: " + utils.esPrimo(4));
39 | console.log("¿Es Primo 57?: " + utils.esPrimo(57));
40 | console.log("¿Es Primo 97?: " + utils.esPrimo(97));
41 |
42 | // Entrada de texto conb read.question. Siempre se lee un string
43 | nombre = read.question('¿Cómo te llamas? ');
44 | console.log('Tu nombre: ' + nombre);
45 |
46 | apellido = read.question("¿Cuál es tu apellido? ");
47 | console.log('Tu apellido: ' + apellido);
48 |
49 | // Si queremos leer un número, hay que poner un tipo de dato: questionInt (entero) o questionFloat (decimales)
50 | edad = read.questionInt("¿Cuál es tu edad directamente? ");
51 |
52 | // Si quiero leer una tecla, puedo usar read.keyIn y decir donde
53 | verdadero = Boolean(read.keyInYN());
54 | // Podemos poner verdadero o verdadero==true
55 | if (verdadero) {
56 | console.log('Sí has pulsado Y');
57 | } else {
58 | console.log('Has pulsado N')
59 | }
60 |
61 | // Haciendo el casting a numero. ¿Adivinas el problema?
62 | edad = Number(read.question("¿Cuál es tu edad con casting? "));
63 |
64 | console.log('Imprimo una constante: ' + NUM_PI);
65 | console.log(chalk.blue.bgYellowBright.bold('¡Hola: ' + nombre + ' ' + apellido + ' y tienes ' + edad +'!'));
66 |
67 | // Esto es un comentario de una línea de código
68 | // Si quiero comentar varias líneas debo poner // en cada una de de ellas
69 |
70 | /*
71 | Esto es un comentario de bloque de código
72 | Si quiero comentar varias líneas debo poner /* en cada una de de ellas
73 | Y cerrarlo con
74 | */
75 |
76 | // Condicionales
77 | if (edad >= 10){
78 | console.log('Verdadero');
79 | } else {
80 | console.log('Falso');
81 | }
82 |
83 | // Condicionales multiples con if
84 | if (edad >= 10){
85 | console.log('Mayor que 10');
86 | } else if (edad >= 5) {
87 | console.log('Menor que 10 y mayor que 5');
88 | } else {
89 | console.log('Menor que 5');
90 | }
91 |
92 | // Condicionales múltiples con swich. El default es el caso por defecto. Break para salir
93 | switch (edad) {
94 | case 10:
95 | console.log('Edad 10');
96 | break;
97 | case 20:
98 | console.log('Edad 20');
99 | break;
100 | default:
101 | console.log('Edad no es 10 ni 20');
102 | }
103 |
104 | // Bucles indefinidos
105 | // While, primero comprueba la condición, luego entra
106 | contador = 0;
107 | while (contador<10){
108 | console.log('Contador: ' + contador);
109 | contador++; // equivale a contador = contador +1
110 | }
111 |
112 | contador = 10;
113 | // repetir mientras, primero ejecuta y luego comprueba la condición por si debe repetirse
114 | do {
115 | console.log('Contador: ' + contador);
116 | contador++; // equivale a contador = contador +1
117 | } while (contador < 10)
118 |
119 | // Bucle indefinidos con for
120 | for (let i = 0; i < 10; i++) {
121 | console.log('Contador: ' + i);
122 | }
123 |
124 | /**
125 | * Todo programa debe emezar con una funcion main()
126 | */
127 |
128 | // Podemos definir aquí las funciones que usaremos
129 | function saludo(mensaje: string): string {
130 | return "Hola, " + mensaje;
131 | }
132 |
133 |
134 |
135 |
--------------------------------------------------------------------------------
/src/mod/utils.ts:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * Funcion que devuelve si un numero es primo o no
4 | * @param num Numero para saber si es primo
5 | * @returns Verdadero si es primo
6 | */
7 | function esPrimo(num: number): boolean {
8 | let esPrimo = true;
9 | // Es divisible entre 2
10 | if(num % 2 == 0) {
11 | esPrimo = false;
12 | }
13 |
14 | // Recorremos los impares
15 | for(let i = 3; i <= Math.sqrt(num) && esPrimo; i+=2 ) {
16 | if (num % i == 0) {
17 | esPrimo = false;
18 | }
19 | }
20 | return esPrimo;
21 | }
22 |
23 | function presentacion() {
24 | console.log("Usando librería de números primos");
25 | }
26 |
27 | // Exportamos las funciones que queramos que sea publicas
28 | export default { esPrimo, presentacion };
29 |
--------------------------------------------------------------------------------
/ts-init.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Para crear el fichero tsconfig.json
3 |
4 | npx tsc --init --rootDir src --outDir build \
5 | --esModuleInterop --resolveJsonModule --lib ES6 \
6 | --module commonjs --allowJs true --noImplicitAny true
--------------------------------------------------------------------------------
/ts-node-init.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/tsconfig.eslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.json",
3 | "include": [
4 | "src/**/*.ts",
5 | "src/**/*.js",
6 | "test/**/*.ts"
7 | ]
8 | }
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */
4 |
5 | /* Basic Options */
6 | // "incremental": true, /* Enable incremental compilation */
7 | "target": "ES5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
8 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
9 | "lib": ["ES6"], /* Specify library files to be included in the compilation. */
10 | "allowJs": true, /* Allow javascript files to be compiled. */
11 | "outDir": "build", /* Redirect output structure to the directory. */
12 | "rootDir": "src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
13 | // "composite": true, /* Enable project compilation */
14 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
15 | // "removeComments": true, /* Do not emit comments to output. */
16 | // "noEmit": true, /* Do not emit outputs. */
17 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */
18 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
19 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
20 |
21 | /* Strict Type-Checking Options */
22 | "strict": true, /* Enable all strict type-checking options. */
23 | "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
24 | // "strictNullChecks": true, /* Enable strict null checks. */
25 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */
26 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
27 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
28 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
29 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
30 |
31 | /* Additional Checks */
32 | // "noUnusedLocals": true, /* Report errors on unused locals. */
33 | // "noUnusedParameters": true, /* Report errors on unused parameters. */
34 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
35 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
36 | // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
37 |
38 | /* Module Resolution Options */
39 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
40 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
41 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
42 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
43 | // "typeRoots": [], /* List of folders to include type definitions from. */
44 | // "types": [], /* Type declaration files to be included in compilation. */
45 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
46 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
47 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
48 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
49 |
50 | /* Source Map Options */
51 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
52 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
53 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
54 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
55 |
56 | /* Experimental Options */
57 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
58 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
59 |
60 | /* Advanced Options */
61 | "resolveJsonModule": true, /* Include modules imported with '.json' extension */
62 | "skipLibCheck": true, /* Skip type checking of declaration files. */
63 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
64 | }
65 | }
66 |
--------------------------------------------------------------------------------