moai-lang-javascript

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Quick Reference (30 seconds)

快速参考(30秒)

JavaScript ES2024+ Development Specialist - Modern JavaScript with Node.js 22 LTS, multiple runtimes, and contemporary tooling.
Auto-Triggers: Files with .js, .mjs, or .cjs extensions, package.json, Node.js projects, JavaScript discussions
Core Stack:
  • ES2024+: Set methods, Promise.withResolvers, immutable arrays, import attributes
  • Node.js 22 LTS: Native TypeScript, built-in WebSocket, stable watch mode
  • Runtimes: Node.js 20 and 22 LTS, Deno 2.x, Bun 1.x
  • Testing: Vitest, Jest, Node.js test runner
  • Linting: ESLint 9 flat config, Biome
  • Bundlers: Vite, esbuild, Rollup
  • Frameworks: Express, Fastify, Hono, Koa
Quick Commands:
Create a Vite project using npm create vite with latest tag, project name, and vanilla template. Initialize with modern tooling using npm init and npm install with D flag for vitest, eslint, and eslint/js. Run with Node.js watch mode using node with watch flag. Run TypeScript directly in Node.js 22+ using node with experimental-strip-types flag.

JavaScript ES2024+开发专家 - 基于Node.js 22 LTS、多运行时及现代工具链的现代JavaScript开发。
自动触发场景:带有.js、.mjs或.cjs扩展名的文件,package.json,Node.js项目,JavaScript相关讨论
核心技术栈:
  • ES2024+:Set方法、Promise.withResolvers、不可变数组、导入属性
  • Node.js 22 LTS:原生TypeScript、内置WebSocket、稳定的监听模式
  • 运行时:Node.js 20和22 LTS、Deno 2.x、Bun 1.x
  • 测试:Vitest、Jest、Node.js测试运行器
  • 代码检查:ESLint 9扁平配置、Biome
  • 打包工具:Vite、esbuild、Rollup
  • 框架:Express、Fastify、Hono、Koa
快速命令:
使用npm create vite命令,指定latest标签、项目名称和vanilla模板来创建Vite项目。使用npm init和npm install命令并加上-D标志初始化Vitest、ESLint及eslint/js等现代工具。使用node加watch标志启用Node.js监听模式运行。在Node.js 22+中使用node加experimental-strip-types标志直接运行TypeScript。

Implementation Guide (5 minutes)

实施指南(5分钟)

ES2024 Key Features

ES2024核心特性

Set Operations:
Create setA with values 1, 2, 3, 4 and setB with values 3, 4, 5, 6. Call setA.intersection with setB to get Set containing 3 and 4. Call setA.union with setB to get Set containing 1 through 6. Call setA.difference with setB to get Set containing 1 and 2. Call setA.symmetricDifference with setB to get Set containing 1, 2, 5, and 6. Call isSubsetOf, isSupersetOf, and isDisjointFrom methods for set comparisons.
Promise.withResolvers:
Create a createDeferred function that destructures promise, resolve, and reject from Promise.withResolvers call. Return an object with these three properties. Create a deferred instance, set a timeout to resolve with done after 1000 milliseconds, and await the promise for the result.
Immutable Array Methods:
Create original array with values 3, 1, 4, 1, 5. Call toSorted to get new sorted array without mutating original. Call toReversed to get new reversed array. Call toSpliced with index 1, delete count 2, and insert value 9. Call with method at index 2 with value 99 to get new array with replaced element. The original array remains unchanged.
Object.groupBy and Map.groupBy:
Create items array with objects containing type and name properties. Call Object.groupBy with items and a function that returns item.type to get an object with arrays grouped by type. Call Map.groupBy with the same arguments to get a Map with type keys and array values.
集合操作:
创建包含值1、2、3、4的setA和包含值3、4、5、6的setB。调用setA.intersection(setB)获取包含3和4的Set。调用setA.union(setB)获取包含1至6的Set。调用setA.difference(setB)获取包含1和2的Set。调用setA.symmetricDifference(setB)获取包含1、2、5和6的Set。调用isSubsetOf、isSupersetOf和isDisjointFrom方法进行集合比较。
Promise.withResolvers:
创建createDeferred函数,从Promise.withResolvers()调用中解构出promise、resolve和reject。返回包含这三个属性的对象。创建deferred实例,设置1000毫秒后用'done'值resolve的定时器,然后await该promise获取结果。
不可变数组方法:
创建包含值3、1、4、1、5的原始数组。调用toSorted获取新的排序数组,不会修改原数组。调用toReversed获取新的反转数组。调用toSpliced(1, 2, 9)进行插入删除操作。调用with(2, 99)方法获取替换指定索引元素后的新数组。原始数组保持不变。
Object.groupBy和Map.groupBy:
创建包含type和name属性对象的items数组。调用Object.groupBy(items, item => item.type)获取按type分组的对象。使用相同参数调用Map.groupBy获取以type为键、数组为值的Map。

