【问题标题】:Babel - how to set aliases to outside of the root directory?Babel - 如何在根目录之外设置别名?
【发布时间】:2021-10-18 13:56:29
【问题描述】:

我有一个 monorepo:

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

我想设置一个别名,以便app.ts 可以简单地调用:

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

而不是

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

我试过这样做:

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')
          }
        }
      ]
    ]
  }
}

但不幸的是,它不起作用。 它抛出:

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)

如何从主目录之外导入内容?

【问题讨论】:

    标签: javascript typescript babeljs babel-plugin-module-resolver


    【解决方案1】:

    转到“域”文件夹并添加一个包含以下内容的新文件 package.json

    {
      "name": "domain"
    }
    

    现在你像这样导入

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

    【讨论】:

      猜你喜欢
      • 2017-11-21
      • 2021-12-21
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多