Create by jsliang on 2021-05-12 11:00:03

Recently revised in 2021-06-12 16:58:04

— — — — — fostered fostered fostered — — — — —

Node series address:

  • Code repository: github.com/LiangJunron…
  • Article repository: github.com/LiangJunron…

— — — — — fostered fostered fostered — — — — —

TypeScript is a superset of JavaScript that adds new functionality to the language (TS).

Jsliang has been jealous of TypeScript for a long time. He has never built TypeScript himself.

This article provides a quick tutorial on TS by configuring Node.js to integrate with TS.

A directory

What’s the difference between a free front end and a salted fish

directory
A directory
Fast TS integration with node.js
 2.1 Directory Structure
 2.2 Initialization Procedure
Three tsconfig. Json
 3.1 compilerOptions Configurable items
 3.2 Files Configurable items
 3.3 Include and Exclude Configurable items
Four ESLint
Five summarizes
Vi References

Fast TS integration with node.js

Returns the directory

2.1 Directory Structure

Returns the directory

Before we do that, let’s understand the directory we’re building:

util
 - src
  - index.ts
 - tsconfig.json
 - package.json
Copy the code

Util is the repository name (folder name), and you can switch to another folder at will

All files except index.ts are generated by command line and can be ignored

So, Here We go~

2.2 Initialization Procedure

Returns the directory

First, initialize package.json:

  • npm init --yes

If the repository name is Chinese, NPM init is required

Then, if in index.ts, the following code is written:

index.ts

const path = require('path');

console.log(path);
Copy the code

SRC /index.ts node SRC /index.ts node SRC /index.ts

internal/modules/cjs/loader.js:883
  throw err;
  ^

Error: Cannot find module 'F:\jsliang\index.ts'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
    at Function.Module._load (internal/modules/cjs/loader.js:725:27)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)   
    at internal/main/run_main_module.js:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}
Copy the code

It is also possible not to report errors!

If you are using VS Code development software, you will see the following prompt:

Could not find the name "require". Do you need to define the node installation type? Try 'NPM I -- save-dev@types /node'. ts(2580)Copy the code

The path and require modules are node.js stuff. To use it, you need to install the Node.js declaration file, i.e. the @types/ Node package.

Then, it’s not enough to simply install @types/node, because @types/node is only declared by the TS file, i.e. Xxx.d.ts, so you need something else:

  • The installation@types/node:npm i @types/node -D
  • The installationtypescript:npm i typescript -D
  • The installationts-node:npm i ts-node -D

NPM i@types /node typescript ts-node -d

[2021-06-12 16:42:05] SyntaxError: SRC /index.ts SRC /index.ts Unexpected identifier, so you should install NPM I ts-node -g, then ts-node SRC /index.ts

SRC /index.ts/node SRC /index.ts/node SRC /index.ts

Node_modules and package-lock.json are generated. Please Google node_modules and package-lock.json

Finally, you can further configure TS content:

  • createtsconfig.json:tsc --init

TSC needs to install typescript globally, so NPM I typescript -g is required first

After executing the command, tsconfig.json is automatically created with the following contents:

Jsliang on 2021-05-11: get tsconfig.json from TSC –init, and open a few restrictions after machine translation (after all, jsliang level 4 did not pass, what is it?)

