-
[Fast-API] Fast-API + TypeScript 환경구성Python 2024. 7. 30. 17:30
문제점 : 기존 app에서 이용하는 web-view를 단순 js코드가 아닌 ts코드를 이용할 필요성이 생김.
해결 : back-end로 사용하고있는 fast-api 서버에 일부 웹뷰를 ts코드로 구현.
현재 프로젝트 구성
project/ ├── templates/ │ ├── (html 파일들) ├── router/ │ ├── (..py) ├── static/ │ ├── audio/ │ │ └── (Audio 파일들) │ ├── css/ │ │ └── (css 파일들) │ ├── js/ │ │ └── (컴파일된 js 파일들) │ ├── ts/ │ │ └── (ts 파일들) └── .env └──main.py └──README.md └──requirements.txt └──...
ts폴더 밑에 package.json, tsconfig.json 등을 만들어줄 예정
cd project/static/ts npm init -y npm install typescript ts-node @types/node --save-dev
생성된 package.json 폴더 수정
//package.json { "name": "project-nm", "version": "1.0.0", "scripts": { "build": "tsc", "watch": "tsc -w" }, "devDependencies": { "typescript": "^5.5.4" } }
tsconfig.json파일 생성
// tsconfig.json { "compilerOptions": { "target": "es6", "module": "commonjs", "outDir": "../js", "rootDir": "./src", "strict": true, "esModuleInterop": true }, "include": ["src/**/*"] }
그리고 서버 기동시 자동으로 컴파일 하기 위해서 main.py 코드 수정
# TypeScript 컴파일 def compile_typescript(): ts_dir = os.path.join(os.getcwd(), "static", "ts") subprocess.run(["npm", "run", "build"], cwd=ts_dir, check=True, shell=True) # 서버 시작 시 TypeScript 컴파일 @app.on_event("startup") async def startup_event(): compile_typescript()
※ subprocess.run 옵션으로 cwd, shell값을 정해주지 않으면 오류가 나니 중의바람.
'Python' 카테고리의 다른 글
파이썬 **의미, 언패킹(unpacking) (0) 2024.08.02