ES2025 Features

ES2025特性

Import Attributes for JSON Modules:
Import config from config.json with type attribute set to json. Import styles from styles.css with type attribute set to css. Access config.apiUrl property.
RegExp.escape:
Create userInput string with special characters like parentheses. Call RegExp.escape with userInput to get escaped pattern string. Create new RegExp with the safe pattern.
JSON模块的导入属性:
使用type属性设置为json从config.json导入config。使用type属性设置为css从styles.css导入styles。访问config.apiUrl属性。
RegExp.escape:
创建包含括号等特殊字符的userInput字符串。调用RegExp.escape(userInput)获取转义后的模式字符串。使用安全模式创建新的RegExp。

Node.js 22 LTS Features

Node.js 22 LTS特性

Built-in WebSocket Client:
Create new WebSocket with wss URL. Add event listener for open event that sends JSON stringified message. Add event listener for message event that parses event.data as JSON and logs the received data.
Native TypeScript Support Experimental:
Run .ts files directly in Node.js 22.6+ using node with experimental-strip-types flag. In Node.js 22.18+, type stripping is enabled by default so files can be run directly.
Watch Mode Stable:
Use node with watch flag for auto-restart on file changes. Use watch-path flag multiple times to watch specific directories like src and config.
Permission Model:
Use node with permission flag and allow-fs-read set to a specific path to restrict file system access. Use allow-net flag with domain name to restrict network access.
内置WebSocket客户端:
使用wss URL创建新的WebSocket。添加open事件监听器,发送JSON字符串化的消息。添加message事件监听器,将event.data解析为JSON并打印接收到的数据。
实验性原生TypeScript支持:
在Node.js 22.6+中使用node加experimental-strip-types标志直接运行.ts文件。在Node.js 22.18+中,类型剥离默认启用,可直接运行文件。
稳定的监听模式:
使用node加watch标志实现文件变更时自动重启。多次使用watch-path标志监听src和config等特定目录。
权限模型:
使用node加permission标志,并设置allow-fs-read为特定路径来限制文件系统访问。使用allow-net标志并指定域名来限制网络访问。

Backend Frameworks

后端框架

Express Traditional Pattern:
Import express. Create app by calling express function. Use express.json middleware. Create a get endpoint at api/users that awaits database query and responds with json. Create a post endpoint that creates a user and responds with status 201 and json. Call listen on port 3000 with callback logging server running.
Fastify High Performance Pattern:
Import Fastify. Create fastify instance with logger set to true. Define userSchema with body containing type object, required array with name and email, and properties with validation constraints. Create a post endpoint with schema option and async handler that creates user and returns with code 201. Call listen with port 3000.
Hono Edge-First Pattern:
Import Hono and middleware functions. Create app instance. Use logger middleware for all routes. Use cors middleware for api routes. Create get endpoint at api/users that awaits database query and returns c.json. Create post endpoint with validator middleware that checks for required fields, then creates user and returns c.json with status 201. Export app as default.
Express传统模式:
导入express。调用express()函数创建app。使用express.json中间件。创建/api/users的GET端点,await数据库查询并返回json响应。创建POST端点创建用户,返回状态码201和json响应。调用listen监听3000端口,回调函数打印服务器运行信息。
Fastify高性能模式:
导入Fastify。创建logger设置为true的Fastify实例。定义userSchema,body为对象类型,required数组包含name和email,properties设置验证约束。创建带schema选项的POST端点,异步处理函数创建用户并返回状态码201。调用listen监听3000端口。
Hono优先边缘模式:
导入Hono及中间件函数。创建app实例。为所有路由使用logger中间件。为api路由使用cors中间件。创建/api/users的GET端点,await数据库查询并返回c.json。创建带validator中间件的POST端点,检查必填字段后创建用户,返回状态码201的c.json。将app导出为默认值。

Testing with Vitest

使用Vitest进行测试

