简体   繁体   中英

Receiving Javascript error "Uncaught SyntaxError: cannot use import statement outside a module" when trying to import. Solution found

Diving into the specifics, I am trying to import code from a JS file called GLTFLoader for Three.js. The goal is to parse a.GLB file and render a Teapot.

HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>
        Three.js #1
    </title>
    <style>
        body{margin: 0;}
    </style>
</head>
<body>
    <script src="js/three.js"></script> // A dependecy.
    <script src="js/cube.js"></script> // The main script.
    <script src="js/loaders/GLTFLoader.mjs"></script> // The module I am trying to import code
</body>                                               // from.
</html>

The Import code and code requiring the import. Can upload full code if need be.

import {GTLFLoader} from "js/loaders/GLTFLoader.mjs"

// Create a mesh.
const loader = new GLTFLoader(); // Instantiate loader.
loader.load("assets/models/utahteapot.glb", function (gltf) { // Load the model.
scene.add(gltf.scene); // Add the loaded model to scene.
}, undefined, function (error) { // Return an error if there is one.
console.error(error);
});

I have tried using the "type="module"" tag within the script tag, I have tried uploading the Loader code straight from the url source, I have tried importing the code within the HTML file, and I even tried creating a local server to host these files. I wasn't doing that before, and I still am now. I have ran out of ideas; I can't find a solution. EDIT: Forgot to mention, the file GLTFLoader extension is.MJS because of an unrelated error I had along this error.

I found a solution. It wasn't how I typed or indexed the files, it was how I was serving them on my local server.

The MIME error was caused by the files always returning as an improper MIME type "plain/text" when I needed it to return as "application/x-javascript". The import error was caused by me not adding type="module" to my main.js file within the HTML file.

So, I scouted for a python script that created a LocalHost server that served the files properly. So that meant I can label the main.js file as a module, and import what I needed from other files.

Here is the script's git.

NOTE: You may have to change your localhost number. The set number is 8080, and I had to change mine to 8090 before my files actually updated. Keep that in mind if your files aren't updating or an error is returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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