Skip to content

Commit

Permalink
[webpack-integration] Include SANITY_STUDIO env vars from .env files
Browse files Browse the repository at this point in the history
  • Loading branch information
rexxars committed Dec 6, 2019
1 parent 4cd838d commit 0ac8711
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
1 change: 1 addition & 0 deletions packages/@sanity/webpack-integration/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"dependencies": {
"@sanity/resolver": "0.146.0",
"@sanity/webpack-loader": "0.146.0",
"dotenv": "^8.2.0",
"fs.realpath": "^1.0.0",
"p-async-cache": "^1.0.2",
"postcss-cssnext": "^3.0.2",
Expand Down
30 changes: 27 additions & 3 deletions packages/@sanity/webpack-integration/src/v3/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
/* eslint-disable no-process-env */
const fs = require('fs')
const path = require('path')
const dotenv = require('dotenv')
const postcssImport = require('postcss-import')
const postcssCssnext = require('postcss-cssnext')
const PartResolverPlugin = require('@sanity/webpack-loader')
Expand All @@ -10,8 +13,29 @@ function getPartResolverPlugin(options) {
return new PartResolverPlugin(options)
}

function getEnvVars(isProd) {
return Object.keys(process.env).reduce(
function tryReadDotEnv(studioRootPath) {
const configEnv = process.env.NODE_ENV || 'development'
const envFile = path.join(studioRootPath, `.env.${configEnv}`)

let parsed = {}
try {
// eslint-disable-next-line no-sync
parsed = dotenv.parse(fs.readFileSync(envFile, {encoding: 'utf8'}))
} catch (err) {
if (err.code !== 'ENOENT') {
// eslint-disable-next-line no-console
console.error(`There was a problem processing the .env file (${envFile})`, err)
}
}

return parsed
}

function getEnvVars({isProd, basePath}) {
const dotEnvVars = tryReadDotEnv(basePath)
const allEnvVars = {...dotEnvVars, ...process.env}

return Object.keys(allEnvVars).reduce(
(acc, key) => {
if (key.startsWith('SANITY_STUDIO_')) {
acc[`process.env.${key}`] = JSON.stringify(process.env[key])
Expand All @@ -32,7 +56,7 @@ function getEnvPlugin(options) {
const webpack = options.webpack || require('webpack')
return new webpack.DefinePlugin({
__DEV__: !isProd && bundleEnv === 'development',
...getEnvVars(isProd)
...getEnvVars({isProd, basePath: options.basePath})
})
}

Expand Down

0 comments on commit 0ac8711

Please sign in to comment.