React에서 동적으로 Library 추가하기

@ZungTa · 2021-05-27 목요일 · 1 min read

Dom에 접근할 수 있을 때 (Mounted) script Element를 만들어서 추가해주면 된다.

코드는 아래와 같다.

useEffect(() => {
  const axiosUrl = "https://unpkg.com/axios/dist/axios.min.js"
  const scripts = document.getElementsByTagName("script")
  for (const script of scripts) {
    if (script.src.includes(axiosUrl)) {
      return
    }
  }

  const axiosScript = document.createElement("script")
  axiosScript.src = axiosUrl
  axiosScript.async = true
  axiosScript.defer = true
  window.document.body.appendChild(axiosScript)
  axiosScript.onload = () => {
    axios
      .get("https://jsonplaceholder.typicode.com/todos/1")
      .then((res: any) => {
        console.log("axios res? ", res)
      })
  }
})

TypeScript에서 사용하려면 d.ts 에서 선언을 잘 해줘서 쓰면 될 것 같다.

@ZungTa
I'm a backend developer
© ZungTa Devlog, Built with Gatsby