Tarojs
支持 react / vue, 因此配置 graphql
较为简单,以下以 urql
客户端为例
参考文档
- https://nearform.com/open-source/urql/docs/basics/react-preact/
- https://nearform.com/open-source/urql/docs/basics/typescript-integration/
安装
精简命令
1 2
| npm install --save urql npm install -D graphql typescript @graphql-codegen/cli @graphql-codegen/client-preset
|
配置 Codegen 生成客户端代码
codegen.ts1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const config: CodegenConfig = { schema: "http://localhost:3000/graphql", documents: ["src/schema/*.graphql", "src/schema/*.ts"], ignoreNoDocuments: true, generates: { "./src/gql/": { preset: "client", plugins: [], config: { useTypeImports: true, }, }, }, }
export default config
|
package.json1 2 3 4
| "codegen": "graphql-codegen",
|
配置 urql
src/app.tsx1 2 3 4 5 6 7 8 9 10 11 12
| import { Client, Provider as UrqlProvider, cacheExchange, fetchExchange } from 'urql';
const client = new Client({ url: '/graphql', exchanges: [cacheExchange, fetchExchange], });
function App(props: { children: React.ReactNode }) {
return <UrqlProvider value={client}>{props.children}</UrqlProvider>; }
|
为避免浏览器提供 CORS 跨域错误,配置 GraphQL
代理服务器
config/dev.ts1 2 3 4 5 6 7 8 9 10 11 12
|
devServer: { proxy: { '/graphql': { target: 'http://localhost:3000', changeOrigin: true, secure: false, }, }, },
|
GraphQl 调用示例
src/schema/home.ts1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| import { useQuery } from "urql" import { graphql } from "~/gql"
export const fetchTabs = graphql(` query FetchTabs { litemallCategory( orderBy: { sortOrder: { direction: asc, priority: 10 } } where: { level: { eq: "L1" } } limit: 8 ) { id name iconUrl } } `)
export function fetchTabList() { const [{data}] = useQuery({ query: fetchTabs })
return data }
export const fetchNewGoods = graphql(` query FetchNewGoods($limit: Int!, $offset: Int!) { litemallGoods( orderBy: { sortOrder: { direction: asc, priority: 10 } } where: { isOnSale: { eq: true }, isNew: { eq: true } } limit: $limit offset: $offset ) { id goodsSn name categoryId gallery keywords brief picUrl shareUrl isNew isHot unit counterPrice retailPrice detail } } `)
export async function fetchNewGoodsList(limit: number, offset: number) { const [{data}] = useQuery({ query: fetchNewGoods, variables: { limit, offset } })
return data }
|
完成
写完 GraphQL
语句后,运行 npm codegen
,即可在 src/gql/
下生成相应的类型代码。