Stan Luo
Stan Luo

Reputation: 3889

TypeScript with Relay: Can't resolve generated module

In my MessageItem.tsx component I have the following code:

const data = useFragment(
    graphql`
      fragment MessageItem_message on Message {
        date
        body
      }
    `,
    message as any
  );

After running relay-compiler --src ./src --schema ../../schema.graphql --language typescript --artifactDirectory ./src/__generated__, a module named MessageItem_message.graphql.ts gets generated.

But when I run the app it gives me an error:

Failed to compile.

./src/components/MessageItem.tsx

Module not found: Can't resolve './__generated__/MessageItem_message.graphql'

The reason is only components at the src root can refer to the right path (./__generated__), whereas components in a folder actually need to refer to the path (../__generated__) but it's not doing so.

How can I configure the path?

Upvotes: 4

Views: 5211

Answers (3)

BryceLarkin
BryceLarkin

Reputation: 504

Edit .babelrc to point to the artifactDirectory

// .babelrc
{
  "plugins": [
    [
      "relay",
      {
        "artifactDirectory": "./src/ui/graphql/types"
      }
    ]
  ]
}

Upvotes: 1

Christian Ivicevic
Christian Ivicevic

Reputation: 10905

Just moments ago I ran into the same issue. The reason is that the relay-compiler is using the artifactDirectory setting to decide where to put the generated files, but the babel-plugin-relay exposing the graphql tag needs to get the very same argument otherwise it just attempts to include a colocated relative file.

I fixed it in my case by configuring the plugin with a babel-plugin-macros.config.js file as follows (where the artifactDirectory is the same as the one supplied to the relay-compiler):

module.exports = {
    relay: {
        artifactDirectory: "./src/ui/graphql/types",
    },
};

This solution assumes you are using the macro via babel-plugin-macros, otherwise you might need to supply that argument via the .babelrc file but I have no experience with that unfortunately.

Upvotes: 0

Ashley Aitken
Ashley Aitken

Reputation: 2529

Remove "--artifactDirectory ./src/__generated__" from the relay-compiler options.

By default it seems the Relay compiler puts a "__generated__" directory in the directory with any source code containing GraphQL.

As a result any "./__generated__" references anywhere and at any level in the source code hierarchy now work as they should.

Thanks to @ThibaultBoursier for the pointer.

PS I wonder if the --artifcactDirectory option is just meant to be used to change the name of the artifact directory, rather than its location?

Upvotes: 0

Related Questions