Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recommended way to share code between gatsby-node.js and components? #18379

Closed
Kadrian opened this issue Oct 9, 2019 · 1 comment
Closed
Labels
type: question or discussion Issue discussing or asking a question about Gatsby

Comments

@Kadrian
Copy link

Kadrian commented Oct 9, 2019

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?

@gatsbot gatsbot bot added the type: question or discussion Issue discussing or asking a question about Gatsby label Oct 9, 2019
@universse
Copy link
Contributor

universse commented Oct 10, 2019

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'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: question or discussion Issue discussing or asking a question about Gatsby
Projects
None yet
Development

No branches or pull requests

2 participants