gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:10:47 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com