개발/환경 설정
[NPM] npm scripts를 현재 디렉토리 기준으로 실행하는 방법
degurii
2021. 5. 20. 02:21
728x90
가끔 상위 폴더에 package.json 하나를 두고 하위 폴더 파일을 기준으로 동일한 npm script를 실행해야 하는 경우가 있습니다.
예를 들면 간단한 프로젝트들을 여러 개 모아놨다던가, 책 예제들을 많이 짜 놓은 경우 등이 있겠죠?
사실 폴더마다 package.json을 작성하는 게 베스트지만 사람마다 귀찮음 포인트는 다르니까요...
폴더 구조가 다음과 같다고 합시다.
Directory
├─ package.json
├─ SubDirectory1
│ ├─ index.html
│ └─ index.js
├─ SubDirectory2
│ ├─ index.html
│ └─ index.js
├─ SubDirectory3
│ ├─ index.html
│ └─ index.js
├─ SubDirectory4
│ ├─ index.html
│ └─ index.js
└─ SubDirectory5
├─ index.html
└─ index.js
이런 경우 스크립트를 다음처럼 작성합니다.
"scripts": {
"start": "명령어 $INIT_CWD/index.js",
},
그 후 실행할 디렉토리로 들어가서 "npm start"를 해주면 잘 돌아가는 걸 볼 수 있습니다.
다만 위 스크립트는 *nix-like 플랫폼, 즉, 리눅스, 맥 등에서만 작동합니다.
윈도우에서는 $INIT_CWD 대신 %INIT_CWD%를 사용해주면 된다고 합니다. 테스트는 해보지 않았습니다. 혹시 해보신 분이 있으면 후기 부탁드립니다.
참고 링크
How can NPM scripts use my current working directory (when in nested subfolder)
It's good that I can run NPM scripts not only from the project root but also from the subfolders. However, with constraint that it can't tell my current working path ($PWD). Let's say there's a co...
stackoverflow.com
728x90