title: Use ContextReplacementPlugin for dynamically setting the resource path in require.context
body: <p>I want to import the posts from two folders, 'NL' and 'JP'. And use a dynamically set folder for that.</p>
  <p>When I write the folder include statically it works:</p>
  <pre><code>import { useState, useEffect } from 'react';
  import importAllMarkdown from '../importAllMarkdown';
  import { Data, PostBlog } from '../shared.types';
  
  type countryCode = 'NL' | 'JP';
  
  function usePosts(countryCode: countryCode): Data&lt;PostBlog&gt;[] | null {
    const [posts, setPosts] = useState&lt;Data&lt;PostBlog&gt;[] | null&gt;(null);
  
    useEffect(() =&gt; {
  
      // this codeblock for each country :(
      if (countryCode === 'NL') {
        const importedPosts: Data&lt;PostBlog&gt;[] = 
          importAllMarkdown(require.context('../posts/NL', true, /\.md$/));
  
        setPosts(importedPosts);
      }
  
      if (countryCode === 'JP') {
        const importedPosts: Data&lt;PostBlog&gt;[] =
          importAllMarkdown(require.context('../posts/JP', true, /\.md$/));
  
        setPosts(importedPosts);
      }
    }, [countryCode, setPosts]);
  
    return posts;
  }
  
  export default usePosts;
  
  </code></pre>
  <p>As you can see in this example, for each country you have to add an entire block to import the files in that folder.</p>
  <p>When you'd dynamically set the folder:</p>
  <pre><code>const folderPath = `../posts/${countryCode}`;
  const importedPosts: Data&lt;PostBlog&gt;[] = 
    importAllMarkdown(require.context(folderPath, true, /\.md$/));
  </code></pre>
  <p>..it gives the error: <code>TypeError: __webpack_require__(...).context is not a function</code>.</p>
  <p>Now from this <a href="https://github.com/webpack/webpack/issues/4772" rel="nofollow noreferrer">Github thread</a> it seems that <a href="http://ContextReplacementPlugin" rel="nofollow noreferrer">ContextReplacementPlugin</a> can be used for dynamically setting the folder.</p>
  <blockquote>
  <p><em>&quot;An alternative is to use require(variable) and use the ContextReplacementPlugin to provide the &quot;staticness&quot; via config. In this case you need to specify all possible values of variable in the arguments of the plugin (or crawl a directory).&quot;</em></p>
  </blockquote>
  <p>So what I'm trying:</p>
  <p><strong>./next.config.js</strong></p>
  <pre><code>module.exports = {
    webpack(config, { webpack }) {
      config.plugins.push(new webpack.ContextReplacementPlugin(
        /^\..\/posts/,
        /NL|JP/,
      ));
      return config;
    },
  };
  </code></pre>
  <p>This still produces the error: <code>TypeError: __webpack_require__(...).context is not a function</code>.</p>
  <p>What is going wrong?</p>