tleunen / babel-plugin-module-resolver

Custom module resolver plugin for Babel
MIT License
3.45k stars 204 forks source link

Alias with array of paths #443

Open JacobDel opened 1 year ago

JacobDel commented 1 year ago

In https://github.com/tleunen/babel-plugin-module-resolver/issues/261 it was discussed there could be two paths defined for one alias (if one path fails, there other could be used). Is it possible that this implementation is broken? https://github.com/tleunen/babel-plugin-module-resolver/pull/376

used versions:

"babel-plugin-module-resolver": "^5.0.0",
"react-native": "0.70.6",

This does not work for me (babel.config.js):

module.exports = {
  presets: ['module:metro-react-native-babel-preset', '@babel/preset-react'],
  env: {
    production: {
      plugins: ['react-native-paper/babel'],
    },
  },
  plugins: [
    [
      'module-resolver',
      {
        root: [
          './src',
        ],
        alias: {
          //'@brand': './src/Apps/brands/default',
          '@brand': ['./src/Apps/brands/example','./src/Apps/brands/default'],
        },
        extentions: ['.js', '.jsx', '.ts', '.tsx'],
      },
    ],
  ],
};

This does work (difference is the path after '@brand' alias):

module.exports = {
  presets: ['module:metro-react-native-babel-preset', '@babel/preset-react'],
  env: {
    production: {
      plugins: ['react-native-paper/babel'],
    },
  },
  plugins: [
    [
      'module-resolver',
      {
        root: [
          './src',
        ],
        alias: {
          '@brand': './src/Apps/brands/default',
          //'@brand': ['./src/Apps/brands/example','./src/Apps/brands/default'],
        },
        extentions: ['.js', '.jsx', '.ts', '.tsx'],
      },
    ],
  ],
};
rvasseur31 commented 1 year ago

I had the same problem this morning, it was because I forget to add the extensions property. Is your file is like somefile.ios.ts, in that case, you should add put this in your extensions property : ["android.tsx", "ios.tsx", ".tsx", "android.ts", "ios.ts", ".ts", ".json"]

He is my full babel.config.js (I use expo and ts) :

const whiteLabel = process.env.WHITE_LABEL;
const brandPath = `./src/brands/${whiteLabel}`;

function generateAlias(name) {
  return [`${brandPath}/${name}`, `./src/${name}`];
}

module.exports = function (api) {
  api.cache(true);
  return {
    presets: ["babel-preset-expo"],
    plugins: [
      [
        "module-resolver",
        {
          root: ["."],
          extensions: ["android.tsx", "ios.tsx", ".tsx", "android.ts", "ios.ts", ".ts", ".json"],
          alias: {
            components: generateAlias("components"),
          },
        },
      ],
    ],
  };
};