I want to define a global constant in a gatsby-plugin and use its content in a page. But it does not work. I added the constant with the function "onCreateWebpackConfig". Why does this not have effects inside the react-part of gatsby? Is there a solution to get webpack-plugins (like weback-define or webpack-provide) work in a react-component?
gatsby-node.js:
exports.onCreateWebpackConfig = ({
plugins,
actions,
}) => {
actions.setWebpackConfig({
plugins: [
plugins.define({
__BLA__: JSON.stringify("Blaa"),
}),
],
})
}
Hey @oschade
Env variables which are prefixed with GATSBY_ will become available in any client side JavaScript. Your code above isn't working because it is being overwritten by https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby/src/utils/webpack.config.js
The reason we only allow variables that are prefixed by GATSBY_ (in the client side) is to ensure env variables aren't accidentally _leaked_ to client side code (which is accessible to anyone viewing source)
Read more about this here
Your code above isn't working because it is being overwritten by https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby/src/utils/webpack.config.js
But this file sets a constant named "__PATH_PREFIX__" with the define-plugin, which I can't access in my index-page either. Where is the webpack-config for the react-part? And will you be able to customize it in future realeases of gatsby?
@oschade Just tried to access __PATH_PREFIX__ in React code and it seems to work fine for me. Are you trying process.env.__PATH_PREFIX__ or __PATH_PREFIX__. It needs to be the latter.
The file you linked to _is_ the webpack config for the React app. Customising it is possible currently in the same way that you included in your issue.
More details at https://www.gatsbyjs.org/docs/add-custom-webpack-config/
Wait, I think I misunderstood previously
I can access __BLA__ in React code
// eslint-disable-next-line
console.log(__PATH_PREFIX__, __BLA__)
Maybe you were trying process.env.__BLA__?
aaah, I missed this line:
// eslint-disable-next-line
Thank you very much!
In case anyone else runs into this, I was logging "process.env" into the browser.. It shows up as an empty object. But apparently the variable property is hidden somehow?
So console.log(process.env) was just this: {}
But if I logged console.log(process.env.GATSBY_LAMBDA_ENDPOINT) I actually had data. 馃う