Gatsby: Recommended way to share code between gatsby-node.js and components?

Created on 9 Oct 2019  ·  1Comment  ·  Source: gatsbyjs/gatsby

Since it's node, gatsby-node.js uses commonjs, components use ES6 modules.

Say I want to share a function that calculates the slug of a created page:

/* export ? */ function getSlug(post) {
   return `/posts/${post.data}${post.title.toLowerCase()}`
}

/* module.exports = { getSlug }; ? */

Now I want to import this function both in

  • in gatsby-node.js to use it in the createPage API
  • in Posts.js to link to the individual post paths.

How would you recommend sharing code & dealing with the different module systems in this case?

question or discussion

Most helpful comment

From my experience, you can just import node modules in your browser code like normal, unless you are using Node APIs. Are you facing any problem?

// shared.js
function getSlug(post) {
   return `/posts/${post.data}${post.title.toLowerCase()}`
}

module.exports = { getSlug }
// Posts.js
import { getSlug } from './path/to/shared.js'

>All comments

From my experience, you can just import node modules in your browser code like normal, unless you are using Node APIs. Are you facing any problem?

// shared.js
function getSlug(post) {
   return `/posts/${post.data}${post.title.toLowerCase()}`
}

module.exports = { getSlug }
// Posts.js
import { getSlug } from './path/to/shared.js'
Was this page helpful?
0 / 5 - 0 ratings

Related issues

kalinchernev picture kalinchernev  ·  3Comments

3CordGuy picture 3CordGuy  ·  3Comments

theduke picture theduke  ·  3Comments

andykais picture andykais  ·  3Comments

magicly picture magicly  ·  3Comments