在导入 three.js 时遇到问题

我使用 node.js 带的 npm 在项目文件夹下载好了 three.js 的文件,然后按照 three.js 的文档,在 html 文件中的 js 代码块中写

import * as THREE from 'three';
import {OrbitControls} from '/node_modules/three/examples/jsm/controls/OrbitControls.js';

启用 VS code 的 live sever 之后,在浏览器控制台看到报错:
Uncaught TypeError: Failed to resolve module specifier “three”. Relative references must start with either “/”, “./”, or “…/”.
然后我试着把 import * as THREE from 'three'; 改成相对路径,也还是不行。
script tag 已经写了 type="module"

问题出在哪里呢?十分感谢

提供一下文件目录结构,你是npm 安装? 还是前端cdn 引入?

目录结构:
│ learn.html
│ package-lock.json
│ package.json

├─image
│ doge.jpg
│ floor.png

└─node_modules
└─three
│ LICENSE
│ package.json
│ README.md

├─build
│ three.cjs
│ three.js
│ three.min.js
│ three.module.js

├─examples
│ └─jsm
│ ├─controls
│ │ OrbitControls.js

用的是 npm 安装,另外我也试了官网提供的 cdn 引用方法,也不行:

import * as THREE from 'https://cdn.skypack.dev/three@0.143.0';
import { OrbitControls } from 'https://cdn.skypack.dev/three@0.143.0/examples/jsm/controls/OrbitControls.js';

这个方法是错误的吗?

你的代码是放到 learn.html 文件里?

是的,这样:

<script type="module">
        import * as THREE from 'node_modules/three/build/three.js';
        import { OrbitControls } from 'node_modules/three/examples/jsm/controls/OrbitControls.js';
        blabla
</script>

代码块在 <body> 里面

你先参考这个项目吧。

nodejs 的下的 模块导入导出标准 与 前端(html)不一样。

1 Like