title: How can I load environment variables with ts-node?
body: <p>I've tried a few implementations which none have been successful.</p>
  <h2>First Attempt</h2>
  <p>Using <code>eval</code> in package.json script <code>&quot;fetch:data&quot;: &quot;eval $(cat .env) ts-node -O '{\&quot;module\&quot;:\&quot;commonjs\&quot;}' ./bin/build-api-data.ts&quot;</code>.</p>
  <p>This results in a JSON parsing error because eval is removing my quotes for some reason.</p>
  <pre><code>undefined:1
  {module:commonjs}
   ^
  
  SyntaxError: Unexpected token m in JSON at position 1
  </code></pre>
  <h2>Second Attempt</h2>
  <p>Using dotenv, the problem I encountered here was it was a race condition resulting in errors like this:</p>
  <pre><code>$ CANDID_ENV=local ts-node -O '{&quot;module&quot;:&quot;commonjs&quot;}' ./bin/build-api-data.ts
  
  /Users/lassiter.gregg/code/candidco-web/node_modules/contentful/dist/webpack:/contentful/contentful.js:49
      throw new TypeError('Expected parameter accessToken')
            ^
  TypeError: Expected parameter accessToken
  </code></pre>
  <p>Code Sample</p>
  <pre class="lang-js prettyprint-override"><code>import fs from 'fs';
  import path from 'path';
  import fetchApiData from '../lib/apiData';
  import dotEnv from 'dotenv-safe';
  
  const { CANDID_ENV } = process.env;
  
  const isLocalBuild = CANDID_ENV === 'local';
  
  console.log(dotEnv);
  
  const API_DATA_FILENAME = 'api_data.json';
  
  const ensureDirectoryExistence = filePath =&gt; {
    var dirname = path.dirname(filePath);
    if (fs.existsSync(dirname)) {
      return true;
    }
    ensureDirectoryExistence(dirname);
    fs.mkdirSync(dirname);
  };
  
  const writeData = (filename, data) =&gt; {
    const filePath = path.join(__dirname, '..', '.data', filename);
    ensureDirectoryExistence(filePath);
    fs.writeFileSync(filePath, JSON.stringify(data));
  
    console.log('API data stored', filePath);
  };
  
  const fetchAndStoreApiData = async () =&gt; {
    console.log('Fetching all API data');
    await dotEnv.config({
      path: isLocalBuild ? './.env' : `./.env.${CANDID_ENV}`,
    });
  
    const newData = await fetchApiData();
    writeData(API_DATA_FILENAME, newData);
  };
  
  const init = async () =&gt; {
    fetchAndStoreApiData();
  };
  
  if (require.main === module) {
    init();
  }
  
  </code></pre>
  <p>In the case above, I've tried doing <code>dotenv.config</code> at the top of the file, in the init, in the function as you see. It always throws the same error about contentful not getting the env variable it needs. That said, if I log <code>process.env</code> and comment out the code relevant to <code>fetchApiData</code> then I see all my environment variables. That's why I think it's a race-time condition but haven't been able to find anything similar to my own issue.</p>
  <p>Additionally, what makes this even more thorny is that this is a custom script that has to work in a node and esnext environment. So, I've had my fair share of thorny import/export issues using syntax I don't really prefer but haven't found away around it (e.g. <code>export = someFunction</code>).</p>