Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

vue.js - How to use a custom Transformer for Gridsome?

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?

question from:https://stackoverflow.com/questions/66054440/how-to-use-a-custom-transformer-for-gridsome

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...