How to use a custom Transformer for Gridsome?

95 views Asked by At

I have a proprietary file format that I'd like to use in my Gridsome website, with each of these files generating a new page. As I understand it, that's exactly what you can use a Transformer for. However, no plugin exists for a Transformer of the file type I'm using. Is it possible to create your own Transformer for private use?

I've first tried simply adding the source-filesystem plugin, but that gives me the error: No transformer for 'application/myformat' is installed.

plugins: [
      {
          use: "@gridsome/source-filesystem",
          options: {
              path: "files/**/*.myformat",
              typeName: "File"
          }
      },
  ]

I've found no documentation to do something similar, which surprised me, since it seems like it must be a fairly common use-case. Anyone know a way to do this?

1

There are 1 answers

0
user1902853 On BEST ANSWER

Alright, I was able to figure this out, but it still seems like there must be a simpler way.

In a separate project directory, I ran npm init to create the bare minimum package.json (my Transformer had no other dependencies, you'll have to include them here if yours does).

I then added my Transformer class as follows in the "main" class I specified in package.json:

class Transformer {
    static mimeTypes () {
        return ['application/myformat']
    }

    parse (source) {
      let parsed = // whatever parsing is necessary
      return {
        parsed
      }
    }

    extendNodeType ({ graphql }) {
      return {
        // custom GraphQL fields for transformed node
      }
    }
}

module.exports = Transformer

Next, from the new directory, run npm link, then from your main project directory (that will be using the Transformer), run npm link your-transformer-project-name.

Finally, you should add the new plugin project to your main project's package.json in the devDependencies section:

...
"devDependencies": {
  "gridsome-transformer-myformat": "^1.0.0"
}