{
  "compilerOptions": {
    / * visit https://aka.ms/tsconfig.json for more * /

    /* Basic options */
    // "incremental": true,                         /* 启用增量编译 */
    "target": "es5"./* Specify the ECMAScript target version: 'ES3' (the default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT. * /
    "module": "commonjs"./ * specified using modules: 'none', 'commonjs',' amd ', 'system', 'umd', 'es2015', 'es2020', or 'ESNext. * /
    // "lib": [], /* Specifies the library file to be included in the compilation */
    // "allowJs": true, /* Allows compiling javascript files */
    // "checkJs": true, /* Reports errors in javascript files */
    // "JSX ": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
    // "declaration": true,                         /* 生成相应的 '.d.ts' 文件 */
    // "declarationMap": true, /* walks through each '.d.ts' file */
    // "sourceMap": true, /* Generates the corresponding '.map' file */
    // "outFile": "./", /* Merge output files into one file */
    "outDir": "./dist"./* Specifies the output directory */
    // "rootDir": "./", /* To control the output directory structure --outDir */
    // "composite": true, /* Enable project compilation */
    // "tsBuildInfoFile": ". ", /* Specifies the file to store incremental compilation information */
    "removeComments": true./* Delete all compiled comments */
    // "noEmit": true, /* Does not generate output file */
    // "importHelpers": true, /* Imports helper functions from tslib */
    // "downlevelIteration": true, /* For-of */ is fully supported in ES5 and ES3
    // "isolatedModules": true, /* Treat each file as a separate module (similar to 'ts.transpilemodule') */

    /* Strict type checking options */
    "strict": true./* Enable all strict type checking options */
    // "noImplicitAny": true, /* The expression and declaration have an implied any type error */
    // "strictNullChecks": true, /* enable strictNullChecks */
    // "strictFunctionTypes": true, /* Enable strict function type checking */
    // strictBindCallApply: true, /* Enable strict bind, call, apply parameter checks */
    / / "strictPropertyInitialization" : true, / * enabled the strict check * / attributes of a class is initialized
    // "noImplicitThis": true, /* Generates an error */ when this is of type any
    // "alwaysStrict": true, /* Check each module in strict mode and add 'use strict' */ to each file

    /* Additional checks */
    "noUnusedLocals": true./* Throw an error */ when there are unused variables
    "noUnusedParameters": true./* An error is thrown when there are unused arguments */
    // "noImplicitReturns": true, /* An error is thrown when not all code in a function returns a value */
    / / "noFallthroughCasesInSwitch" : true, / * switch statement fallthrough error report. (that is, switch case statements are not allowed to run through) */
    // "noUncheckedIndexedAccess": true, /* With undefined */
    / / "noPropertyAccessFromIndexSignature" : true, / * need index sign access did not declare attributes to use the element in the * /

    /* Module Resolution Options */
    // "moduleResolution": "node", /* select the moduleResolution policy: 'node' (node.js) or 'classic' (TypeScript pre-1.6) */
    // "baseUrl": "./", /* The base directory used to resolve non-relative module names */
    // "Paths ": {}, /* List of module names to baseUrl based path mappings */
    // "rootDirs": [], /* The list of root folders whose combined contents represent the structural contents of the project runtime */
    // "typeRoots": [], /* List of files containing type declarations */
    // "types": [], /* List of type declaration filenames to include */
    / / "allowSyntheticDefaultImports" : true, / * allows never to set default import/export modules by default
    "esModuleInterop": true./* Enable interaction between CommonJS and ES modules by creating namespace objects for all imports */
    // "preserveSymlinks": true, /* The real path of symbolic links is not resolved */
    // "allowUmdGlobalAccess": true, /* Allows access from modules to UMD global variables */

    /* Source Map Options */
    // "sourceRoot": "", /* Specifies where the debugger should find the TypeScript file instead of the source file */
    // "mapRoot": "", /* Specifies where the debugger should find the mapping file instead of the generated file */
    // "inlineSourceMap": true, /* Generate a single soucemaps file instead of generating a different sourcemaps file */
    // "inlineSources": true, /* E generates the code and sourcemaps in a file, requiring both the --inlineSourceMap and --sourceMap attributes */ to be set

    /* Experimental Options */
    // "experimentalDecorators": true, /* Enable decorator */
    // "emitDecoratorMetadata": true, /* Provides metadata support for decorators */

    /* Advanced Options */
    "skipLibCheck": true./* Skip type checking for declared files */
    "forceConsistentCasingInFileNames": true        /* Base uses case-insensitive references to the same file */}}Copy the code

The purpose of this file is to make TypeScript use the.ts files in this directory and subdirectories as part of the compilation context and include some of the default compilation options.

There are other configuration items you can see below.

Three tsconfig. Json

Returns the directory

The tsconfig.json file is mainly for good habits, such as following the rule not to write any types throughout your code and not to import useless packages.

If you need to verify this configuration item, you can write the following code to index.ts:

import path from 'path';

console.log('Jsliang Node library');
Copy the code

Node SRC /index.ts error:

This acts as a constraint.

Here are some configuration items.

3.1 compilerOptions Configurable items

