javascriptgraphql-js

What is this new syntax gql`string`?


Consider:

const GET_DOGS = gql`
  {
    dogs {
      id
      breed
    }
  }
`;

I found this new syntax from here.

What is the explanation for this syntax? Where can I find detail about it?


Solution

  • It's called a tagged template. Template literals (`...`) can be prefixed with a function name. Upon evaluation, this function will be called and the static and dynamic parts of the template literal are passed to the function. Example:

    function foo(staticParts, dynamicParts) {
      console.log(staticParts, dynamicParts);
    }
    
    foo`this is a ${42} test`

    Tagged templates can be used to create domain specific languages, such as in this example.

    There are many questions around tagged templates you can learn more from.