0

我是 react-native 的新手,我正在尝试帮助一个项目。我首先重构代码以获得更好的文件结构。我实现了桶并添加了路径别名(模块解析器)。在 vscode 中一切正常,但是当我在 android 上运行时,它给了我这个错误:

TypeError:_app.default.objects 不是函数。{...} _app.default.objects 未定义。

这是我的 tsconfig:

"baseUrl": ".",
    "paths": {
      "@assets/*": ["./app/assets/*"],
      "@components/*": ["./app/components/*"],
      "@components": ["./app/components"],
      "@containers/*": ["./app/containers/*"],
      "@db": ["./app/db"],
      "@db/*": ["./app/db/*"],
      "@languages/*": ["./app/languages/*"],
      "@navigation/*": ["./app/navigation/*"],
      "@styles/*": ["./app/styles/*"],
      "@services": ["./app/services"],
      "@services/*": ["./app/services/*"],
      "@utils": ["./app/utils"],
      "@utils/*": ["./app/utils/*"],
    }

还有我的 babel-config:

  plugins: [
    [
      'module-resolver',
      {
        root: ['./app'],
        extensions: ['.ios.js', '.android.js', '.js', '.json', '.ts', '.tsx'],
        alias: {
          '@languages': './app/languages',
          '@db': './app/db',
          '@styles': './app/styles',
          '@services': './app/services',
          '@utils': './app/utils',
          '@assets': './app/assets',
          '@navigation': './app/navigation',
          '@components': './app/components',
          '@containers': './app/containers',
        },
      },
    ],
  ]

每次我使用数据库时都会引发错误:这是我的导入:

import { Song } from '@db'
import { GlobalSettings } from "@db/GlobalSettings";

如果我使用类似的东西:

const [songs, setSongs] = useState(Song.getAll())

但它与 db 目录中的其他所有内容相同。

谢谢!

4

1 回答 1

0

经过长时间的调试,发现是我的配置文件babel.config.js(或者tsconfig.json,我不知道)有问题。

这对我有用:
tsconfig.json

{
  "compilerOptions": {
    ...,
    "baseUrl": "./app/",
    "paths": {
      "@assets/*": ["assets/*"],
      "@components/*": ["components/*"],
      "@components": ["components"],
      "@containers/*": ["containers/*"],
      "@containers": ["containers"],
      "@db/*": ["db/*"],
      "@db": ["db"],
      "@languages/*": ["languages/*"],
      "@languages": ["languages"],
      "@navigation/*": ["navigation/*"],
      "@navigation": ["navigation"],
      "@styles/*": ["styles/*"],
      "@styles": ["styles"],
      "@services/*": ["services/*"],
      "@services": ["services"],
      "@utils/*": ["utils/*"],
      "@utils": ["utils"],
    },
   ...
  },
...
}

babel.config.js

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      'module-resolver',
      {
        root: ['./app'],
        alias: {
          '@languages': './app/languages',
          '@db': './app/db',
          '@styles': './app/styles',
          '@services': './app/services',
          '@utils': './app/utils',
          '@assets': './app/assets',
          '@navigation': './app/navigation',
          '@components': './app/components',
          '@containers': './app/containers',
        },
      },
    ],
  ],
};
于 2021-01-12T11:05:59.140 回答