首页 > 解决方案 > 使用 npm 在 React Native 中使用范围导入

问题描述

我正在尝试改变在 React Native 中导入模块的方式。这样做的标准方法是这样的:

import HomeScreen from "../../screens/Home"

我也可以通过以下方式播种:

import HomeScreen from "@screens/Home"

为此,我尝试在屏幕文件夹中创建一个 package.json 文件并为其命名

{
   "name": "@screens"
}

但不工作。

更新:

我尝试使用 babel-plugin-module-resolver 并使用我的 .babelrc 和 .tsconfig 对其进行配置,但问题仍然存在

.babelrc

{
  "plugins": [
    [
      "module-resolver",
      {
        "root": ["./src"],
        "alias": {
          "test": "./test",
          "underscore": "lodash"
        }
      }
    ]
  ]
}

tsconfig.json

{
  "compilerOptions": {
    "allowJs": false,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "jsx": "react-native",
    "module": "es2015",
    "moduleResolution": "node",
    "outDir": "build",
    "rootDir": "src",
    "noImplicitAny": false,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "sourceMap": true,
    "target": "es2015",
    "lib": ["es2015", "es2017", "dom"],
    "skipLibCheck": true,
    "baseUrl": ".",
    "paths": {
      "*": ["src/*"],
      "test/*": ["test/*"],
      "underscore": ["lodash"]
    }
  },
  "exclude": ["node_modules"],
  "include": ["src"]
}

PS:我也在使用打字稿

标签: javascriptreactjstypescriptreact-nativeecmascript-6

解决方案


推荐阅读