简体   繁体   English

从 npm 导入 Three.js 时出错,安装在 JavaScript 文件中(不是 ZFC35FDC70D5FC69D2539883A82EZA 脚本)

[英]Error importing Three.js from npm install inside of JavaScript file (not html script)

I'm trying to import Three.js inside of my JavaScript file (not HTML script element), but I get an error "Uncaught SyntaxError: Cannot use import statement outside a module".我正在尝试在我的 JavaScript 文件(不是 HTML 脚本元素)中导入 Three.js,但我收到错误“未捕获的语法错误:无法在模块外使用导入语句” My Three.js code works if I put it in a Script element in HTML but I want to use a canvas element to display the code from JavaScript file instead.如果我将 Three.js 代码放在 HTML 的 Script 元素中,我的 Three.js 代码可以工作,但我想使用 canvasZ 元素来显示来自 Z6836155AF75CEFED70 文件的代码。

I've installed Three.js using NPM already and imported.我已经使用 NPM 安装并导入了 Three.js。 I also used a canvas element in my html which I queried for in my JavaScript.我还在我的 html 中使用了 canvas 元素,我在 JavaScript 中查询了该元素。

import * as THREE from 'three';

    let scene, camera, renderer, geo, orbs, controls;

    function init() {
        scene = new THREE.Scene();
        camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight);

        controls = new THREE.TrackballControls(camera);
        controls.addEventListener('change', render);
        let canvas = document.querySelector("canvas");

    renderer = new THREE.WebGLRenderer({
        alpha: true,
        canvas: canvas
    });

I've tried declaring a const and requiring, as well as adding "type="module" to the script and that didn't work either.我尝试过声明一个 const 并要求,以及在脚本中添加“type=”module”,但这也不起作用。

I'm new to Three and I'm not sure if this is best practice because I've seen it being used in script tags more often than in a separate JS file.我是 Three 的新手,我不确定这是否是最佳实践,因为我看到它在脚本标签中的使用频率高于在单独的 JS 文件中的使用频率。

Thank you!谢谢!

Resolved, I just found out it was because I installed the package incorrectly!解决了,我才发现是因为我安装错了package!

I included a downloaded three.js file in the directory from my previous attempt.我在之前尝试的目录中包含了一个下载的 three.js 文件。 That's why the installation didn't go through even though the terminal said successfully installed.这就是为什么即使终端说安装成功,安装也没有通过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM