简体   繁体   中英

How to use root option in babel-plugin-module-resolver?

I'm trying to use babel-plugin-module-resolver in a react-native app. When I use plugin config like this in babel.config.js it works perfectly.

plugins: [
    [
      'module-resolver',
      {
        extensions: ['.ios.js', '.android.js', '.js', '.json'],
        alias: {
          utils: './src/utils',
        },
      },
    ],
  ],

But the problem is that I have to write ./src in every alias path. So I tried to use root option. Here's the code I tried

plugins: [
    [
      'module-resolver',
      {
        root: './src', // I also tried ['./src']
        extensions: ['.ios.js', '.android.js', '.js', '.json'],
        alias: {
          utils: 'utils', // already tried '/utils' and './utils'
        },
      },
    ],
  ],

But that didn't worked for me and I get this error:

error: Error: Unable to resolve module '../../../utils/Themes' from 'src/components/shared/Container.js': 

So what's the correct way to use root option?

Well, I found a solution that doesn't really fix the problem but makes it works.

I'm using typescript, and babel to compile it.

My files structure is something like this:

|-dist
|-src
  |-db
     |-connect
        |-index.ts
  |-index.ts
|-.babelrc
|-etc...

When babel compiles my code, the import of db/connect in src/index.ts , go from this:

import ... from "db/connect"

to this:

var _connect = require("../db/connect");

and should be like this:

var _connect = require("./db/connect");

How you can see, babel backs one folder, and no matter what I try, this still missing the require path.

So, to resolve this, I simply add /dist to the paths in .babelrc

before:

[
   "module-resolver",
      {
         "root": ["./"], # or ["src"] or "src" or ["./src"] or "./src" or any way you can imagine
         "alias": {
            "db": "./db",
         }
      }
   }
]

after:

[
   "module-resolver",
      {
         "alias": {
            "db": "./dist/db",
         }
      }
   }
]

And as you said, the root doesn't affect the require path, so I just removed it.

This doesn't fix the problem, but makes it work.

Hope it helps, good luck! :)

检查文件 bable.config.js 并删除插件模块解析器,root 对我有帮助

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM