프로그래밍/NodeJS

npm nodemodules import하기

Beginner:) 2023. 1. 30.
320x100

원래 웹 쪽이 아니라 고생 좀 했다.

 

nodemodule에서 "npm install bootstrap" 하여서 bootstrap nodemudle을 내려받았다.

 

목적은 icon을 외부에서 가져오는 게 아닌, 나의 로컬 서버에서 icon을 가져오기 위해서.

 

외부에서 가져와도 상관없지만 로컬에서 가져올 상황이 많을 것 같아서 포기 않고 방법을 찾아 구글링을 좀 많이 했다.

 

처음에는 static 폴더에 nodemodule 데이터를 복붙 해서 사용했는데, 낭비인 것 같아서 + 앞으로도 많이 쓰일 것 같아서 포기 않고 찾아 헤맸다. (express 환경이긴 한데 대부분 비슷한 방법일 듯)

 

결론은 static이 아닌 nodemodule의 데이터를 찾아오는 방법이다.

 


1. app js에서 nodemodule의 경로를 임의로 지정한다.

app.use('/bootstrap', express.static(__dirname+'/node_modules/bootstrap-icons/'))

 

이렇게 하면 html (나 같은 경우 jade)에서 href 같은 거로 static이 아닌 nodemodule 데이터를 불러올 수 있다.

 

jade를 몰라도 몇 번 보면 이해는 할 것이다. 

img.image(src="/bootstrap/icons/filetype-" + item.name.split(".").pop() + ".svg" onerror="this.onerror=null; this.src='/bootstrap/icons/files.svg'" width="100%" style="width:48px")

 

아래는 이해를 돕기 위한 bootstrap-icons의 구조.

사진에는 안 보이지만 bootstrap/icons 아래에 filetype-*으로 jpg, jpeg, svg, bmp 등 여러 가지 icon들이 있다. 

 

item.name은 백엔드에서 받아오는 데이터이다.

 

어쨌건 중요한 건 서버의 "node_modules/bootstrap-icons"를 "/bootstrap"이라는 url로 대체하였고, jade(html or 프론트앤드)에서 경로를 "bootstrap"으로 변환해서 사용한 것이 중요하다.

 

진짜 간단하게 한 줄 요약하자면 "node_modules/bootstrap-icons" 폴더를 "static" 폴더와 같이 사용한 것이다.

 

이전에는 static/image 파일에 넣어서 nodemodule과 중복해서 사용했는데, 이제는 중복 없이 이미지를 가져오고 있다.

img.image(src="/bootstrap/icons/filetype-" + item.name.split(".").pop() + ".svg" onerror="this.onerror=null; this.src='/bootstrap/icons/files.svg'" width="100%" style="width:48px")

 


사실 개인적인 서버에서는, 특히 접근이 잦지 않은 서버에서는 상관이야 없겠지만, 이게 정답에 가깝진 않을까...?

 

 

참고) 

https://www.youtube.com/watch?v=nDSpd6f8t_o

반응형

댓글