gajus / babel-plugin-graphql-tag Goto Github PK
View Code? Open in Web Editor NEWCompiles GraphQL tagged template strings using graphql-tag.
License: Other
Compiles GraphQL tagged template strings using graphql-tag.
License: Other
I'm using both babel-plugin-graphql-tag
and apollo-link-logger
but found that it will compile into broken code. The transformer will remove the following require
statement inside apollo-link-logger
incorrectly.
var _client = require('@apollo/client');
var loggerLink = new _client.ApolloLink(function (operation, forward) {
...
});
This will cause:
ReferenceError: _client is not defined
Hi, I'm using this plugin in a relatively small project (UnlyEd/next-right-now#56), the issue we're facing is that we're not seeing any difference in the build size results after enabling it.
Btw, I'm aware of the fragments requirements usage.
More context:
Without the plugin:
Using the plugin:
Any feedback?
Thanks!
Hello @gajus
Thank you for working on this.
The lack of a changelog file and the lack of tagged releases makes it difficult to upgrade this package in dependents. Are you open to the idea of changelogs?
Cheers
I'm trying to integrate babel-plugin-graphql-tag
into my project, but the peerDependency version of ^0.10.1
conflicts with my installed version of 0.11.7
, and prevents me from upgrading to a 0.12.x
release.
One resolution to this would be to broaden the accepted peerDependency range, like graphql-tag
does. This would allow apps (like mine) that depend on babel-plugin-graphql-tag
to upgrade.
However, from a search through this repo it seems like graphql
is never explicitly imported, which makes me suspect that it is not needed as a peerDependency. Since this project only directly imports graphql-tag
, and graphql-tag
has its own peerDependency on graphql
, it should be sufficient to let graphql-tag
declare its own peerDependency on graphql
.
I'll post a PR to remove the peerDependency shortly. If you'd prefer to keep the peerDependency and simply broaden it, I'm happy to submit a PR for that instead.
Relates to #7
Hi there,
thanks for this very useful plugin!
I've recently migrated a project to @apollo/client
v3 and encountered an error with the way this plugin seems to remove the import statements.
Console error:
path/to/app/node_modules/@apollo/client/core/index.js 16:9
Module parse failed: Export 'gql' is not defined (16:9)
File was processed with these loaders:
* ../../node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| enableExperimentalFragmentVariables = gql.enableExperimentalFragmentVariables,
| disableExperimentalFragmentVariables = gql.disableExperimentalFragmentVariables;
> export { gql };
File related to the above error: (node_modules/@apollo/client/core/index.js
)
[...]
import gql from 'graphql-tag';
export var resetCaches = gql.resetCaches, disableFragmentWarnings = gql.disableFragmentWarnings, enableExperimentalFragmentVariables = gql.enableExperimentalFragmentVariables, disableExperimentalFragmentVariables = gql.disableExperimentalFragmentVariables;
export { gql };
As you can see, @apollo/client
is importing gql from graphql-tag
and assigning a few vars before exporting it. This plugin seems to remove the import statement, which leads to the above error.
I was able to resolve this by setting importSources: ["@apollo/client"]
via the configuration. However, this is a bad user experience for migrating projects because they would have to change all imports at once and I think, this plugin shouldn't touch any files located in node_modules
. I propose, we exclude the node_modules
directory.
What do you think? Do you have a better fix in mind?
Hey, I'm getting
Uncaught Error: Cannot use e "__Schema" from another module or realm.
Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.
I suppose its due to the babel-plugin using 0.10.5 while my app uses >1.0.0. Could we get rid of the dependency in the plugin?
Hi!
I've recently created https://github.com/leoasis/graphql-tag.macro which is kind of the same as this library but using babel-macros.
One thing that I added in my lib is support for concatenating definitions from interpolated values in the tagged string literal. This allows to interpolate fragments in particular. You can see the implementation here.
Would you be willing to accept a PR adding this feature to this plugin so people that prefer plain babel plugins can benefit from this?
I am currently using urql client to handle my graphQL needs and I am using this plugin to optimize the gql queries.
I have the following config on my babel.config.js file:
module.exports = {
presets: [
'@vue/app',
],
plugins: [
// reference: https://www.apollographql.com/docs/react/performance/babel/#using-babel-plugin-graphql-tag
['graphql-tag',
{
importSources: ['@urql/core'],
},
],
],
};
I dont have the graphql-tag dependency directly installed since urql has its own version.
How do you recommend I procceed?
In modern JS engines, using JSON.parse on huge objects can improve performance significantly. It would be nice to have an option to do this.
I'm trying to implement https://github.com/leoasis/graphql-persisted-document-loader in my React Application.
With your plugin everything works good, beautiful! But with graphql-persisted-document-loader
is a little bit a mess (in React).
I was wondering if you can add a simple "documentHash" or "documentID" or "queryHash" (maybe also using that package) for the hash of the query useful for persisted GraphQL queries.
Is this difficult?
Can you see the positive sides of this feature?
I don't see a 3.0.0, in the list of git tags.
I guess this is more "philosophical" but in the package.json if the end-user has to have it (peer-dep) and you have to have it to develop with (dev-dep) wouldn't it make sense to just promote graphql-tag
to a full dependency?
The readme doesn't make it clear if this Babel plugin is able to replace gql
when it is imported from places other than graphql-tag
; namely @apollo/client
.
I tried to load this plugin in the Babel REPL to find out, but it never loads successfully. In a Next.js repo, looking at the resulting bundle, it seems to not work?
No one could answer the question here. I'm surprised the community hasn't smoothed this over yet, since Apollo is advising everyone to import gql
from @apollo/client
for Apollo Client v3 which had a very long beta period:
The
@apollo/client
package includesgraphql-tag
as a dependency and re-exportsgql
. To simplify your dependencies, we recommend importinggql
from@apollo/client
and removing allgraphql-tag
dependencies.
โ https://www.apollographql.com/docs/react/migrating/apollo-client-3-migration/#graphql-tag
This seems like bad advice. They don't even follow their own advice in their "Compiling queries with Babel" docs:
This approach will allow you to use the
graphql-tag
library as usual
โ https://www.apollographql.com/docs/react/performance/babel/#using-babel-plugin-graphql-tag
Maybe Apollo didn't give much thought to performance when designing and documenting their new API?
Either way, if this plugin doesn't handle gql
imported from @apollo/client
it probably needs to moving forward.
It looks like the most recent semantic-release (for 5af4adb) failed to publish. Can you fix this and publish?
I'm doing something really basic. Just making a query with useQuery
from a .graphql
file. But if I modify the query, useQuery
still uses the old version of the query. I've confirmed that it is actually making the request, not returning cached results. Sometimes if I change my code to make a different query, and switch back, the changes are reflected. Very strange. But if I use a template string query directly, I don't have the issue, so I think the issue is in the babel build.
My webpack config is pretty standard:
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: 'graphql-tag/loader',
},
Is there some hidden setting for this behavior or something? Thanks for any advice you can provide.
When using transform to calculate the hash for the persisted query, the whole query including fragments has to be known. However, both source and ast parameters for transform only contain the query, not the fragments.
The gql
tag gracefully handles duplicate fragment definitions, which may be pulled in through a series of nested fragments.
Right now, this tool will not de-dupe the fragments, which results in GraphQL errors.
For example, the HomeQuery
below will fail because it contains duplicate definitions of ImageFragment
.
const ImageFragment = gql`
fragment ImageFragment on Image {
src
}
`;
const UserFragment = gql`
fragment UserFragment on User {
avatar {
...ImageFragment
}
}
${ImageFragment}
`;
const EpisodeFragment = gql`
fragment EpisodeFragment on Episode {
image {
...ImageFragment
}
}
${ImageFragment}
`;
const HomeQuery = gql`
query HomeQuery {
episodes {
...EpisodeFragment
}
users {
...UserFragment
}
}
${EpisodeFragment}
${UserFragment}
`;
I don't know a thing about writing Babel plugins, otherwise I'd dive in.
๐ @leoasis, looks like you wrote the initial fragment support. Perhaps this is an easy fix?
Hey, I wanted to submit a failing test case, but I just did a fresh checkout from master and ran npm i && npm test
and I get this failure:
โ babel-plugin-graphql-tag git:(master) โ npm test
> [email protected] test /workspace/scratch/babel-plugin-graphql-tag
> NODE_ENV=test mocha --compilers js:babel-register
babel-plugin-graphql-tag/graphql tag
1) converts inline gql tag to a compiled version
โ does not transpile template literals without a tag
โ does not transpile template literals without gql tag
2 passing (411ms)
1 failing
1) babel-plugin-graphql-tag/graphql tag converts inline gql tag to a compiled version:
/workspace/scratch/babel-plugin-graphql-tag/test/fixtures/graphql-tag/converts inline gql tag to a compiled version/actual.js !== /workspace/scratch/babel-plugin-graphql-tag/test/fixtures/graphql-tag/converts inline gql tag to a compiled version/expected.js
+ expected - actual
'start': 0,
'end': 15,
'source': {
'body': 'query foo {foo}',
- 'name': 'GraphQL request',
- 'locationOffset': {
- 'line': 1,
- 'column': 1
- }
+ 'name': 'GraphQL request'
}
}
};
at run (node_modules/babel-helper-transform-fixture-test-runner/lib/index.js:259:47)
at runTask (node_modules/babel-helper-transform-fixture-test-runner/lib/index.js:63:13)
at Context.<anonymous> (node_modules/babel-helper-transform-fixture-test-runner/lib/index.js:93:15)
Any idea what might cause that failure? Looks like the transform does the correct thing but the 'snapshot' test doesn't account for a (new?) locationOffset
property?
First: I have no problem using it through webpack.config.js
.
But I can't get compiled results when i use chainWebpack to config webpack,
So I'm not sure my configuration code is correct.
config.module
.rule('graphql')
.test(/\.graphql$/)
.include
.add(path.resolve(__dirname, 'src'))
.end()
.exclude
add(/node_modules/)
.end()
.use('graphql-tag/loader')
.loader('graphql-tag/loader')
.end();
# demo.graphql
query Demo {
uv
}
I got a Base64 string when I imported it
import DemoGQL from './demo.graphql'
I observed a increase in bundle size using this plugin.
That kindof makes sense as it in a way inlines the result of qql in the bundle.
I just wanted to check if my understanding is correct?
Just wondering if this is on your radar.
From the readme:
import gql from 'graphql-tag';
const foo = gql`query {bar}`;
This throws:
error Error: GraphQL query must have name.
The graphql-tag
library itself doesn't require a query to be named. What are your thoughts on skipping this validation, or making it an option?
Apollo client changed the way graphql-tag
is exported, it causes runtime error after babel transform:
My versions:
"@apollo/client": "3.3.19",
"@babel/core": "7.14.3",
"babel-plugin-graphql-tag": "3.3.0",
"graphql-tag": "2.12.3",
Babel config:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
['graphql-tag', { importSources: ['graphql-tag'] }],
],
};
It works fine when I reverted @apollo/client
Moving from v2 to v3 generally implies a breaking change, though there is no CHANGELOG/HISTORY file or updated Releases. Could you please let us know what breaking changes (if any) are present when going from v2 -> v3? Thank you!
I just installed this plugin, this is my configuration
rollup.config.js
const babel = require('rollup-plugin-babel');
module.exports = {
plugins: [
babel({
babelrc: false,
plugins: [
'babel-plugin-graphql-tag',
],
}),
],
};
But when I run rollup I get
[!] (babel plugin) Error: Cannot find module '@babel/helper-plugin-utils'
Error: Cannot find module '@babel/helper-plugin-utils'
at Function.Module._resolveFilename (module.js:548:15)
at Function.Module._load (module.js:475:25)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (my-code/node_modules/babel-plugin-graphql-tag/dist/index.js:10:26)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
Works fine if I remove your plugin or if I install @babel/helper-plugin-utils
manually, however I don't think I should install that package myself, it should be in the dependencies of this plugin.
Is there any official way to bypass this plugin for places where we need to dynamically create the queries?
For example I have some code where I let the users pick the fields he wants to see in a table and manually build the query based on that. I can't create a query at compile time because there are too many fields to do all the combinations of fields selected
Not sure if this is possible or needed by the babel plugin, but it would be great to remove the "source" part of the "loc" object. It seems to just be bloat since the query is preprocessed into other objects.
Hi, this plugin as it, is breaking a rule in yarn v2.
As described in #32 @babel/helper-plugin-utils should be a dependency
This means that when trying to use yarn v2
Error: A package is trying to access another package without the second one being listed as a dependency of the first one
Required by: babel-plugin-graphql-tag@virtual:c18b4f024c7ecbdb98a3630eac603cf0e6d94c4582ad9f9e2250387151455e632a6181511c25f5ec799e5a2994b4e7df41046a09544d3b70e2089ba3e573db0d#npm:2.5.0 (via /C:/Users/pablo/TrAC-v2/.yarn/$$virtual/babel-plugin-graphql-tag-virtual-d3908e9d0d/0/cache/babel-plugin-graphql-tag-npm-2.5.0-72c4bced6d-1.zip/node_modules/babel-plugin-graphql-tag/dist/)
I will send a PR hoping to fix this issue.
babel-plugin-graphql-tag
: ^1.6.0react-apollo
: ^2.1.5@babel/*
: ^7.0.0-beta.54We added babel-plugin-graphql-tag
to our workflow yesterday, but with the above configuration the apollo react components think the query has changed on each render, causing total API thrashing.
We just reverted for now, but it's likely that the query needs to be hoisted out to a permanent scope. This is (obviously) something that can be done manually, but ideally would be handled by the plugin, since it's not obvious to a developer that the string template is in fact compiled into an object with a distinct identity.
EDIT: to clarify, this will thrash:
SomeComponent = () => (
<Query query={gql`
query SomeQuery($id: ID!) {
node(id: $id) {
}
`} >...</Query>
);
while this works as intended
const query = gql`
query SomeQuery($id: ID!) {
node(id: $id) {
}
`;
SomeComponent = () => (
<Query query={query} >...</Query>
);
Hi,
Just wondering if this lib will work with Babel7? if yes, that could be handy to add to readme ;)
I am probably missing something, but after adding the plugin to my .bablrc I can't tell if my .graphql files are being compiled @ build time (my bundle size hasn't reduced, either). I looked through the code and don't see the debug statements going off either when I run build with webpack.
package.json
"dependencies": {
"@babel/polyfill": "7.0.0-rc.1",
"apollo-cache-inmemory": "^1.2.7",
"apollo-client": "^2.3.8",
"apollo-link": "^1.2.2",
"apollo-link-context": "^1.0.8",
"apollo-link-error": "^1.1.0",
"apollo-link-http": "^1.5.4",
"apollo-link-ws": "^1.0.8",
"apollo-utilities": "^1.0.18",
"graphql": "^0.13.2",
"graphql-tag": "^2.9.2",
"grid-styled": "^5.0.2",
"jwt-decode": "^2.2.0",
"mobx": "^5.0.3",
"mobx-react": "^5.2.5",
"mobx-state-tree": "^3.2.1",
"prop-types": "^15.6.2",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"react-router-dom": "^4.3.1",
"styled-components": "^3.4.2"
},
"devDependencies": {
"@babel/core": "^7.0.0-rc.1",
"@babel/plugin-proposal-class-properties": "^7.0.0-rc.1",
"@babel/plugin-proposal-decorators": "^7.0.0-rc.1",
"@babel/plugin-proposal-export-namespace-from": "^7.0.0-rc.1",
"@babel/plugin-proposal-function-sent": "^7.0.0-rc.1",
"@babel/plugin-proposal-json-strings": "^7.0.0-rc.1",
"@babel/plugin-proposal-numeric-separator": "^7.0.0-rc.1",
"@babel/plugin-proposal-object-rest-spread": "^7.0.0-rc.1",
"@babel/plugin-proposal-throw-expressions": "^7.0.0-rc.1",
"@babel/plugin-syntax-dynamic-import": "^7.0.0-rc.1",
"@babel/plugin-syntax-import-meta": "^7.0.0-rc.1",
"@babel/preset-env": "^7.0.0-rc.1",
"@babel/preset-react": "^7.0.0-rc.1",
"@babel/register": "^7.0.0-rc.1",
"babel-core": "^7.0.0-bridge.0",
"babel-eslint": "8",
"babel-jest": "^23.4.2",
"babel-loader": "^8.0.0-beta.4",
"babel-plugin-graphql-tag": "^1.6.0",
"babel-plugin-transform-inline-environment-variables": "^0.4.3",
"clean-webpack-plugin": "^0.1.19",
"compression-webpack-plugin": "^1.1.11",
"eslint": "^5.3.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-import-resolver-webpack": "^0.10.1",
"eslint-loader": "^2.1.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-jsx-a11y": "^6.1.1",
"eslint-plugin-react": "^7.11.1",
"file-loader": "^1.1.11",
"html-webpack-plugin": "3.2.0",
"image-webpack-loader": "^4.3.1",
"jest": "^23.5.0",
"mobx-devtools-mst": "^0.9.18",
"raw-loader": "^0.5.1",
"react-testing-library": "^5.0.0",
"svg-url-loader": "^2.3.2",
"uglifyjs-webpack-plugin": "^1.3.0",
"unfetch": "^3.1.1",
"url-loader": "^1.1.0",
"webpack": "^4.16.5",
"webpack-chunk-hash": "^0.6.0",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5",
"webpack-serve": "^2.0.2",
"webpack-stylish": "^0.1.8"
},
.babelrc
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"browsers": [">0.25%", "not ie 11", "not op_mini all"]
}
}
],
"@babel/preset-react"
],
"plugins": [
"graphql-tag",
"transform-inline-environment-variables",
"@babel/plugin-proposal-object-rest-spread",
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
],
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-syntax-import-meta",
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-json-strings",
"@babel/plugin-proposal-function-sent",
"@babel/plugin-proposal-export-namespace-from",
"@babel/plugin-proposal-numeric-separator",
"@babel/plugin-proposal-throw-expressions"
]
}
Example query
import gql from 'graphql-tag'
const UserById = gql`
query queryId($id: ID!) {
findUserById(id: $id) {
id
email
}
}
`
export default UserById
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.