javascript - 如何在 react-native 项目中启用 jsconfig.json

标签 javascript react-native

我正在设置一个新的 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/*"]
    }
  }
}

包.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

最佳答案

您应该使用 babel-plugin-module-resolver .
babel.config.js 的示例配置:

module.exports = {
  ...other config

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

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

关于javascript - 如何在 react-native 项目中启用 jsconfig.json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57039306/

相关文章:

javascript - 使用 Node 和 FS 制作我自己的 "database"

javascript - 如何使用 angularjs、Django、Django Rest 框架更新模型

javascript - Chrome 扩展程序 : can't get value from storage with one click

javascript - 在执行渲染方法之前数据不可用 - React Native

JavaScript 未捕获类型错误 : Object has no method

javascript - 将文件转换为数组并使用数据列表和选项标签添加数组元素以用于自动完成文本框

reactjs - 为什么 npm install react-native 不起作用?

react-native - 使用 React Native 开发视频编辑器应用程序。是好是坏?

javascript - React Native 组件未在 map() 迭代器内渲染

javascript - 将应用程序更新到新代码库后,AsyncStorage 是否仍然存在?