-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
BabelPluginRelay.js
109 lines (100 loc) · 2.87 KB
/
BabelPluginRelay.js
1
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule BabelPluginRelay
* @flow
* @format
*/
'use strict';
const compileGraphQLTag = require('./compileGraphQLTag');
const compileRelayQLTag = require('./compileRelayQLTag');
const getDocumentName = require('./getDocumentName');
const getValidGraphQLTag = require('./getValidGraphQLTag');
const getValidRelayQLTag = require('./getValidRelayQLTag');
const invariant = require('./invariant');
import typeof BabelTypes from 'babel-types';
import type {Validator} from './RelayQLTransformer';
export type RelayPluginOptions = {
schema?: string,
compat?: boolean,
haste?: boolean,
// Classic options
inputArgumentName?: string,
snakeCase?: boolean,
substituteVariables?: boolean,
validator?: Validator<any>,
};
export type BabelState = {
file?: any,
opts?: RelayPluginOptions,
};
/**
* Using babel-plugin-relay with only the modern runtime?
*
* {
* plugins: [
* "relay"
* ]
* }
*
* Using babel-plugin-relay in compatability or classic mode?
*
* {
* plugins: [
* ["relay", {"compat": true, "schema": "path/to/schema.graphql"}]
* ]
* }
*
*/
module.exports = function BabelPluginRelay(context: {types: BabelTypes}): any {
const {types: t} = context;
if (!t) {
throw new Error(
'BabelPluginRelay: Expected plugin context to include "types", but got:' +
String(context),
);
}
return {
visitor: {
TaggedTemplateExpression(path, state) {
// Convert graphql`` literals
const ast = getValidGraphQLTag(path);
if (ast) {
compileGraphQLTag(t, path, state, ast);
return;
}
// Convert Relay.QL`` literals
const [quasi, tagName, propName] = getValidRelayQLTag(path);
if (quasi && tagName) {
const schema = state.opts && state.opts.schema;
invariant(
schema,
'babel-plugin-relay: Missing schema option. ' +
'Check your .babelrc file or wherever you configure your Babel ' +
'plugins to ensure the "relay" plugin has a "schema" option.\n' +
'https://facebook.github.io/relay/docs/babel-plugin-relay.html#additional-options',
);
const documentName = getDocumentName(path, state);
path.replaceWith(
compileRelayQLTag(
t,
path,
schema,
quasi,
documentName,
propName,
tagName,
true, // enableValidation
state,
),
);
}
},
},
};
};