diff --git a/bin/setup.js b/bin/setup.js index 370ba90..dbdaf46 100644 --- a/bin/setup.js +++ b/bin/setup.js @@ -35,7 +35,7 @@ const questions = [ { name: 'spaceId', message: 'Your Space ID', - when: !argv.spaceId, + when: !argv.spaceId && !process.env.CONTENTFUL_SPACE_ID, validate: input => /^[a-z0-9]{12}$/.test(input) || 'Space ID must be 12 lowercase characters', @@ -47,7 +47,7 @@ const questions = [ }, { name: 'deliveryToken', - when: !argv.accessToken, + when: !argv.accessToken && !process.env.CONTENTFUL_DELIVERY_TOKEN, message: 'Your Content Delivery API access token', }, ] @@ -55,10 +55,14 @@ const questions = [ inquirer .prompt(questions) .then(({ spaceId, managementToken, deliveryToken }) => { + const { CONTENTFUL_SPACE_ID, CONTENTFUL_DELIVERY_TOKEN } = process.env - spaceId = spaceId || argv.spaceId - managementToken = managementToken || argv.managementToken - deliveryToken = deliveryToken || argv.deliveryToken + // env vars are given precedence followed by args provided to the setup + // followed by input given to prompts displayed by the setup script + spaceId = CONTENTFUL_SPACE_ID || argv.spaceId || spaceId + managementToken = argv.managementToken || managementToken + deliveryToken = + CONTENTFUL_DELIVERY_TOKEN || argv.deliveryToken || deliveryToken console.log('Writing config file...') const configFilePath = path.resolve(__dirname, '..', '.contentful.json') diff --git a/gatsby-config.js b/gatsby-config.js index 1c3559b..6f41f16 100644 --- a/gatsby-config.js +++ b/gatsby-config.js @@ -1,4 +1,21 @@ -const contentfulConfig = require('./.contentful') +let contentfulConfig + +try { + contentfulConfig = require('./.contentful') +} catch (_) { + contentfulConfig = { + spaceId: process.env.CONTENTFUL_SPACE_ID, + accessToken: process.env.CONTENTFUL_DELIVERY_TOKEN, + } +} finally { + const { spaceId, accessToken } = contentfulConfig + + if (!spaceId || !accessToken) { + throw new Error( + 'Contentful spaceId and the delivery token need to be provided.' + ) + } +} module.exports = { pathPrefix: '/gatsby-contentful-starter', @@ -7,7 +24,7 @@ module.exports = { 'gatsby-plugin-react-helmet', { resolve: 'gatsby-source-contentful', - options: contentfulConfig + options: contentfulConfig, }, ], }