简体   繁体   中英

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

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?

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'

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