JavaScript 有着资源丰富的生态圈,但同时也令人在面对这一堆套件、工具以及设置时眼花撩乱、不知所措。TypeScript 能用比较严谨的方式来开发 JavaScript 程序,可以大大地提升代码的可维护性,也可以增加多人协作时的效率。笔者甚至觉得我们都应该用 TypeScript 来编写 JavaScript 程序会比较好。然而,要创建出一个完整 TypeScript 项目是一件繁琐的事情,我们会需要安装多种套件及工具并撰写设置档和代码,来使项目能符合我们自己的开发习惯。在这篇文章中,笔者要分享自己创建 TypeScript 项目的方式。
如果您还不熟悉 TypeScript 的话,可以先参考《TypeScript 学习之路》系列文章。
全域工具
撰写 TypeScript 工具除了要安装 typescript 套件来取得 tsc 工具外,笔者建议也把套件管理工具改成 pnpm(预设是 npm)。
pnpm 的好处是它的速度很快,且会用链接(link)的方式来存放 Node.js 套件,可以省下大量的时间和硬盘空间。pnpm 还有一个特性是,在 package.json 的 dependencies 相关属性中,必须要把有依赖到(有 import)的套件都明确写出来,要引入套件 B 时不能因为 dependencies 相关属性中的套件 A 已经有依赖套件 B 了就不把套件 B 写在 dependencies 的相关属性中。
搭配 depcheck 工具可以检查 dependencies 相关属性中有无没用到的套件被写进来了。
运行以下指令,可以安装上述的这些全域工具:
IDE 的选用
IDE 当然就是用 VS Code 了,最多人使用也最方便。如果您还没有用过 VS Code,可以参考以下这篇文章:
要用 VS Code 来开发 JavaScript 程序,笔者会另外安装以下的延伸模块:
ESLint:ESLint 是一个 JavaScript Linter,可以用来检查代码语法风格以及格式化代码。这个延伸模块可以把 ESLint 的功能集成进 VS Code 中,就不用每次都打指令来操作 ESLint 了。Docker:Docker 是一种轻量级的操作系统虚拟化解决方案,可以用来制作开发或是运行 JavaScript 程序的所需环境。这个延伸模块除了可以让 VS Code 支持 Dockerfile 和 Docker Compose 的设置档之外,也有在 VS Code 内加入管理 Docker 映像和容器的功能,这样就不用每次都打指令来操作 Docker 了。Remote Development:这个延伸模块可以透过 SSH 打开远程的程序项目,也可以打开 Docker 容器或是 WSL 中的程序项目。Live Server:如果您是要开发 Web 前端相关的项目,这个延伸模块可以快速在本地端启动一个简单的 HTTP 服务器来帮助您查看您输出的文件(例如 HTML、CSS、JS)经由 HTTP 服务器提供后,在网页浏览器上运行的结果。
运行以下指令可以快速安装上面提到的 VS Code 延伸模块:
code --install-extension dbaeumer.vscode-eslint
code --install-extension ms-azuretools.vscode-docker
code --install-extension ms-vscode-remote.vscode-remote-extensionpack
code --install-extension ritwickdey.LiveServer
接着在 VS Code 的用户设置档(JSON 格式)中,加上以下设置:
{
...
"[json]": {
"editor.detectIndentation": false,
"editor.formatOnSave": true,
},
"[jsonc]": {
"editor.detectIndentation": false,
"editor.formatOnSave": false,
},
"[typescript]": {
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "always"
},
"editor.detectIndentation": false,
"editor.formatOnSave": false,
},
"js/ts.tsdk.path": "node_modules/typescript/lib",
...
}
加入以上设置后,VS Code 会在手动保存(非自动保存)JSON 文件的时候,如果它是标准的 JSON 格式,就会进行格式化(自动排版)。同样地,手动保存 TS 文件的时候,对该文件运行 eslint --fix 指令,自动修正能修正的代码语法,并进进程式码格式化。禁用 editor.detectIndentation 可以使 VS Code 的格式化功能严格遵守 VS Code 设置的 editor.tabSize 数值(默认值是 4),才不会不同文件的 TAB 字符的空格数量参差不齐。设置 js/ts.tsdk.path 是为了强制让 VS Code 去使用项目自己相依的 TypeScript,而非 VS Code 内置的,避免两个不一致产生一些「我错你对、你对我错」的问题。
除了 JSON 外,禁用 editor.formatOnSave 是因为 JSON 是单纯的数据传输格式,自动在保存文件时格式化并不会有什么影响。但是 JSON-C 可能有注解排版的问题,所以对其禁用自动格式化。TS 文件则因为 ESLint 也会进行格式化的关系,所以不需要再多运行一次格式化。
如果是在 Windows 操作系统上运行 VS Code,可以再加入如下的设置来让 TypeScript、JSON 等文件使用 Unix 系统的换行字符 LF (\n),而不是 Windows 系统的换行字符 CRLF (\r\n),以减少一些问题。
{
...
"files.eol": "\n",
...
}
创建 TypeScript 项目
不管是什么类型的 TypeScript 项目,都可以透过这个小节提供的方式来创建出最基本的雏型。
创建 Node.js 项目
在项目根目录中运行以下指令来产生出一个 Node.js 项目必定会有的 package.json 文件:
在这个指令动作的过程中,您可以顺便设置 package.json 中的部份字段值,像是版本号码,项目描述等等。
将 package.json 文件产生出来后,移除其中的 main 字段,再进行如下的修改:
{
...
"type": "module",
"exports": "./index.js",
"engines": {
"node": ">=22"
},
...
}
将 type 字段设为 module,可以使这个 Node.js 项目成为 ESM。最大的好处是我们可以直接使用 await,不需要先定义出一个 async 的函数再在里面写 await。exports 字段可以设置要用哪个文件 ./index.js 作为此 ESM 预设暴露出来的文件。engines.node 字段可以设置这个 Node.js 项目支持的 Node.js 版本范围。
加入 TypeScript
在项目根目录中运行以下指令来产生出一个 TypeScript 项目必定会有的 tsconfig.json 文件,此为 TypeScript 的设置档。
将 tsconfig.json 文件产生出来后,进行如下的修改:
{
"compilerOptions": {
...
"outDir": "./dist",
"module": "node20",
"target": "es2024",
// "types": [],
"sourceMap": false,
"declaration": false,
"declarationMap": false,
"noUncheckedIndexedAccess": false,
"exactOptionalPropertyTypes": false,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
...
}
}
将 compilerOptions.target 的字段值可以照着 Node.js 当前的 LTS 版本所能支持的最新 JavaScript 版本来设置(Node.js 22 就有支持到 ES2024),TypeScript 预设会用最新的版本。
compilerOptions.module 字段值设为 Node20 会依照其它设置来决定编译出来的模块要不要支持 CommonJS,抑或只是纯 ESM。当 package.json 中的 type 字段为 module,TypeScript 就会编译出纯 ESM。
compilerOptions.outDir 用来设置 TypeScript 所编译出来的 JavaScript 文件要放置哪个目录下,其底下的 JS 文件路径会相对于 TypeScript 编译器所编译的所有 TS 文件的共同上层目录(因为没设置 compilerOptions.rootDir)。笔者习惯把 TypeScript 源代码都放在 src 目录下,测试脚本都放在 tests 目录下,编译好的 JavaScript 文件都放在 dist 目录或 lib 目录下。
虽然在此处并未明确设置,但当 compilerOptions.module 字段值是 node16、node18、node20、nodenext 等等,compilerOptions.moduleResolution 的字段值会被预设为 node16 或是 nodenext,此时 TypeScript 编译器可以用 Node.js 惯用的套件路径写法来引用到 node_modules 目录中的套件,且 import 的路径中需要包含扩展名,如此才符合 Node.js ESM 的规范。
当 compilerOptions.esModuleInterop 字段值是 true 时,如果 bar 不是 ESM,则 import foo from "bar" 是可以被允许使用的,程序会尝试去使用模块暴露的 default 字段来当作 foo 的值。如果不存在 default,则会直接使用这个模块的参考,要注意此时也并不等同于 import * as foo from "bar",因为这个模块可能压根就不是一个对象(object),而是其他数据类型。
将 compilerOptions.noUncheckedIndexedAccess 和 compilerOptions.exactOptionalPropertyTypes 设为 false 是因为如果它们是设为 true 的话,TypeScript 写起来将会变得十分恼人,失去开发速度快的优势。
将 compilerOptions.types 注解掉可以使 TypeScript 去抓所有 @types/ 下的 .d.ts 定义档来用。
接着要创建另外一个专门用来建置项目的 TypeScript 设置档,命名为 tsconfig.build.json。文件内容如下:
{
"extends": "./tsconfig.json",
"include": [
"src/**/*",
]
}
extends 字段可以用来继承其它的 TypeScript 设置档。此处我们替原先的设置档添加 include 字段,用来限制 TypeScript 在建置项目时只去编译 src 目录下的文件。
之所以要分两个 TypeScript 设置档,是因为我们希望预设的 tsconfig.json 可以直接和 ESLint 一同使用,让 VS Code 可以对整个项目目录下的 JavaScript/TypeScript 文件作类型检查,而不是只能对 src 目录下的文件有作用。
然后还要修改 package.json 内的 scripts 字段,如下:
{
...
"scripts": {
"clean": "rimraf dist",
"build": "npm run clean && tsc -p tsconfig.build.json",
"lint": "eslint src",
"lint:fix": "npm run lint -- --fix"
}
...
}
如此一来,在项目根目录下运行 npm run clean 就可以清除输出目录;运行 npm run build 就可以在清空输出目录后,编译 TypeScript 代码;运行 npm run lint 就可以用 eslint 来检查 src 目录底下的 TypeScript 代码;运行 npm run lint:fix 就可以用 eslint 在检查代码的同时顺便进行修正。
当然,现在我们还没有把 tsc、ESLint、rimraf 加进项目。所以还要在项目根目录中运行以下指令,来安装相关的套件:
接着在项目根目录中添加 eslint.config.mjs 文件,内容如下:
import { defineConfig, globalIgnores } from "eslint/config";
import eslint from '@eslint/js';
import stylistic from "@stylistic/eslint-plugin";
import * as importPlugin from "eslint-plugin-import";
import globals from "globals";
import tseslint from "typescript-eslint";
export default defineConfig(
globalIgnores(["*.mjs", "dist/*"]),
eslint.configs.recommended,
...tseslint.configs.strictTypeChecked,
...tseslint.configs.stylisticTypeChecked,
{
languageOptions: {
globals: {
...globals.browser,
...globals.node,
},
parserOptions: {
projectService: true,
},
},
rules: {
// These rules relate to possible logic errors in code:
"array-callback-return": "error",
"no-constructor-return": "error",
"no-inner-declarations": ["error", "both"],
"no-promise-executor-return": "error",
"no-self-compare": "error",
"no-template-curly-in-string": "warn",
"no-unmodified-loop-condition": "warn",
"no-unreachable-loop": "error",
"require-atomic-updates": "error",
// These rules suggest alternate ways of doing things:
"accessor-pairs": "error",
"arrow-body-style": ["error", "as-needed"],
"block-scoped-var": "error",
"camelcase": ["error", {
properties: "never",
}],
"consistent-this": ["error", "self"],
"curly": "error",
"default-case-last": "error",
"eqeqeq": "error",
"func-names": ["error", "as-needed"],
"func-style": ["error", "expression"],
"grouped-accessor-pairs": "error",
"guard-for-in": "error",
"logical-assignment-operators": ["error", "always", {
enforceForIfStatements: true
}],
"new-cap": ["error", {
newIsCap: true,
capIsNew: true,
}],
"no-bitwise": ["error", {
int32Hint: true,
}],
"no-caller": "error",
"no-div-regex": "error",
"no-eq-null": "error",
"no-eval": "error",
"no-extend-native": "error",
"no-extra-bind": "error",
"no-extra-label": "error",
"no-implicit-coercion": "error",
"no-implicit-globals": "error",
"no-invalid-this": "error",
"no-iterator": "error",
"no-label-var": "error",
"no-lone-blocks": "error",
"no-lonely-if": "error",
"no-multi-assign": "error",
"no-nested-ternary": "error",
"no-new": "error",
"no-new-func": "error",
"no-new-wrappers": "error",
"no-object-constructor": "error",
"no-octal-escape": "error",
"no-plusplus": ["error", {
allowForLoopAfterthoughts: true,
}],
"no-proto": "error",
"no-return-assign": "error",
"no-sequences": "error",
"no-unneeded-ternary": "error",
"one-var": ["error", "never"],
"operator-assignment": "error",
"prefer-arrow-callback": "error",
"prefer-const": "error",
"prefer-exponentiation-operator": "error",
"prefer-numeric-literals": "error",
"prefer-object-has-own": "error",
"prefer-object-spread": "error",
"prefer-regex-literals": "error",
"prefer-rest-params": "error",
"prefer-spread": "error",
"prefer-template": "error",
"radix": ["error", "as-needed"],
"require-unicode-regexp": "error",
"sort-imports": ["error", {
ignoreDeclarationSort: true,
}],
"symbol-description": "error",
"vars-on-top": "error",
// These rules care about how the code looks rather than how it executes:
"unicode-bom": "error",
}
},
{
rules: {
// override
"@typescript-eslint/no-require-imports": ["error", {
allowAsImport: true,
}],
"@typescript-eslint/no-unused-vars": ["error", {
args: "all",
argsIgnorePattern: "^_",
caughtErrors: "all",
caughtErrorsIgnorePattern: "^_",
destructuredArrayIgnorePattern: "^_",
varsIgnorePattern: "^_",
ignoreRestSiblings: true,
}],
"@typescript-eslint/restrict-template-expressions": ["error", {
allowBoolean: true,
allowNullish: true,
allowNumber: true,
allowRegExp: true,
}],
// switch on
"@typescript-eslint/consistent-type-exports": "error",
"@typescript-eslint/consistent-type-imports": ["error", {
disallowTypeAnnotations: false,
fixStyle: "separate-type-imports",
prefer: "type-imports",
}],
"@typescript-eslint/default-param-last": "error",
"@typescript-eslint/explicit-function-return-type": "error",
"@typescript-eslint/explicit-member-accessibility": ["error", {
accessibility: "no-public",
}],
"@typescript-eslint/explicit-module-boundary-types": "error",
"@typescript-eslint/method-signature-style": "error",
"@typescript-eslint/no-import-type-side-effects": "error",
"@typescript-eslint/no-loop-func": "error",
"@typescript-eslint/no-unnecessary-parameter-property-assignment": "error",
"@typescript-eslint/no-unnecessary-qualifier": "error",
"@typescript-eslint/no-use-before-define": "error",
"@typescript-eslint/no-useless-empty-export": "error",
},
},
stylistic.configs['recommended'],
{
rules: {
// override
"@stylistic/arrow-parens": ["error", "always"],
"@stylistic/brace-style": ["error", "1tbs", {}],
"@stylistic/indent": ["error", 4, {
SwitchCase: 1,
}],
"@stylistic/indent-binary-ops": ["error", 4],
"@stylistic/lines-between-class-members": "off",
"@stylistic/member-delimiter-style": ["error", {}],
"@stylistic/multiline-ternary": ["error", "never"],
"@stylistic/no-extra-parens": ["error", "all", {
nestedBinaryExpressions: false,
}],
"@stylistic/no-mixed-operators": ["error", {}],
"@stylistic/no-multiple-empty-lines": ["error", {
max: 2,
maxEOF: 0,
maxBOF: 0,
}],
"@stylistic/no-trailing-spaces": ["error", {
skipBlankLines: true,
}],
"@stylistic/object-curly-spacing": ["error", "always", {
arraysInObjects: true,
objectsInObjects: true,
}],
"@stylistic/quote-props": ["error", "as-needed"],
"@stylistic/quotes": ["error", "double", {}],
"@stylistic/semi": ["error", "always"],
"@stylistic/semi-spacing": ["error", {
before: false,
after: true,
}],
"@stylistic/spaced-comment": ["error", "always", {}],
"@stylistic/wrap-iife": ["error", "outside", {}],
"@stylistic/yield-star-spacing": ["error", "after"],
// switch on
"@stylistic/array-bracket-newline": ["error", {
minItems: 4,
multiline: true,
}],
"@stylistic/array-element-newline": ["error", "consistent"],
"@stylistic/function-call-argument-newline": ["error", "consistent"],
"@stylistic/function-call-spacing": "error",
"@stylistic/function-paren-newline": ["error", "multiline-arguments"],
"@stylistic/generator-star-spacing": ["error", {
before: false,
after: true,
}],
"@stylistic/implicit-arrow-linebreak": "error",
"@stylistic/jsx-quotes": ["error", "prefer-double"],
"@stylistic/linebreak-style": "error",
"@stylistic/newline-per-chained-call": ["error", {
ignoreChainWithDepth: 3,
}],
"@stylistic/no-extra-semi": "error",
"@stylistic/nonblock-statement-body-position": "error",
"@stylistic/object-curly-newline": ["error", {
"ObjectExpression": { "multiline": true, "minProperties": 4 },
"ObjectPattern": { "multiline": true, "minProperties": 4 },
"ImportDeclaration": { "multiline": true, "minProperties": 4 },
"ExportDeclaration": { "multiline": true, "minProperties": 4 }
}],
"@stylistic/object-property-newline": ["error", {
allowAllPropertiesOnSameLine: true,
}],
"@stylistic/semi-style": "error",
"@stylistic/switch-colon-spacing": "error",
"@stylistic/wrap-regex": "error",
}
},
importPlugin.flatConfigs.recommended,
importPlugin.flatConfigs.typescript,
{
settings: {
"import/resolver": {
"typescript": true,
"node": true,
}
},
rules: {
// override
// switch on
"import/no-empty-named-blocks": "error",
"import/no-extraneous-dependencies": ["error", {
devDependencies: false,
}],
"import/no-mutable-exports": "error",
"import/no-unused-modules": ["warn", {
unusedExports: true,
src: [
"src/**/*",
],
}],
"import/no-absolute-path": "error",
"import/no-cycle": "error",
"import/no-self-import": "error",
"import/consistent-type-specifier-style": ["error", "prefer-top-level"],
"import/first": "error",
"import/newline-after-import": "error",
"import/no-named-default": "error",
"import/no-namespace": "warn",
"import/order": ["error", {
"newlines-between": "always-and-inside-groups",
alphabetize: {
order: "asc",
},
warnOnUnassignedImports: true,
}],
}
},
);
您也可以自行参考 ESLint 的官方文档、typescript-eslint 的官方文档、ESLint Stylistic 的官方文档和 eslint-plugin-import 的官方文档来设置 rules 字段。
另外,由于 eslint-plugin-import 有 Bug 存在,所以还需要添加 .eslintrc 文件到这个项目下,空文件即可。
设置好 ESLint 后,使用 VS Code 来打开这个 TypeScript 项目,就可以比较安心地撰写 TypeScript 代码了!
加入 Git
在项目根目录中运行以下指令来产生出一个 Git 项目必定会有的 .git 目录:
接着要在项目根目录中创建出 .gitignore 文件。考虑到 Node.js 项目常见的 IDE 有 VS Code 和 WebStorm 这两个,且考虑到也有一些坚持使用 Vim 来完成一切文字编辑相关事务的人,笔者的 .gitignore 文件内容如下:
### Intellij+all ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij+all Patch ###
# Ignore everything but code style settings and run configurations
# that are supposed to be shared within teams.
.idea/*
!.idea/codeStyles
!.idea/runConfigurations
### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
### Node Patch ###
# Serverless Webpack directories
.webpack/
# Optional stylelint cache
# SvelteKit build / generate output
.svelte-kit
### Vim ###
# Swap
[._]*.s[a-v][a-z]
!*.svg # comment out if you don't need vector files
[._]*.sw[a-p]
[._]s[a-rt-v][a-z]
[._]ss[a-gi-z]
[._]sw[a-p]
# Session
Session.vim
Sessionx.vim
# Temporary
.netrwhist
*~
# Auto-generated tag files
tags
# Persistent undo
[._]*.un~
### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
### VisualStudioCode Patch ###
# Ignore all local history of files
.history
.ionide
以上设置参考自 gitignore.io,异动部份已经标注。
再来要替项目加上 Git Hooks。有关于 Git Hooks 的说明可以参考以下这篇文章:
在项目根目录中添加 .githooks 目录,并在该目录下添加拥有可运行权限的 pre-commit 文件,内容如下:
#!/bin/bash
npm run lint
接着修改 package.json 中的 scripts 字段,如下:
{
...
"scripts": {
...
"prepare": "git config core.hooksPath .githooks || exit 0"
}
...
}
prepare 脚本会在 npm ci 或是 npm i 的时候被运行。当我们 clone 一个 Node.js 项目后,通常首先要做的事情就是 npm ci 或是 npm i,所以利用 prepare 脚本来设置 Git Hooks 的目录。
加入 VS Code 设置档
在项目根目录中添加 .vscode 目录,这个目录用来存放给 VS Code 看的设置档。
在 .vscode 目录中添加 tasks.json 文件,这个文件可以用来为 VS Code 添加任务(Task)。内容如下:
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "build",
"label": "Build",
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
tasks 字段底下可以设置多个任务。
每个任务都有 type 字段,用来设置这个任务的类型,npm 表示要运行 package.json 的 scripts 字段所设置的脚本。script 字段用来设置要运行的脚本名称。label 字段用来设置这个任务的名称。group 用来设置这个任务属于建构(build)还是测试(test)类型的任务,group.isDefault 用来设置这个任务是否为 group.kind 这个类型的预设任务。
以上设置,会将 npm run build 设为这个 Node.js 项目在 VS Code 中时的预设建构任务。在 VS Code 中,按下 Ctrl + Shift + b,就可以运行预设的建构任务,也就是说,会去运行到 npm run build。
在 VS Code 的命令选择区中,可以运行 Run Task 命令来选取一个任务来运行。
函数库项目
如果我们现在要创建的 TypeScript 项目是要给其它项目引入来用的话,就属于函数库项目。
除非您很清楚您接下来要实作的函数库都不会用到 Node.js 的任何模块,不然首先要运行以下指令将 Node.js 的定义套件加入 dependencies 中。
然后要修改 package.json,如下:
{
...
"exports": "./lib/lib.js",
"types": "./lib/lib.d.ts",
"files": ["lib"],
...
"scripts": {
"clean": "rimraf lib",
...
"build:watch": "npm run build -- -w",
...
"prepack": "npm run build"
}
...
}
对于函数库项目,笔者会将编译出来的 JavaScript 文件改放在 lib 目录下,这样在其它 Node.js 项目引用这个项目中特定 JS 文件的时候就会使用 foo/lib/bar 这样的路径,而不是 foo/dist/bar,后者看起来怪怪。
以上设置中,types 字段可以用来指定预设的定义档路径,这个文件等等会说明如何产生;files 字段可以填写打包(npm pack)这个 Node.js 项目时要包含进来的文件或是目录。
build:watch 脚本可以让 tsc 持续侦测文件的变化不断地去进行编译,方便在撰写代码的过程中实时找出有没有什么会编译错误的地方。
prepack 脚本会在运行 npm pack 或是 npm publish 指令时被自动运行,除了可以在发布程序之前检查是否能通过编译外,还能确保 lib 目录下的 JavaScript 文件是跟 TypeScript 源代码同步的。
再来是编辑 .gitignore 文件,加入 /lib。如下:
/lib
...
还要编辑 eslint.config.mjs 文件,将 ignores 的 dist/* 改为 lib/*。
再来是编辑 tsconfig.json 文件,如下:
{
"compilerOptions": {
...
"outDir": "./lib",
"declaration": true,
...
},
...
}
激活 declaration 可以在编译 TypeScript 的同时产生出 .d.ts 定义档。
接着修改 eslint.config.mjs 文件的 import/no-unused-modules 规则,如下:
{
...
"rules": {
...
"import/no-unused-modules": ["warn", {
unusedExports: true,
src: [
"src/**/*"
],
ignoreExports: [
"src/lib.ts",
],
}],
...
}
}
以上设置,可以让我们在 src/lib.ts 文件正常使用 export 关键字。
之后就是创建 src/lib.ts 文件,开始制作函数库啦!
一般来说,函数库项目输出的 ./lib 目录不需要进 Git 仓库,所以有在 .gitignore 文件中加入 /lib 来忽略。但如果您并未打算将函数库项目发布到 npm Registry,而是想要直接透过远程的 Git 仓库来安装使用的话,./lib 目录就应该要进 Git 仓库中。在这样的情况下,.gitignore 文件中不要忽略 /lib,且最好再加上 .githooks/pre-push 文件来保证开发端推到远程 Git 仓库上的 ./lib 目录是和 TypeScript 源代码有同步的,该文件的内容如下:
#!/bin/bash
npm run build
if ! git diff --exit-code -- lib; then
git add lib && git commit --no-verify -m "generate dist files"
fi
应用程序项目
如果我们现在要创建的 TypeScript 项目是要直接使用 node、pm2 等指令来运行的话,就属于应用程序项目。
由于是 Node.js 的应用程序,通常会使用到 Node.js 本身提供的模块。若预期会使用到,可以运行以下指令将 Node.js 的定义套件加入 devDependencies 中。
再来还要加入 nodemon 作为开发阶段用来运行项目的工具,它可以在文件发生变化的时候自动重新运行 JavaScript/TypeScript 程序。为了使 nodemon 能检查并运行 ESM + TypeScript 程序,还需要安装 ts-node。所以要运行以下指令来安装这两个套件:
在项目根目录下创建 ts-node 的脚本档,文件名为 ts-node.register.mjs,内容如下:
import { register } from "node:module";
import { pathToFileURL } from "node:url";
import { inspect } from "node:util";
const isTruthy = (v) => (/^(1|true|yes|y|on)$/i).test(String(v ?? "").trim());
const tsNodeLogErrorEnabled = isTruthy(process.env.TS_NODE_LOG_ERROR);
const useColor = Boolean(process.stderr.isTTY);
if (!tsNodeLogErrorEnabled) {
process.on("uncaughtException", (err) => {
if (useColor && !(err instanceof Error)) {
console.error(`\x1b[31m${inspect(err)}\x1b[0m`);
} else {
console.error(err);
}
process.exit(1);
});
}
register("ts-node/esm", pathToFileURL("./"));
TS_NODE_LOG_ERROR 是 ts-node 提供的功能,笔者不建议打开这个功能,因为会让程序在 TypeScript 类型检查错误后依然会去运行程序。
然后要删除 package.json 内的 exports 字段,接着做如下的修改:
{
...
"bin": "./dist/app.js",
...
"scripts": {
...
"start": "NODE_ENV=production node --enable-source-maps dist/app.js",
"start:dev": "NODE_ENV=development nodemon --exec \"node --enable-source-maps --import ./ts-node.register.mjs src/app.ts\" -e 'ts,json'",
...
}
...
}
start 脚本是正式环境时透过运行 npm start 指令来使用,会直接运行 JS 文件。start:dev 脚本是在开发环境使用,还可以结合 VS Code 的调试工具。而 NODE_ENV 是 Node.js 程序中常用来判断运行环境的环境变量。
这里要注意的是,如果您的应用程序项目有要在 Windows 环境上运行的话,NODE_ENV 环境变量用以上的方式来设置是会出问题的。解决方法是使用以下指令来安装 run-with-node-env 套件:
然后要再次修改 package.json,如下:
{
...
"scripts": {
...
"start": "run-with-node-env production node --enable-source-maps dist/app.js",
"start:dev": "run-with-node-env development nodemon --exec \"node --enable-source-maps --import ./ts-node.register.mjs src/app.ts\" -e 'ts,json'",
...
}
...
}
tsconfig.json 文件要加上如下的设置,使 TypeScript 编译器能产生 SourceMap 文件,以及让 ts-node 能正常动作。
{
"compilerOptions": {
...
"sourceMap": true,
...
},
...
"ts-node": {
"files": true
}
}
再来要在 .vscode 目录下添加 launch.json 文件,内容如下:
{
"version": "0.2.0",
"configurations": [
{
"type": "node-terminal",
"name": "start:dev",
"request": "launch",
"command": "npm run start:dev"
}
]
}
configurations 字段底下可以设置多笔调试组态。
每个组态都有 type 字段,用来设置这个组态的类型,node-terminal 表示要使用 VS Code 的 JavaScript Debug Terminal。name 字段用来设置这个组态的名称,会显示在 VS Code 调试工具的组态菜单中。request 字段用来设置这个组态是要启动(launch)新的进程(process),还是要将已有的进程给附加(attach)进来。command 用来设置这个组态要运行的指令。
有了这个组态设置,在 VS Code 的调试工具中,就可以选择 start:dev 来运行与调试。
之后就是创建 src/app.ts 文件,开始制作应用程序啦!
加入 Jest 测试框架至 TypeScript 项目
开发 JavaScript/TypeScript 程序,测试是非常重要的一环。笔者选用的测试工具是 Facebook 开发的 Jest 测试框架,比起同样很多人使用的 Mocha,Jest 在使用上更为简易。
运行以下指令来安装所需的相关套件:
然后要修改 package.json,如下:
{
...
"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
"test:coverage": "node --experimental-vm-modules node_modules/jest/bin/jest.js --coverage",
"test:inspect-brk": "node --experimental-vm-modules --inspect-brk=0.0.0.0:9230 node_modules/jest/bin/jest.js --testTimeout 0 --runInBand",
...
"lint": "eslint src tests",
...
"prepublishOnly": "npm run lint && npm run test"
}
...
}
test 脚本会运行 jest 进行测试。test:coverage 脚本可以导出测试覆盖率。test:inspect-brk 脚本可以在运行测试的时候先等待测试进程附加至调试工具后才开始动作,之所以监听 0.0.0.0 而不是 127.0.0.1 是为了让测试即便在 Docker 容器中运行,也还是可以在 Host 环境来调试。
prepublishOnly 脚本会在运行 npm publish 指令时被自动运行(prepublishOnly 脚本运行完后是 prepack 脚本),可以在发布程序之前检查是否能通过代码校验和测试。
然后要修改 tsconfig.build.json 文件,排除掉文件名为 .spec.ts 或 .test.ts 结尾的文件。这样的话要写单元测试也可以在 src 目录中的某个 .ts 文件旁边创建出一个 .spec.ts 或 .test.ts 文件来专门为该 .ts 文件写单元测试。Jest 预设会可执行文件名为 .spec.ts 或 .test.ts 结尾的文件。
{
...
"exclude": [
"**/*.spec.ts",
"**/*.test.ts"
]
}
要让 Jest 能运行 TypeScript 程序,还要加上 jest.config.json 文件,内容如下:
{
"extensionsToTreatAsEsm": [
".ts"
],
"transform": {
"^.+\\.[jt]sx?$": [
"ts-jest",
{
"useESM": true
}
]
},
"moduleNameMapper": {
"^(\\.\\.?\\/.+)\\.jsx?$": "$1"
}
}
以上的 moduleNameMapper 字段是要将引用到我们自己项目下的 js 文件给去掉扩展名,不然 Jest 会找不到该文件。
再来要修改 .vscode/tasks.json 文件,添加新任务进去。如下:
{
...
"tasks": [
...
{
"type": "npm",
"script": "test",
"label": "Test",
"group": {
"kind": "test",
"isDefault": true
}
}
]
}
以上设置,会将 npm run test 设为这个 Node.js 项目在 VS Code 中时的预设测试任务。在 VS Code 的命令选择区中,可以运行 Run Test Task 命令来运行预设的测试任务,当然,您也可以替这个命令设置快速键(设成 Alt + t 还蛮好用的,而 Run Build Task 则可以改设为 Alt + b)。
再来要修改 .vscode/launch.json 文件,添加新组态进去。如果您是函数库项目,并不会有 .vscode/launch.json 文件,请自行添加,相关说明可以参考创建应用程序项目的小节。将 .vscode/launch.json 文件修改如下:
{
"version": "0.2.0",
"configurations": [
...
{
"type": "node-terminal",
"name": "test",
"request": "launch",
"command": "npm test"
},
{
"type": "node",
"name": "test:inspect-brk",
"request": "attach",
"port": 9230
}
]
}
运行 test:inspect-brk 组态之前,要先运行 npm run test:inspect-brk 指令。
接着修改 eslint.config.mjs 文件的 import/no-extraneous-dependencies 规则,如下:
{
...
"rules": {
...
"import/no-extraneous-dependencies": ["error", {
devDependencies: [
"tests/**/*",
"**/*.test.ts",
"**/*.spec.ts",
],
}],
...
}
}
在撰写测试的时候,我们可能会需要引用到只有在测试程序中才会使用到的套件,此时应将这类新套件使用 pnpm i -D <套件名称> 指令来安装,将套件安装至 package.json 文件的 devDependencies 字段中。如此一来当这个 Node.js 项目被其它项目引用的时候,就不需要再去相依只有在这个 Node.js 项目进行测试时才会用到的套件。
eslint.config.mjs 文件中,import/no-extraneous-dependencies 规则能设置除了指定的路径外,其余的地方都不能引用属于 devDependencies 的套件,以免目前这个程序项目被其它项目引用的时候发生缺少套件的问题。而以上设置,可以允许写在 package.json 文件的 devDependencies 字段中的套件能在我们的测试程序中引用。
最后,我们可以添加 tests/template.test.ts 文件来测试看看 Jest 框架有没有加入成功。文件内容如下:
describe("Hello Jest", () => {
it("should success", () => {
expect(true).toBe(true);
});
});
然后在项目根目录下运行 npm test 指令试试吧!
加入 Web 框架至 TypeScript 项目
不同的 Web 框架有不同的用法,可以参考下列的延伸文章:

