Babel Relay Plugin #Facebook Relay文档翻译#

鲁昕
2023-12-01

原文地址
上一篇 Network Layer
Relay文档翻译目录

Relay uses a babel plugin to convert from Relay.QL string templates to
JavaScript code that describes each query and includes data from the GraphQL
schema.
Relay使用**babel**plugin来将Relay.QL字符串模板转换成描述查询的JS代码,还能通过GraphQL schema来引入数据。

While you type queries as follows:
当你用下面方式写query的时候:

Relay.QL`
  fragment on User {
    # ...
  }
`

This gets converted into an immediately-invoked function:
它将转换成一个立刻执行函数

(function() {
  // Return a description of the query ...
})();

Usage

The easiest way to get started for now is with the Relay Starter Kit - this includes an example schema file and configures the babel-relay-plugin npm module to transpile queries.
最简单的方式开始使用Relay是通过Relay Starter Kit,它包含了schema的样例,配置好了babel-relay-plugin

Advanced Usage

If you’re not using the starter kit, you’ll have to configure babel to use the babel-relay-plugin. The steps are as follows:
如果你不用start kit,你需要配置babel来使用babel-relay-plugin,步骤如下:

// `babel-relay-plugin` returns a function for creating plugin instances
var getBabelRelayPlugin = require('babel-relay-plugin');

// load previously saved schema data (see "Schema JSON" below)
var schemaData = require('schema.json');

// create a plugin instance
var plugin = getBabelRelayPlugin(schemaData);

// compile code with babel using the plugin
return babel.transform(source, {
  plugins: [plugin],
});

Schema JSON

The plugin needs to understand your schema - schemaData in the above snippet. There are two ways to get this information, depending on the GraphQL implementation.
该插件需要理解你的schema——上面的schemaData片段。有两种方法获得该信息,取决于GraphQL的实现。

Using graphql

An example of how to load a schema.js file, run the introspection query to get schema information, and save it to a JSON file can be found in the starter kit.
加载schema.js的例子,在 starter kit中运行自检查询获得schema信息,并且输出到一个JSON文件中。

Using Other GraphQL Implementations

If you’re using a different GraphQL server implementation, we recommend adapting the above example to load the schema from your GraphQL server (e.g. via an HTTP request) and then save the result as JSON.
如果你使用的是不同的GraphQL实现,我们建议您适配上面的例子,通过您的GraphQL server加载schema并输出JSON。

Additional Options

By default, babel-relay-plugin catches GraphQL validation errors and logs them without exiting. The compiled code will also throw the same errors at runtime, making it obvious that something went wrong whether you’re looking at your terminal or browser console.
默认情况,babel-relay-plugin捕捉GraphQL的校验错误并且在不退出的情况下记下错误日志。编译的代码运行时还是会继续抛出该错误,让你可以在终端上容易的看到错误。

When compiling code for production deployment, the plugin can be configured to immediately throw upon encountering a validation problem:
当编译在生产环境部署时,该插件可以被配置为遇到校验错误立刻中止。

var plugin = getBabelRelayPlugin(schemaData, {
  abortOnError: true,
});
 类似资料: