Babel - how to set aliases to outside of the root directory?

495 views Asked by At

I have a monorepo:

domain/
  entities/
    account.ts
  ...
mobile/
    src/
      app.ts
  node_modules/
  package.json
  babel.config.js

I want to set an alias so that app.ts can simply call:

import { Account } from 'domain/entities/account'

instead of

import { Account } from '../../../domain/entities/account'

I tried doing it like so:

const path = require('path')

module.exports = (api) => {
  api.cache(true)

  return {
    presets: ['module:metro-react-native-babel-preset'],
    plugins: [
      ['module:react-native-dotenv', {
        moduleName: 'react-native-dotenv'
      }],
      [
        'module-resolver',
        {
          extensions: [
            '.js',
            '.jsx',
            '.ts',
            '.tsx'
          ],
          alias: {
            domain: path.resolve(__dirname, '../domain')
          }
        }
      ]
    ]
  }
}

But it doesn't work, unfortunately. It throws:

Error: Unable to resolve module /home/kibe/work/iros-customer-frontend/domain/entities/account from ...

None of these files exist:
  * ../domain/entities/account(.js|.jsx|.ts|.tsx)

How can I import stuff from outside the main directory?

1

There are 1 answers

0
Xhirazi On

Go to "domain" Folder and add a new file package.json with following content

{
  "name": "domain"
}

Now you import like this

import { Account } from 'domain/entities/account'