Gatsby: [gatsby-ssr] __dirname always returns /

Created on 15 Apr 2019  路  2Comments  路  Source: gatsbyjs/gatsby

Description

__dirname in the gatsby-ssr.js file always return / rather than its actual path.

Steps to reproduce

In a starter (i.e. npx gatsby new test), paste something like the following into gatsby-ssr.js:

console.log("dirname", __dirname)

exports.onPreRenderHTML = function onPreRenderHTML() {
  console.log("dirname", __dirname)
}

Expected result

It should return/log the actual path of the gatsby-ssr.js file.

Actual result

It always returns /.

(Note that in other files like gatsby-node.js, it's returning the right path.)

Environment

Run gatsby info --clipboard in your project directory and paste the output here.


  System:
    OS: macOS 10.14
    CPU: (8) x64 Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz
    Shell: 5.3 - /bin/zsh
  Binaries:
    Node: 11.12.0 - /usr/local/bin/node
    npm: 6.7.0 - /usr/local/bin/npm
  Languages:
    Python: 2.7.10 - /usr/bin/python
  Browsers:
    Chrome: 73.0.3683.103
    Firefox: 63.0.3
    Safari: 12.0
  npmPackages:
    gatsby: ^2.2.13 => 2.2.13 
    gatsby-plugin-sass: ^2.0.11 => 2.0.11 
question or discussion

Most helpful comment

It's not really a bug, the code is ran inside webpack which also changes some variables that are relative to node.

to fix this you can do a workaround like this:

// in gatsby-node.js
process.env.GATSBY_SSR_DIRNAME = __dirname
// in gatsby-ssr.js
exports.onPreRenderHTML = function onPreRenderHTML(args) {
  console.log("dirname", process.env.GATSBY_SSR_DIRNAME)
}

All 2 comments

another not really related thing I should mention is that: also only in gatsby-ssr.js, I couldn't do something like this, but only exporting per function:

console.log("dirname", __dirname)

function onPreRenderHTML() {
  console.log("dirname", __dirname)
}

module.exports = { onPreRenderHTML }

It's not really a bug, the code is ran inside webpack which also changes some variables that are relative to node.

to fix this you can do a workaround like this:

// in gatsby-node.js
process.env.GATSBY_SSR_DIRNAME = __dirname
// in gatsby-ssr.js
exports.onPreRenderHTML = function onPreRenderHTML(args) {
  console.log("dirname", process.env.GATSBY_SSR_DIRNAME)
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

jimfilippou picture jimfilippou  路  3Comments

Oppenheimer1 picture Oppenheimer1  路  3Comments

signalwerk picture signalwerk  路  3Comments

totsteps picture totsteps  路  3Comments

dustinhorton picture dustinhorton  路  3Comments