简体   繁体   中英

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?

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?

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.

Edit .babelrc to point to the artifactDirectory

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM