티스토리 뷰

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%를 사용해주면 된다고 합니다. 테스트는 해보지 않았습니다. 혹시 해보신 분이 있으면 후기 부탁드립니다.

 

 

참고 링크

https://stackoverflow.com/questions/46205456/how-can-npm-scripts-use-my-current-working-directory-when-in-nested-subfolder

 

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

'개발 > 환경 설정' 카테고리의 다른 글

Webpack으로 React.js 빌드하기  (2) 2020.02.11
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함