如何在React Native项目中启用jsconfig.json

8
我正在设置一个新的react-native项目,并希望通过在项目根目录添加jsconfig.json文件来配置应用程序以支持使用绝对路径导入模块。但是应用程序无法解析这些模块。 我需要进行其他设置吗? 我已经使用react-native-cli 2.0.1创建了一个新的React-Native项目,并尝试像这样从App.js中导入MyButton:`import MyButton from '~/components/MyButton';`
|-- android
|-- ios
|-- node_modules
|-- src
    |-- components
        |-- MyButton.js
    |-- App.js
|-- .eslintrc.js
|-- .flowconfig
|-- .watchmanconfig
|-- app.json
|-- babel.config.json
|-- index.js
|-- jsconfig.json
|-- metro.config.js
|-- package.json

jsconfig.json:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "~/*": ["src/*"]
    }
  }
}

package.json

{
  "name": "TestApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "react": "16.8.6",
    "react-native": "0.60.3"
  },
  "devDependencies": {
    "@babel/core": "^7.5.4",
    "@babel/runtime": "^7.5.4",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.8.0",
    "eslint": "^6.0.1",
    "jest": "^24.8.0",
    "metro-react-native-babel-preset": "^0.55.0",
    "react-test-renderer": "16.8.6"
  },
  "jest": {
    "preset": "react-native"
  }
}

我希望应用程序可以解决这个模块,但是出现了错误:

`Error: Unable to resolve module `~/components/MyButton` from `/TestApp/src/App.js`: Module `~/components/MyButton` does not exist in the Haste module map
2个回答

16

你应该使用 babel-plugin-module-resolver

babel.config.js的示例配置:

module.exports = {
  ...other config

  plugins: [
    ['module-resolver', {
      root: [
        './src',
      ],
      "alias": {
        "~": "./src",
      }
    }],
  ],
};

React Native 默认不支持从 jsconfig.json 解析模块。


谢谢您的评论。我尝试了您的配置,但遇到了一个新问题。我将根目录设置为“.”,因为我的带有应用程序注册表的index.js不在src文件夹中。尽管如此,我仍然收到了“应用程序未注册”的错误。您有什么想法是我的错误吗? - Fabian Ullmann
1
没有问题,它可以运行了。感谢您的帮助! - Fabian Ullmann

-1

另一种方法:

  1. 在src文件夹内创建一个名为package.json的文件。
  2. 填写以下代码

    { "name": "src" }

  3. 上述步骤使您能够使用绝对地址。

例如:import MyButton from 'components/MyButton.js';


我没有使用src作为基础,是否可以像这样使用它:import {...} from 'src/components' - Hossein Alipour
@hosseinalipour 请查看此链接:https://medium.com/better-programming/using-absolute-paths-in-react-native-3be369244fb1 - Mohammed Ashfaq

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接