Configuration:
Create vitest.config.js with defineConfig. Set test object with globals true, environment node, and coverage with provider v8 and reporters for text, json, and html.
Test Example:
In test file, import describe, it, expect, vi, and beforeEach from vitest. Import functions to test. Create describe block for User Service. In beforeEach, call vi.clearAllMocks. Create it block for should create a user that awaits createUser and expects result to match object with name and email, and id to be defined. Create it block for should throw on invalid email that expects createUser to reject with Invalid email error.
配置:
创建vitest.config.js,使用defineConfig。设置test对象,globals为true,environment为node,coverage使用v8提供者,reporters为text、json和html。
测试示例:
在测试文件中,从vitest导入describe、it、expect、vi和beforeEach。导入要测试的函数。创建User Service的describe块。在beforeEach中调用vi.clearAllMocks()。创建should create a user的it块,await createUser并断言结果匹配包含name和email的对象,且id已定义。创建should throw on invalid email的it块,断言createUser会抛出Invalid email错误。

ESLint 9 Flat Config

ESLint 9扁平配置

Create eslint.config.js. Import js from eslint/js and globals. Export array with js.configs.recommended followed by object with languageOptions containing ecmaVersion 2025, sourceType module, and globals merged from globals.node and globals.es2025. Set rules for no-unused-vars with error and args ignore pattern, no-console with warn and allowed methods, prefer-const as error, and no-var as error.
创建eslint.config.js。从eslint/js和globals导入js。导出数组,包含js.configs.recommended,后续对象的languageOptions设置ecmaVersion为2025,sourceType为module,globals合并globals.node和globals.es2025。设置rules:no-unused-vars为error并指定args忽略模式,no-console为warn并指定允许的方法,prefer-const为error,no-var为error。

Biome All-in-One

Biome一体化工具

Create biome.json with schema URL. Enable organizeImports. Set linter enabled with recommended rules. Set formatter enabled with indentStyle space and indentWidth 2. Under javascript.formatter, set quoteStyle to single and semicolons to always.

创建biome.json并指定schema URL。启用organizeImports。启用linter并使用推荐规则。启用formatter,indentStyle为space,indentWidth为2。在javascript.formatter下设置quoteStyle为single,semicolons为always。

Advanced Patterns

高级模式

For comprehensive documentation including advanced async patterns, module system details, performance optimization, and production deployment configurations, see:
  • reference.md for complete API reference, Context7 library mappings, and package manager comparison
  • examples.md for production-ready code examples, full-stack patterns, and testing templates
如需包含高级异步模式、模块系统细节、性能优化及生产部署配置的完整文档,请查看:
  • reference.md:完整API参考、Context7库映射及包管理器对比
  • examples.md:生产就绪代码示例、全栈模式及测试模板

Context7 Integration

Context7集成

For Node.js documentation, use context7 get library docs with nodejs/node and topics like esm modules async. For Express, use expressjs/express with middleware routing. For Fastify, use fastify/fastify with plugins hooks. For Hono, use honojs/hono with middleware validators. For Vitest, use vitest-dev/vitest with mocking coverage.

对于Node.js文档,使用context7 get library docs命令,指定nodejs/node及esm modules async等主题。对于Express,指定expressjs/express及middleware routing主题。对于Fastify,指定fastify/fastify及plugins hooks主题。对于Hono,指定honojs/hono及middleware validators主题。对于Vitest,指定vitest-dev/vitest及mocking coverage主题。

Works Well With

适配工具

  • moai-lang-typescript for TypeScript integration and type checking with JSDoc
  • moai-domain-backend for API design and microservices architecture
  • moai-domain-database for database integration and ORM patterns
  • moai-workflow-testing for DDD workflows and testing strategies
  • moai-foundation-quality for code quality standards
  • moai-essentials-debug for debugging JavaScript applications

  • moai-lang-typescript:TypeScript集成及JSDoc类型检查
  • moai-domain-backend:API设计及微服务架构
  • moai-domain-database:数据库集成及ORM模式
  • moai-workflow-testing:DDD工作流及测试策略
  • moai-foundation-quality:代码质量标准
  • moai-essentials-debug:JavaScript应用调试

最后更新:2026-01-11 状态:活跃(v1.2.0)

Quick Troubleshooting

Module System Issues:
Check package.json for type field. ESM uses type module with import and export. CommonJS uses type commonjs or omits the field and uses require and module.exports.
Node.js Version Check:
Run node with version flag for 20.x or 22.x LTS. Run npm with version flag for 10.x or later.
Common Fixes:
Clear npm cache with npm cache clean using force flag. Delete node_modules and package-lock.json then run npm install. Fix permission issues by setting npm config prefix to home directory npm-global folder.
ESM and CommonJS Interop:
To import CommonJS from ESM, import the default then destructure named exports from it. For dynamic import in CommonJS, use await import and destructure the default property.

Last Updated: 2026-01-11 Status: Active (v1.2.0)