JavaScript:nanogql(客户端)
graphql-github-io-zh-Hans生态项目与库
nanogql:极简模板字符串 GraphQL 客户端
nanogql 是一个体积小巧的 GraphQL 客户端库,核心卖点在于允许开发者通过 ES6 模板字符串直接编写 GraphQL 查询与变更(Mutation),而无需引入繁重的运行时依赖。
项目信息
- 项目名称:nanogql
- 描述:使用模板字符串的微型 GraphQL 客户端库
- GitHub:yoshuawuyts/nanogql
- npm 包名:
nanographql - 所属分类:生态项目与库
安装
通过 npm 安装时,请注意包名与项目名的差异:
bash
npm install nanographql
基本用法
nanographql 默认导出一个模板字符串标签函数,用于将 GraphQL 查询字符串编译为可执行的请求函数。
1. 简单查询
js
const graphql = require('nanographql')
const query = graphql`
query ($id: ID!) {
user (id: $id) {
name
}
}
`
// 生成请求配置(需配合 fetch 或其他 HTTP 客户端使用)
const fetchOptions = query({
variables: { id: 'abc123' }
})
fetch('/graphql', fetchOptions)
.then(res => res.json())
.then(data => console.log(data))
2. 传递变量
编译后的函数接收一个 { variables } 对象,自动将变量填充到查询字符串中:
js
const query = graphql`
query ($name: String!) {
hello (name: $name)
}
`
const { query: queryString, variables } = query({
variables: { name: 'World' }
})
console.log(queryString) // 展开后的完整查询语句
3. 变更操作
同样支持 mutation 语法:
js
const mutation = graphql`
mutation ($input: CreatePostInput!) {
createPost (input: $input) {
id
title
}
}
`
fetch('/graphql', mutation({
variables: {
input: { title: 'Hello' }
}
}))
API 概览
| 成员 | 类型 | 说明 |
|---|---|---|
graphql |
函数 | 默认导出,作为模板字符串标签使用 |
| 返回函数 | Function |
接受 { variables } 参数,输出包含 query、variables 的请求配置对象 |
返回的请求配置结构:
js
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: '...', // 解析后的查询字符串
variables: { ... } // 原始变量对象
})
}
特性与优势
- 零依赖:核心实现极简,无任何运行时依赖,适合轻量级项目和函数计算环境
- 模板字符串原生语法:无需编写额外构建配置,直接在 JavaScript 中书写 GraphQL 文档
- 自动变量插值:基于模板字符串的替换机制,将变量安全注入查询文本
- 框架无关:可与
fetch、axios或任何 HTTP 客户端自由搭配
相关链接
- GitHub 仓库:https://github.com/yoshuawuyts/nanogql
- 源码镜像/组织:choojs/nanographql
提示:对于复杂查询、缓存或订阅等高级需求,建议评估其他功能更完整的客户端(如 Apollo Client 或 urql)。
nanographql专注于“小而美”的场景,适合对体积敏感或需要快速原型验证的项目。
帮助我们改进文档
发现翻译问题或内容错误?请告诉我们。