Returns the directory

To configure some items in TS:

{
  "compilerOptions": {

    /* Basic options */}}Copy the code

3.2 Files Configurable items

Returns the directory

Specify the files to compile with files:

{
  "files": [
    "./some/file.ts"]}Copy the code

3.3 Include and Exclude Configurable items

Returns the directory

Include and exclude specify the files to include and exclude:

{
  "include": [
    "./folder"]."exclude": [
    "./folder/**/*.spec.ts"."./folder/someSubFolder"]}Copy the code

Four ESLint

Returns the directory

You can constrain code specifications via TSLint or ESLint.

However, the TSLint official website says that it has been discarded in favor of ESLint for 2019 and beyond, so let’s install ESLint here.

Reference: palantir. Making. IO/tslint /

Execute command:

  • npm i eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin -D

Then create.eslintrc.js to hold the following:

module.exports = {
  / / the parser
  parser: "@typescript-eslint/parser".// Convert TS to an ESTree compatible format parser so it can be used in ESLint
  
  // Extension: used to inherit existing ESLint configurations
  extends: ["plugin:@typescript-eslint/recommended"]./ / the plugin
  plugins: ["@typescript-eslint"].// Environment: Set the code environment so that ESLint automatically recognizes all global variables for that environment
  env: {
    node: true.commonjs: true.amd: true.es6: true,},/** * "off" or 0 - turn off the rule * "WARN" or 1 - turn on the rule, using warning level errors: WARN (will not cause the program to exit), * "error" or 2 - turn on the rule, using error level errors: Error (when raised, the program exits) */
  rules: {
    /* Possible Errors - These rules relate to Possible JavaScript Errors or logic Errors */
    "no-dupe-args":            2.// Disallow duplicate arguments in function definitions
    "no-dupe-keys":            2.Disallow duplicate keys in object literals
    "no-empty":                2.// Disallow empty statement blocks
    "no-func-assign":          2.// Disallow reassignment of function declarations
    "no-irregular-whitespace": 2.// Disallow irregular whitespace
    "no-unreachable":          2.// Disallows unreachable code after return, throw, continue, and break statements

    /* Best Practices - These rules are about Best Practices and help avoid some problems */
    "eqeqeq":                  2.// Use === and! = =
    "curly":                   2.// Force all control statements to use the same parenthesis style

    /* Variables - These rules relate to Variables */
    "no-delete-var":           2.// Disable variable deletion
    "no-unused-vars":          2.// An unused variable appears in the base

    /* Node.js and CommonJS - Node.js rules */
    "global-require":          2.Require require() to appear in the top-level module scope
    "handle-callback-err":     2.// Error tolerance is required in the callback function}};Copy the code

After the configuration is successful, we can see in index.ts:

The configuration item in the picture is turned off. Not being able to console is too weird

Tips: Use VS Code’s [ESlint] plugin to taste better

Five summarizes

Returns the directory

The current directory structure is as follows:

+ src
  - index.ts
- .eslintrc.js
- package.json
- tsconfig.json
Copy the code

SRC /index.ts node SRC /index.ts node SRC /index.ts node SRC /index.ts

Package. json:

{
  "name": "jsliang"."version": "1.0.0"."description": "Fe-util, Node Library"."main": "index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "jsliang"."Node Tool Library"."Node"]."author": "jsliang"."license": "ISC"."devDependencies": {
    "@types/node": "^ 15.12.2"."@typescript-eslint/eslint-plugin": "^ 4.26.1"."@typescript-eslint/parser": "^ 4.26.1"."eslint": "^ 7.28.0"."ts-node": "^ 10.0.0"."typescript": "^ 4.3.2." "}}Copy the code

So we’ll see you next time

Vi References

Returns the directory

  • TSLint
  • ESLint
  • ESLint Chinese website
  • ESLint: Configures rules
  • CSDN: ESLint simple configuration
  • Snowdream: ESLint configuration parameter

Jsliang’s document library is licensed by Junrong Liang under the Creative Commons Attribution – Non-commercial – Share alike 4.0 International License. Based on the github.com/LiangJunron… On the creation of works. Outside of this license agreement authorized access can be from creativecommons.org/licenses/by… Obtained.