title: How to Use `import.meta` When Testing With Jest
body: <p>I am writing Node.js code (in TypeScript) using ESModules and I need access to <code>__dirname</code>. In order to access the ESM equivalent of <code>__dirname</code> in CommonJS, I call <code>dirname(fileURLToPath(import.meta.url))</code>. I am also writing tests in Jest with TypeScript. Using <a href="https://jestjs.io/docs/en/getting-started" rel="noreferrer">this</a> guide, I set up Babel. When I run the <code>jest</code> command, I get</p>
  <pre><code>const DIRNAME = (0, _path.dirname)((0, _url.fileURLToPath)(import.meta.url));
                                                                        ^^^^
  SyntaxError: Cannot use 'import.meta' outside a module
  </code></pre>
  <p>Here are the files I wrote</p>
  <p><em><code>someCode.ts</code>:</em></p>
  <pre><code>import { dirname } from &quot;path&quot;;
  import { fileURLToPath } from &quot;url&quot;;
  
  const DIRNAME = dirname(fileURLToPath(import.meta.url));
  
  export const x = 5;
  </code></pre>
  <p><em><code>someCode.test.ts</code>:</em></p>
  <pre><code>import { x } from &quot;./someCode&quot;;
  
  it(&quot;Returns 5 as the result&quot;, () =&gt; {
      expect(x).toEqual(5);
  });
  </code></pre>
  <p><em><code>.babelrc.json</code>:</em></p>
  <pre><code>{
      &quot;presets&quot;: [
          [&quot;@babel/preset-env&quot;, { &quot;targets&quot;: { &quot;node&quot;: &quot;current&quot; } }],
          &quot;@babel/preset-typescript&quot;
      ]
  }
  </code></pre>
  <p><em><code>tsconfig.json:</code></em></p>
  <pre><code>{
      &quot;compilerOptions&quot;: {
          &quot;target&quot;: &quot;ES2020&quot;,
          &quot;module&quot;: &quot;ESNext&quot;,
          &quot;moduleResolution&quot;: &quot;node&quot;
      },
      &quot;include&quot;: [&quot;./src/**/*.ts&quot;, &quot;./src/**/*.js&quot;]
  }
  </code></pre>
  <p><em><code>package.json</code>:</em></p>
  <pre><code>{
      &quot;name&quot;: &quot;test&quot;,
      &quot;version&quot;: &quot;1.0.0&quot;,
      &quot;description&quot;: &quot;&quot;,
      &quot;main&quot;: &quot;index.js&quot;,
      &quot;type&quot;: &quot;module&quot;,
      &quot;scripts&quot;: {
          &quot;test&quot;: &quot;jest&quot;
      },
      &quot;keywords&quot;: [],
      &quot;author&quot;: &quot;&quot;,
      &quot;license&quot;: &quot;ISC&quot;,
      &quot;devDependencies&quot;: {
          &quot;@babel/core&quot;: &quot;^7.12.7&quot;,
          &quot;@babel/preset-env&quot;: &quot;^7.12.7&quot;,
          &quot;@babel/preset-typescript&quot;: &quot;^7.12.7&quot;,
          &quot;jest&quot;: &quot;^26.6.3&quot;,
          &quot;typescript&quot;: &quot;^4.1.2&quot;
      }
  }
  </code></pre>
  <p><strong>Environment:</strong></p>
  <ul>
  <li>Node: 14.1.0</li>
  <li><em>See <code>package.json</code> for module versions</em></li>
  </ul>