简体   繁体   English

Babel - 如何在根目录之外设置别名?

[英]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:我想设置一个别名,以便app.ts可以简单地调用:

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 Go 到“域”文件夹并添加一个新文件 package.json,内容如下

{
  "name": "domain"
}

Now you import like this现在你像这样导入

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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