Three.js를 import를 할 때, 아래와 같이 three.js를 import를 하게 된다. 근데, 가끔 three.js의 js 파일을 import 할 때 아래의 해당 URL에 접속이 되지 않는 문제가 3월에 2번이 발생했다. 이게 또 언제 발생할 지 몰라서, three.js 공식 홈페이지에서 배포하는 파일을 다운로드하여 경로에 저장을 해서 가져다 쓰는 형태로 바꾸려고 한다.
<!-- 3d.js -->
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three/build/three.module.js",
"three/addons/": "https://unpkg.com/three/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// THREE를 전역 객체에 연결
window.THREE = THREE;
window.OrbitControls = OrbitControls;
</script>
문제 해결 방법
실질적으로, three.js를 사용할 때 현재 내가 사용하는 모듈은 three.module.js 파일과 카메라를 사용하기 위한 orbitControls.js를 사용해야 한다.
그래서, 이 2가지의 js 파일을 다운로드하여 경로에 저장을 하면 된다.
아래와 같이, three.module.js와 OrbitControls.js를 해당 경로에 넣고, import를 한 다음에, module script에 해당 라이브러리를 import하면 된다.
<!-- 3d.js -->
<script type="importmap">
{
"imports": {
"three": "../common/js/three.module.js",
"OrbitControlsImport": "../common/js/OrbitControls.js"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'OrbitControlsImport';
// THREE를 전역 객체에 연결
window.THREE = THREE;
window.OrbitControls = OrbitControls;
</script>
여기서, 이 2개의 js만 import를 수정해야 하는게 아니라, three.module.js 를 보면, three.core.js를 다시 import를 하기 때문에 three.core.js 파일도 함께 다운로드 및 경로를 수정해줘야 한다.

즉, three.module.js를 사용하기 위해서는 three.core.js도 같이 import를 해야 한다.
이렇게 하면, URL에 CORS가 걸리더라도 문제없이 사용할 수 있다.
최근댓글