Search code examples
webpackrequire

How to require JavaScript using webpack from a dynamic directory


I have some old-school plain old ES5 JavaScript that I need to pull into my application that is using webpack as a bundler. The problem is that the location of these files is in a folder whose path is dynamic. It seems that webpack does not work well with expressions in require and require.context doesn't allow them at all.

For known path directories to require all the files in a directory and its subdirectories, this approach works fine:

let domainRequires = require.context('./app/domain', true, /\.js$/); domainRequires.keys().forEach(domainRequires);

Since I can't use an expression in require.context, I tried just using plain require and it is NOT working:

require('../../path/to/code/my-library-' + versionNumber + '/domain/clazz.js');

using the full relative path.

I've also tried to use require.context but enhancing the regex portion to get it working and haven't had luck:

require.context('../../path/to/code', true, /^my-library-.*\/domain\/.*\.js$/);

Any thoughts, suggestions, or solutions would be welcome. If I need to use something 3rd party with webpack, that's fine too.


Solution

  • I ended up figuring this out. By using the webpack resolve.alias, I could add:

    resolve: {
      alias: {
        common: path.resolve(__dirname, '../../path/to/code/my-library-' + versionNumber + '/domain')
      }
    }
    

    in webpack.config.

    Then in my code, I can require all of the files under /domainvia:

    var commonRequires = require.context('common', true, /\.js$/);
    commonRequires.keys().forEach(commonRequires);
    

    Likewise, I could get a single file via:

    require('common/clazz.js'); // ../../path/to/code/my-library-1.0.0/domain/clazz.js
    

    FWIW, to get versionNumber I used node's fs module to read from a json file, used JSON.parse(file) and then retrieved the version at the top of webpack.config