Create by jsliang on 2021-05-12 11:00:03
Recently revised in 2021-06-12 16:58:04
——————————☆☆☆——————————
Corresponding address of Node series:
- Code repository: https://github.com/LiangJunrong/all-for-one
- Article warehouse: https://github.com/LiangJunrong/document-library/tree/master/%E7%B3%BB%E5%88%97-%E5%89%8D%E7%AB%AF%E8% B5%84%E6%96%99/Node
——————————☆☆☆——————————
TypeScript is a superset of JavaScript, adding new features to the language (hereinafter referred to as TS).
jsliang have been envious of TypeScript for a long time. I haven't built it by myself. I have used others to build it. I just want to try this time.
This article quickly explains the use of TS Node.js
a catalog
The front end that does not toss, what is the difference with the salted fish
Two Node.js quick integration of TS
Return to list
2.1 Directory structure
Return to catalog
Before that, we first understand the directory that will be built:
util
- src
- index.ts
- tsconfig.json
- package.json
util is the warehouse name (folder name), you can change to another folder at will
Except for
index.ts
is manually added, other files are generated by the command line, so you can ignore it
Then, Here We go~
2.2 Initialization steps
Return to list
first , initialize package.json
:
npm init --yes
If the warehouse is named in Chinese, you need to fill in npm init
and then , if in index.ts
, the following code is written:
index.ts
const path = require('path');
console.log(path);
At this time, execute node src/index.ts
, and you will see an error:
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: []
}
It is also possible not to report an error!
If you are using VS Code development software, you will see the prompt:
找不到名称 "require"。是否需要为节点安装类型定义? 请尝试使用 `npm i --save-dev @types/node`。ts(2580)
It means that the path
and require
modules are both Node.js things. To use it, you need to install the declaration file of Node.js, that is, install the package @types/node
followed by , if you install @types/node
alone, it is not enough, because @types/node
only the TS
file, that is, xxx.d.ts
, so other content is needed:
- Install
@types/node
:npm i @types/node -D
- Install
typescript
:npm i typescript -D
- Install
ts-node
:npm i ts-node -D
Executed together:
npm i @types/node typescript ts-node -D
[2021-06-12 16:42:05] I found a missing point. According to this article, after installing these packages, if you execute
node src/index.ts
it will still report:SyntaxError: Unexpected identifier
, so you should installnpm i ts-node -g
, and then executets-node src/index.ts
At this time, execute node src/index.ts
, you will find that path
is printed out, it is feasible, the plan is passed~
At this time,node_modules
andpackage-lock.json
will be generated, these 2 are not introduced in detail, please Google
finally , you can also configure TS content in depth:
- Created
tsconfig.json
:tsc --init
tsc needs to installtypescript
, so you need to executenpm i typescript -g
After executing the command, tsconfig.json
will be created automatically, with the following content:
160c47eaeb8de42021-05-11
throughtsc --init
fromtsconfig.json
after machine translation (after all, 160c47eaeb8de7 jsliang never been level 4, what do you think~)
{
"compilerOptions": {
/* 访问 https://aka.ms/tsconfig.json 查看更多 */
/* 基本选项 */
// "incremental": true, /* 启用增量编译 */
"target": "es5", /* 指定 ECMAScript 目标版本: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 或者 'ESNEXT'. */
"module": "commonjs", /* 指定使用模块: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', 或者 'ESNext'. */
// "lib": [], /* 指定要包含在编译中的库文件 */
// "allowJs": true, /* 允许编译 javascript 文件 */
// "checkJs": true, /* 报告 javascript 文件中的错误 */
// "jsx": "preserve", /* 指定 jsx 代码的生成: 'preserve', 'react-native', 'react', 'react-jsx' 或者 'react-jsxdev'. */
// "declaration": true, /* 生成相应的 '.d.ts' 文件 */
// "declarationMap": true, /* 对每个 '.d.ts' 文件进行遍历 */
// "sourceMap": true, /* 生成相应的 '.map' 文件 */
// "outFile": "./", /* 将输出文件合并为一个文件 */
"outDir": "./dist", /* 指定输出目录 */
// "rootDir": "./", /* 用来控制输出目录结构 --outDir */
// "composite": true, /* 启用项目编译 */
// "tsBuildInfoFile": "./", /* 指定文件来存储增量编译信息 */
"removeComments": true, /* 删除编译后的所有的注释 */
// "noEmit": true, /* 不生成输出文件 */
// "importHelpers": true, /* 从 tslib 导入辅助工具函数 */
// "downlevelIteration": true, /* 在 ES5 和 ES3 中全面支持 for-of */
// "isolatedModules": true, /* 将每个文件作为单独的模块 (与 'ts.transpileModule' 类似) */
/* 严格的类型检查选项 */
"strict": true, /* 启用所有严格类型检查选项 */
// "noImplicitAny": true, /* 在表达式和声明上有隐含的 any 类型时报错 */
// "strictNullChecks": true, /* 启用严格的 null 检查 */
// "strictFunctionTypes": true, /* 启用严格的 function 类型检查 */
// "strictBindCallApply": true, /* 启用严格的 bind、call、apply 方法参数检查 */
// "strictPropertyInitialization": true, /* 启用严格的类的属性初始化检查 */
// "noImplicitThis": true, /* 当 this 表达式值为 any 类型的时候,生成一个错误 */
// "alwaysStrict": true, /* 以严格模式检查每个模块,并在每个文件里加入 'use strict' */
/* 额外的检查 */
"noUnusedLocals": true, /* 有未使用的变量时,抛出错误 */
"noUnusedParameters": true, /* 有未使用的参数时,抛出错误 */
// "noImplicitReturns": true, /* 并不是所有函数里的代码都有返回值时,抛出错误 */
// "noFallthroughCasesInSwitch": true, /* 报告 switch 语句的 fallthrough 错误。(即,不允许 switch 的 case 语句贯穿) */
// "noUncheckedIndexedAccess": true, /* 在索引签名结果中包含 undefined */
// "noPropertyAccessFromIndexSignature": true, /* 需要索引签名中未声明的属性才能使用元素访问 */
/* Module Resolution Options */
// "moduleResolution": "node", /* 选择模块解析策略: 'node' (Node.js) or 'classic' (TypeScript pre-1.6) */
// "baseUrl": "./", /* 用于解析非相对模块名称的基目录 */
// "paths": {}, /* 模块名到基于 baseUrl 的路径映射的列表 */
// "rootDirs": [], /* 根文件夹列表,其组合内容表示项目运行时的结构内容 */
// "typeRoots": [], /* 包含类型声明的文件列表 */
// "types": [], /* 需要包含的类型声明文件名列表 */
// "allowSyntheticDefaultImports": true, /* 允许从没有设置默认导出的模块中默认导入 */
"esModuleInterop": true, /* 通过为所有导入创建名称空间对象,启用 CommonJS 和 ES 模块之间的的互动性 */
// "preserveSymlinks": true, /* 不解析符号链接的真实路径 */
// "allowUmdGlobalAccess": true, /* 允许从模块访问 UMD 全局变量 */
/* Source Map Options */
// "sourceRoot": "", /* 指定调试器应该找到 TypeScript 文件而不是源文件的位置 */
// "mapRoot": "", /* 指定调试器应该找到映射文件而不是生成文件的位置 */
// "inlineSourceMap": true, /* 生成单个 soucemaps 文件,而不是将 sourcemaps 生成不同的文件 */
// "inlineSources": true, /* E将代码与 sourcemaps 生成到一个文件中,要求同时设置了 --inlineSourceMap 或 --sourceMap 属性 */
/* Experimental Options */
// "experimentalDecorators": true, /* 启用装饰器 */
// "emitDecoratorMetadata": true, /* 为装饰器提供元数据的支持 */
/* Advanced Options */
"skipLibCheck": true, /* 跳过声明文件的类型检查 */
"forceConsistentCasingInFileNames": true /* 进制对同一文件使用大小写不一致的引用 */
}
}
The purpose of this file is to make TypeScript use the .ts
file in this directory and subdirectories as part of the compilation context, and include some default compilation options.
In addition, there are some configuration items you can view the following explanation.
three tsconfig.json explanation
return to catalog
tsconfig.json
file is mainly to develop some good habits, for example any
type throughout the code, and do not use import
some useless packages.
If you need to check this configuration item, friends can write the following code index.ts
import path from 'path';
console.log('jsliang 的 Node 工具库');
Executing node src/index.ts
will report an error:
This acts as a constraint.
Some configuration items are explained below.
3.1 compilerOptions configurable items
Return to catalog
Used to configure some items in TS:
{
"compilerOptions": {
/* 基本选项 */
}
}
3.2 files Configurable items
Return to catalog
Specify the files to be compiled through files
{
"files": [
"./some/file.ts"
]
}
3.3 include and exclude configurable items
return to catalog
Specify the files that need to be included and excluded files through include
and exclude
{
"include": [
"./folder"
],
"exclude": [
"./folder/**/*.spec.ts",
"./folder/someSubFolder"
]
}
Four ESLint
Return to catalog
You can use TSLint or ESLint to constrain the code specification.
However, the official website of TSLint stated that it was abandoned in 2019 and later, and use ESLint instead, so let's install ESLint here.
References: https://palantir.github.io/tslint/
Excuting an order:
npm i eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin -D
Then create .eslintrc.js
to store the following content:
module.exports = {
// 解析器
parser: "@typescript-eslint/parser", // 把 TS 转换成 ESTree 兼容格式的解析器,这样就可以在 eslint 中使用了
// 拓展:用来继承已有的 ESLint 配置
extends: ["plugin:@typescript-eslint/recommended"],
// 插件
plugins: ["@typescript-eslint"],
// 环境:设置代码环境,eslint 能够自动识别对应环境所有的全局变量
env: {
node: true,
commonjs: true,
amd: true,
es6: true,
},
/**
* "off" 或 0 - 关闭规则
* "warn" 或 1 - 开启规则,使用警告级别的错误:warn (不会导致程序退出),
* "error" 或 2 - 开启规则,使用错误级别的错误:error (当被触发的时候,程序会退出)
*/
rules: {
/* Possible Errors - 这些规则与 JavaScript 可能的错误或者逻辑错误有关 */
"no-dupe-args": 2, // 禁止 function 定义中出现重名参数
"no-dupe-keys": 2, // 禁止对象字面量中出现重复的 key
"no-empty": 2, // 禁止出现空语句块
"no-func-assign": 2, // 禁止对 function 声明重新赋值
"no-irregular-whitespace": 2, // 禁止不规则的空白
"no-unreachable": 2, // 禁止在 return、throw、continue 和 break 语句之后出现不可达代码
/* Best Practices - 这些规则是关于最佳实践的,帮助避免一些问题 */
"eqeqeq": 2, // 要求使用 === 和 !==
"curly": 2, // 强制所有控制语句使用一致的括号风格
/* Variables - 这些规则与变量有关 */
"no-delete-var": 2, // 禁止删除变量
"no-unused-vars": 2, // 进制出现未使用过的变量
/* Node.js and CommonJS - 关于 Node.js 相关的规则 */
"global-require": 2, // 要求 require() 出现在顶层模块作用域中
"handle-callback-err": 2, // 要求回调函数中有容错处理
},
};
After the configuration is successful, we can see index.ts
This configuration item in the picture is closed, it is too
console
Small Tips: It’s more delicious with the [ESlint] plug-in of VS Code
Five Summary
return to catalog
The current directory structure is as follows:
+ src
- index.ts
- .eslintrc.js
- package.json
- tsconfig.json
The corresponding content has been explained above. The current execution of node src/index.ts
can also be run, and the TS is constructed.
Finally, post the package.json
prevent the friends from going the wrong way:
{
"name": "jsliang",
"version": "1.0.0",
"description": "Fe-util, Node 工具库",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"jsliang",
"Node 工具库",
"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"
}
}
See you in the next issue~
Six references
Return to list
- TSLint
- ESLint
- ESLint Chinese Net
- ESLint: configuration rule
- CSDN: eslint simple configuration
- snowdream: ESLint configuration parameter
jsliang's document library is by 160c47eaeb93f0 Liang Junrong using Creative Commons Attribution-Non-commercial Use-Same Method Sharing 4.0 International License Agreement . <br/>Based on the works https://github.com/LiangJunrong/document-library <br/> addition to this license may be authorized usage rights from https://creativecommons.org/licenses/by-nc-sa/2.5/cn/ obtained at.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。