babel-plugin-module-resolver: [Babel7] Does not resolve module for monorepo with babel-node

Hi there,

I have a monorepo designed like this:

- packages
-- package-1
-- package-2
babel.config.js

In packages/package-2 I have a script defined in package.json like this:

"dev": "babel-node --config-file ../../babel.config.js ./index.js",

The babel config for module-resolver is :

 const plugins = [
    [
      "module-resolver",
      {
        cwd: "packagejson",
        root: "./",
        alias: {
          "@package1": "./packages/package-1"
        }
      }
    ]
  ];

The babel config is loaded, but can’t resolve the module './packages/package-1' :

Error: Cannot find module './packages/package-1'
    at Function.Module._resolveFilename (module.js:548:15)
    at Function.Module._load (module.js:475:25)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> ([...]/packages/package-2/index.js:1:1)
    at Module._compile (module.js:653:30)
    at Module._compile ([...]/node_modules/pirates/lib/index.js:83:24)
    at Module._extensions..js (module.js:664:10)
    at Object.newLoader [as .js] ([...]/node_modules/pirates/lib/index.js:88:7)
    at Module.load (module.js:566:32)

Thanks a lot !

EDIT: workaround for me : using yarn workspaces https://yarnpkg.com/lang/en/docs/workspaces/#toc-how-to-use-it

About this issue

  • Original URL
  • State: open
  • Created 6 years ago
  • Reactions: 4
  • Comments: 16

Commits related to this issue

Most upvoted comments

That’s because babel does not build anything outside the current cwd. You’d need to override the ignore option to only include node_modules. This is how I do this, albeit with babel/register:

require('@babel/register')({
  // Find babel.config.js up the folder structure.
  rootMode: 'upward',

  // Since babel ignores all files outside the cwd, it does not compile sibling packages
  // So rewrite the ignore list to only include node_modules
  ignore: ['node_modules'],
});

@snaerth

I had the same problem as you. I solved it by creating a specific babel.config.js for each package and extending it to the root babel.config.js.

packages
- package-1
-- utils
-- components
-- babel.config.js
- package-2
-- src
-- babel.config.js
babel.config.js

For each babel.config, I have this configuration:

module.exports = {
  extends: './../../babel.config.js',
  plugins: [
    [
      'module-resolver',
      {
        alias: {
          '@utils': './utils',
          '@components': './components',
        },
      },
    ],
  ],
};