【问题标题】:How to enable jsconfig.json in react-native project如何在 react-native 项目中启用 jsconfig.json
【发布时间】:2019-07-15 11:59:36
【问题描述】:

我正在设置一个新的 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

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

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

    babel.config.js的配置示例:

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

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

    【讨论】:

    • 感谢您的评论。我已经尝试了您的配置并遇到了一个新问题。我已将 root 设置为“。”导致我的带有应用程序注册表的 index.js 不在 src 文件夹中。不管怎样,我得到了错误Application has not been registred。你知道我的错误是什么吗?
    • 不运行...感谢您的帮助!
    【解决方案2】:

    替代方式:

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

      { “名称”:“src” }

    3. 上述步骤使您可以使用绝对地址。

    例如。从 'components/MyButton.js' 导入 MyButton;

    【讨论】:

    • 我没有使用src作为基础,是否可以像import {...} from 'src/components'一样使用它?
    • @hosseinalipour 请通过这个link
    猜你喜欢
    • 1970-01-01
    • 2020-12-28
    • 2020-09-16
    • 2019-05-16
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多