如何设置 TypeScript + Node.js 项目

我们在这个博客上讨论了很多先进的 Node.js 和 TypeScript概念,特别是领域驱动设计和大型企业应用程序模式。但是,在收到有兴趣了解基本 TypeScript 入门项目外观的读者的电子邮件后,我将这些内容放在一起。

先决条件

  • 你应该安装了 Node 和 npm
  • 你应该熟悉 Node 和 npm 生态系统
  • 您安装了代码编辑器(最好是 VS Code,它是 TypeScript 的冠军)

目标

在这个简短的指南中,我将引导您完成创建一个基本的 TypeScript 应用程序和编译它的过程。其实真的很简单!

之后,我们将设置一些脚本,用于在 中热重载development、构建production和运行production


关于TypeScript

TypeScript 被微软开发并挪用为“可扩展的 JavaScript”,是 JavaScript 的超集,意思是 JavaScript 能做的一切,TypeScript 都能做(和更多 更好的)。

TypeScript 主要是为了解决两个问题:

  1. 为 JavaScript 开发人员提供一个可选的类型系统
  2. 为 JavaScript 开发人员提供针对当前 JavaScript 引擎利用未来 JavaScript 版本的计划功能的能力。

我们在本博客的大多数主题中使用 TypeScript,因为它更适合创建持久的软件,并且让编译器帮助捕获错误和验证类型非常有帮助。


最初设定

让我们创建一个文件夹供我们工作。

mkdir typescript-starter
cd typescript-starter

接下来,我们将设置项目package.json并添加依赖项。

设置 Node.js package.json

-y创建时使用该标志package.json将简单地批准所有默认值。

npm init -y

将 TypeScript 添加为开发依赖项

这可能并不令人意外;)

npm install typescript --save-dev

安装后typescript,我们可以通过命令访问命令行 TypeScript 编译器tsc。更多关于下面的内容。

为 TypeScript 安装环境 Node.js 类型

TypeScript 有隐式、显式和环境类型。环境类型是添加到全局执行范围的类型。由于我们使用的节点,这将是很好,如果我们能得到的类型安全和自动完成节点上的API,如filepathprocess,等那有什么关系安装的DefinitelyTyped类型定义为节点就行了。

npm install @types/node --save-dev

创建一个tsconfig.json.

tsconfig.json是我们定义 TypeScript 编译器选项的地方。我们可以创建一个带有多个选项集的 tsconfig。

npx tsc --init --rootDir src --outDir build \
--esModuleInterop --resolveJsonModule --lib es6 \
--module commonjs --allowJs true --noImplicitAny true
  • rootDir:这是 TypeScript 寻找我们代码的地方。我们已将其配置为在src/文件夹中查找。这就是我们将编写 TypeScript 的地方。
  • outDir:TypeScript 将我们编译后的代码放在哪里。我们希望它转到一个build/文件夹。
  • esModuleInterop:如果您在过去几年中处于 JavaScript 领域,您可能已经意识到模块系统已经有点失控(AMD、SystemJS、ES 模块等)。对于需要更长时间讨论的主题,如果我们将其commonjs用作我们的模块系统(对于 Node 应用程序,您应该这样做),那么我们需要将其设置为true.
  • resolveJsonModule: 如果我们在这个项目中使用 JSON,这个选项允许 TypeScript 使用它。
  • lib:这个选项为我们的项目添加了环境类型,允许我们依赖来自不同 Ecmascript 版本、测试库甚至浏览器 DOM api 的功能。我们想利用一些es6语言功能。这一切都被编译成es5.
  • module:commonjs是 2019 年的标准 Node 模块系统。让我们使用它。
  • allowJs:如果您要将旧的 JavaScript 项目转换为 TypeScript,此选项将允许您在其中包含.js文件.ts
  • noImplicitAny: 在 TypeScript 文件中,不允许不明确地指定类型。每个类型都需要具有特定类型或显式声明any。没有隐含的anys。

在这一点上,你应该有一个tsconfig.json看起来像这样的:

{
  "compilerOptions": {
    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "lib": ["es6"],                     /* Specify library files to be included in the compilation. */
    "allowJs": true,                          /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "build",                          /* Redirect output structure to the directory. */
    "rootDir": "src",                         /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    "noImplicitAny": true,                    /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "resolveJsonModule": true                 /* Include modules imported with '.json' extension */
  }
}

我们可以继续清理我们不需要的注释掉的东西。我们tsconfig.json应该是这样的:

{
  "compilerOptions": {
    "target": "es5",                          
    "module": "commonjs",                    
    "lib": ["es6"],                     
    "allowJs": true,
    "outDir": "build",                          
    "rootDir": "src",
    "strict": true,         
    "noImplicitAny": true,
    "esModuleInterop": true,
    "resolveJsonModule": true
  }
}

我们准备运行我们的第一个 TypeScript 文件。

创建src文件夹并创建我们的第一个 TypeScript 文件

mkdir src
touch src/index.ts

让我们写一些代码。

console.log('Hello world!')

编译我们的TypeScript

要编译我们的代码,我们需要tsc使用npxNode 包执行器运行命令。tsc将读取tsconfig.json当前目录中的 ,并针对 TypeScript 编译器应用配置以生成已编译的 JavaScript 代码。

npx tsc

我们编译的代码

看看build/index.js,我们已经编译了我们的第一个 TypeScript 文件。

"use strict";
console.log('Hello world!');

有用的配置和脚本

冷装

冷重新加载对本地开发很好。为了做到这一点,我们需要依赖更多的包:ts-node直接运行 TypeScript 代码而不必等待它被编译,以及nodemon监视我们的代码更改并在文件更改时自动重新启动。

npm install --save-dev ts-node nodemon

添加nodemon.json配置。

{
  "watch": ["src"],
  "ext": ".ts,.js",
  "ignore": [],
  "exec": "ts-node ./src/index.ts"
}

然后要运行该项目,我们所要做的就是运行nodemon. 让我们为此添加一个脚本。

"start:dev": "nodemon",

通过运行npm run start:devnodemon将启动我们的应用程序 using ts-node ./src/index.ts,观察对.ts和 内部.js文件的更改/src

创建生产版本

为了清理和编译用于生产的项目,我们可以添加一个build脚本。

Install rimraf,一个像rm -rf命令一样的跨平台工具(只是删除你告诉它的任何东西)。

npm install --save-dev rimraf

然后,将此添加到您的package.json.

"build": "rimraf ./build && tsc",

现在,当我们运行时npm run buildrimrafbuild在 TypeScript 编译器向 发出新代码之前删除我们的旧文件夹dist

生产启动脚本

为了在生产环境中启动应用程序,我们需要做的就是build首先运行命令,然后在build/index.js.

启动脚本如下所示。

"start": "npm run build && node build/index.js"

我告诉你这很简单!现在,你走吧。创造伟大的事物,我的朋友

相关标签:
  • NodeJs
  • TypeScript
  • tsconfig.json
0人点赞

发表评论

当前游客模式,请登陆发言

所有评论(0)

用户头像
咕叽Boy

嗯哼、、