TypeScript 기반 React Native 앱에서 가져오기에 대한 절대 경로를 구성하려면 어떻게 해야 합니까?
TypeScript 기반 React Native 앱에서 '....................' 스타일의 상대 가져오기를 피하기 위해 앱 대신 절대 가져오기를 사용할 수 있도록 구성하려고 합니다.
구성이 Jest 장치 테스트도 지원하는 것이 중요합니다.
나는 다음을 사용하여 앱을 만들었다.
React Native 버전: 0.60.5
이를 위해 필요한 정확한 구성은 무엇입니까?
요약:.
npm 패키지는 물론 및 에 일부 구성이 필요합니다.
단계별:
npm 또는 yarn을 사용하여 설치합니다.
npm i babel-plugin-module-resolver --save-dev # Or (If you're using yarn): yarn add --dev babel-plugin-module-resolver
: 에 추가
: 다음 값으로 명명된 키를 추가합니다.
[
[
'module-resolver',
{
extensions: [
'.js',
'.jsx',
'.ts',
'.tsx',
'.android.js',
'.android.tsx',
'.ios.js',
'.ios.tsx'
],
root: ['.']
}
]
]
전체 구성:
:
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"isolatedModules": true,
"jsx": "react",
"lib": ["es6"],
"moduleResolution": "node",
"noEmit": true,
"strict": true,
"target": "esnext",
"baseUrl": "."
},
"exclude": ["node_modules", "babel.config.js", "metro.config.js", "jest.config.js"]
}
:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
extensions: [
'.js',
'.jsx',
'.ts',
'.tsx',
'.android.js',
'.android.tsx',
'.ios.js',
'.ios.tsx'
],
root: ['.']
}
]
]
};
이것은 React Native 버전 0.60.5에서 를 사용하여 만든 깨끗하고 새로운 프로젝트를 위한 것입니다.
필요
// Meh
import config from '../../../../../../../config';
// Awesome!
import config from '@cuteapp/config';
방법
- 이 바벨 플러그인 패키지 추가
yarn add --dev babel-plugin-module-resolver
- 나의
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
require.resolve('babel-plugin-module-resolver'),
{
cwd: 'babelrc',
extensions: ['.ts', '.tsx', '.js', '.ios.js', '.android.js'],
alias: {
'@cuteapp': './app'
}
}
],
'jest-hoist'
]
};
- 나의
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"isolatedModules": true,
"jsx": "react",
"lib": ["es2015", "es2015.promise", "es2016.array.include", "dom"],
"strict": true,
"moduleResolution": "node",
"baseUrl": "./",
"paths": {
"@cuteapp/*": ["app/*/index", "app/*"]
},
"noEmit": true,
"resolveJsonModule": true,
"target": "esnext",
"types": ["jest"]
},
"exclude": ["node_modules", "babel.config.js", "metro.config.js"]
}
- IDE를 다시 시작합니다.
- 바로 그겁니다.
TypeScript를 사용하고 절대 경로 별칭과 함께 가져오기를 사용하려는 모든 사용자에게 적합합니다.
모든 코드 폴더가 의 내부에 있다고 가정합니다.
안쪽의 객체에 삽입합니다.
이제 가져오기에서 절대 경로를 사용할 수 있습니다.
간단한 단계를 사용하여 해결할 수 있습니다.
: react-app-rewired를 에 추가합니다. 또는
: 설치 후 기본 응답을 변경할 수 있습니다.JS 스크립트 대상:
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-app-rewired eject"
}
: 루트 경로에 다음과 같은 내용을 포함하는 새 파일을 만듭니다.
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"services/*": ["./src/shared/services/*"],
"interfaces/*": ["./src/shared/interfaces/*"]
}
}
}
: 사용하려는 경로를 선택할 수 있습니다. 예를 들어, 내부에서 키를 변경하는 것만으로 가능합니다.
값에도 동일하게 적용됩니다. 여기서 상대 경로를 사용합니다.
: 방금 만든 을(를) 확장하기 전에 에 추가합니다. 이렇게요.
{
"extends": "./tsconfig.paths.json",
...//rest of file infos compilerOptions, include... whatever
}
: 별칭 및 상대 경로를 추가하여 새 파일을 만듭니다.
const path = require('path');
module.exports = function override(config) {
config.resolve = {
...config.resolve,
alias: {
...config.alias,
'services': path.resolve(__dirname, 'src/shared/services'),
'interfaces': path.resolve(__dirname, 'src/shared/interfaces')
},
};
return config;
};
: 을(를) 사용하는 경우 파일을 저장하고 그 안에 추가해야 합니다. IDE 또는 텍스트 편집기를 다시 시작합니다(VCode).
이건. 이제 그냥 뛰거나.
새로 만든 React Native + Typescript 프로젝트에서는 다른 모든 답변이 작동하지 않았습니다.
그리고 를 모두 설정하는 것이 효과적이었습니다.
{
"baseUrl": ".",
"paths": {
"NAME_IN_PACKAGE_JSON/*": ["./*"]
}
}
NAME_IN_PACKE_JSON을 의 이름 필드로 바꿉니다. 예를 들어, 이름 필드가 다음과 같은 작업을 수행할 수 있습니다.
import HomeScreen from "myapp/screens/HomeScreen";
바벨 플러그인을 사용하지 않으려는 경우
- 다음을 사용하여 폴더 안에 새 파일을 만듭니다. (원하는 것으로 바꾸면 될 수도 있습니다.)
{
"name": "myapp"
}
- tsconfig.json 파일을 업데이트합니다.
{
"compilerOptions": {
...
"baseUrl": "./",
"paths": {
"myapp/*": ["src/*"]
}
...
}
}
- .tsx 파일에서
import { MyThing } from 'myapp/MyThing';
프로젝트 루트에 "src" 파일이 있는 경우 패키지를 추가하기만 하면 됩니다.json 파일링하고 거기에 써라. 그러면 "src/..."라는 이름의 모든 가져오기가 올바르게 해결됩니다.
나는 이 해결책을 찾았다.
2022 업데이트
1. 폴더에 를 만듭니다.그리고 더 넣어라.
2.이렇게 파일을 업데이트하세요.
{
"compilerOptions": {
...
"baseUrl": "./",
"paths": {
"src/*": ["src/*"]
}
...
}
}
3. 아이디어를 다시 시작하세요.
이제 이렇게 수입할 수 있습니다.
import MyComponent from 'src/components/MyComponent';
'개발하자' 카테고리의 다른 글
파일 변수가 있는 테라폼을 사용하여 user_data를 ec2 인스턴스에 추가합니다. (0) | 2022.11.08 |
---|---|
빠른 API - Axios로 파일 업로드 - 잘못된 요청 (0) | 2022.11.07 |
Showing line numbers in IPython/Jupyter Notebooks (0) | 2022.11.06 |
파이썬에서 잘못된 경로 문자를 제거하는 방법은 무엇입니까? (0) | 2022.11.06 |
미래의 인스턴스 <String?문자열 데이터 플러터/파이어베이스 대신 >' (0) | 2022.11.04 |