Search code examples
javascriptnode.jsrequirejsnode-modulescommonjs

Require Dynamically in NodeJS


I am working on a CLI package inside a monorepo that has a command called buildX: Goes through several directories, try to require a module that exist in some files withing those directories.

So basically I will try to do something like:

buildX --source ./somewhere --target ./somewhere/else 

And it should do some operations with those modules in somewhere and save it in target.

The problem is: If i have:

* - somewhere
*   | - index.js
*
*somewhere else

Index.js:

import { coolFunction } from 'cool-library';

export default coolFunction({some: object, generated: dynamically })

While doing require('./somewhere/index.js'), there is an exception: It cannot find the module in the specified path. This is because when executing __dirname, the path that appears there is the path where the bin is stored, instead of the one where it is executed.

How could I require index.js in a dynamic way? I tried with SystemJS, also with eval, also with dynamic-import-support.

I just want to be able to execute the index.js export default.

Any suggestion or solution is totally welcome! Thanks in advance


Solution

  • Found a solution based on ESLint's library. The have a util function that helps to import the configuration files on the flight from the current workspace instead of using __dirname.

    For the problems that people may find after requiring successfully, like ES6 imports or any other feature not supported by your node version, you could use babel-register to build your modules on the flight instead of pre-building them.