头图

现代 Node.js 的开发体验,已经不输 Golang、Rust 这些新兴编程语言。而且,比起使用它的兄弟语言 Deno、Bun,使用 Node 开发项目,坑更少一些,生态也更好一些。

Node.js 的一个特点就是轻便。这个特点我想主要是相比 Java 这种略显笨重的语言来说的。据说,国外的创新项目大部分都是用 Node 来开发的。(在很久以前,是用 PHP 或者 Ruby on Rails 开发。)猜测其原因之一,是前后端统一用一种编程语言能方便代码复用减少切换。国内的项目,由于前后端职责分离,后端程序员使用 Java、Golang 较多。

在 2024 年,创建一个全新的 Node.js 项目并获得不错的开发体验,例如类型校验、格式化、风格检查、单元测试、打包部署,变得非常简单。我们采用的开发工具有:

  • vscode - 开源免费 IDE
  • pnpm - Node 包管理器

创建空项目

pnpm init
mkdir src
mkdir test

设置 TypeScript

pnpm add -D typescript @types/node

更新 package.json,采用 ESM 并加上构建脚本。

{
    "type": "module",
    "scripts": {
        "build": "tsc"
    },
}

增加 tsconfig.json,含有下面这些选项。

{
    "compilerOptions": {
        "module": "nodenext",
        "moduleResolution": "nodenext",
        "target": "esnext",
        "sourceMap": true,
        "outDir": "dist"
    },
    "include": [
        "src",
        "test"
    ]
}

试运行

src 下增加项目的源文件,比如 hello.ts

import { createServer } from 'node:http';
const server = createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello World!\n');
});
// starts a simple http server locally on port 3000
server.listen(3000, '127.0.0.1', () => {
    console.log('Listening on 127.0.0.1:3000');
});

构建并运行

pnpm install
pnpm build
node dist/hello.js
> Listening on 127.0.0.1:3000

为了获得最佳的开发体验,可以选用以下配置

格式化和风格检查

pnpm add -D -E @biomejs/biome
pnpm biome init
pnpm biome check src
pnpm biome check src --apply

推荐安装 vscode 的插件,在保存的时候自动格式化。

单元测试

test 下增加测试用例的源文件,比如 hello.test.ts

import assert from 'node:assert';
import test from 'node:test';
test('that 1 is equal 1', () => {
    assert.strictEqual(1, 1);
});
test('that throws as 1 is not equal 2', () => {
    // throws an exception because 1 != 2
    assert.strictEqual(1, 2);
});

构建并运行测试用例

pnpm build
node --test dist/test

断点调试

.vscode 下新增 launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Debug",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "program": "${workspaceFolder}/src/hello.ts",
            "outFiles": [
                "${workspaceFolder}/dist/**/*.js",
                "!**/node_modules/**"
            ]
        }
    ]
}

打包成单文件(部署)

pnpm add -D -E esbuild
pnpm esbuild src/hello.ts --bundle --platform=node --target=node18 --outfile=dist/main.js

生成的 dist/main.js 能在任何安装了 node18 的环境下运行,不需要安装依赖。

总结

最终项目的目录像这个样子

.
├── biome.json
├── package.json
├── tsconfig.json
├── src
│   └── hello.ts
└── test
    └── hello.test.ts

使用到下面这些命令

pnpm install
pnpm build
pnpm biome check src test
node --test dist/test
node dist/src/hello.js

在 2024 年, Node.js 及其生态已经出现了一些现代化的开发工具,能够简洁的创建项目并获得不错的开发体验。一个支持类型校验、格式化、风格检查、单元测试的新项目只包含 5 个文件,极大程度的降低了新项目的门槛和“样板代码”的数量。

作为参考,本文的示例项目能在这里获取到。


黄灏
4 声望0 粉丝

一个技术爱好者。