2.threejs的引入方式

我们前面编写代码的时候,使用的是最传统的 script 标签的方式引入的,这种方式虽然简单,但是和我们现在流行的开发方式是不一样的,后续可能会带来很多麻烦,因此这里再谈谈其他引入方式。

使用 npm

这是目前比较流行的引入方式,首先需要安装 threejs:

npm i three

然后引入我们需要的模块

// 方式 1: 导入整个 three.js核心库
import * as THREE from 'three';
const scene = new THREE.Scene();


// 方式 2: 仅导入你所需要的部分
import { Scene } from 'three';
const scene = new Scene();

使用CDN同时也使用ES Module

如果我们想继续使用传统的CDN方式引入,而且还想和使用npm 方式那样,使用ES Module,那么我们可以这样做:

首先,从我们下载的 threejs 包下的 build/three.module.min.js 中引入需要的模块,我们这里移动了three.module.min.js 的路径,实际路基要根据自己的实际情况。

<!-- 1.这里需要添加  type="module" -->
<script type="module">
 // 2. 引入需要的模块
 import * as THREE from './three.module.min.js';
 const scene = new THREE.Scene();
</script>
Import Maps

除了上面的直接的方法,我们还可以使用 Import Maps 进行引入。Import Maps 是一种导入映射,它允许我们在一个单独的配置文件中定义模块标识符和对应的实际文件路径,然后在你的代码中使用这些模块标识符来导入模块,而不必使用相对路径或者基于包名的导入方式。这有助于减少导入语句中的复杂性,同时提供了更好的模块路径管理。

比如:我们原来引入一个文件是这样的:

<script type="module">
import * as THREE from './three.module.min.js';
</script>

如果我们使用 Import Maps 的话,可以提前为 路径 './three.module.min.js' 设置一个标识符。比如:

<script type="importmap">
       {
           "imports": {
               "three": "./three.module.min.js"
           }
       }
</script>

上面的代码,相当于为路径 ./three.module.min.js 设置了个别名 three,当我们想导入的时候,就可以这样写:

<script type="module">
 import * as THREE from 'three';
</script>
插件导入 (Addons)

在我们下载的threejs 包下的 examples/jsm/ 目录下,存放着很多自带的插件,我们导人的时候也可以通过配置 Import Maps 进行处理:

<!-- 将 three/addons/ 与 ./jsm/ 进行映射 -->
<script type="importmap">
       {
           "imports": {
               "three": "./three.module.min.js",
               "three/addons/": "./jsm/"
           }
       }
</script>
<script type="module">
 import * as THREE from 'three';
 // 使用的时候,遇到three/addons/,就会按照 ./jsm/ 去处理
 import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
</script>


独立的js模块

我们写的业务代码,也可以带入存放到一个独立的js文件中。比如我们单独创建一个 ./logic.js 文件。然后将我们的代码复制进去:

import * as THREE from 'three';
// 使用的时候,遇到three/addons/,就会按照 ./jsm/ 去处理
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'

后再页面中我们可以这样使用:

<script type="importmap">
       {
           "imports": {
               "three": "./three.module.min.js",
               "three/addons/": "./jsm/"
           }
       }
</script>
<!-- 直接引入我们刚创建的文件 -->
<script type="module" src="./logic.js"></script>


使用 Import Maps 配合独立js文件的好处是,咱们写的代码在将来使用npm配合构建工具的时候,不用改动就可以直接将其当成一个模块使用。

参考资料:https://threejs.org/docs/index.html#manual/zh/introduction/Installation





微信 遇到疑问可加微信进行反映