1、安裝CLI
$ yarn add -D graphql @graphql-codegen/cli
2、初始化
$ graphql-codegen init
gql文件示例
// backend-id-options.gql query getBackendIdOptions($content: String, $backendIds: [Int!]) { backendIdOptions(content: $content, backendIds: $backendIds) { name sellerPhone accountType id disabled } }
// current-user.gql query CurrentUser { currentUser { role liveRoom { id name } } }
初始化命令執行後會在根目錄下生成 codegen.yml,這個文件可以根據 graphql 的接口自動生成調用方法,生成文件在 libs/xxx/graphql/documents.ts(這個地址是你自己項目裏配置的地址),然後直接引用裏面的方法來調接口
// codegen.yml
overwrite: true
schema: "http://localhost:3333/xxx-api/graphql"
documents: "libs/xxx/graphql/**/*.{gql,graphql}"
generates:
libs/xxx/graphql/documents.ts:
plugins:
- "typescript"
- "typescript-operations"
- "typescript-apollo-angular"
注意:接口地址必須指定正確,否則執行命令會報錯
3、執行生成命令
// package.json
"scripts": {
"generate": "graphql-codegen --config codegen.yml"
}