简体   繁体   中英

Javascript module not importing

I've been having trouble getting javascript modules to work properly the last week and I've looked around as much as I can but I keep hitting dead ends about how to fix it.

I've got the site running through a python test server which does take into account MIME types:

import http.server
from http.server import HTTPServer, BaseHTTPRequestHandler
import socketserver

PORT = 8080

Handler = http.server.SimpleHTTPRequestHandler

Handler.extensions_map={
        '.manifest': 'text/cache-manifest',
    '.html': 'text/html',
        '.png': 'image/png',
    '.jpg': 'image/jpg',
    '.svg': 'image/svg+xml',
    '.css': 'text/css',
    '.js':  'application/x-javascript',
    '.module.js': 'module',
    '': 'application/octet-stream', # Default
    }

httpd = socketserver.TCPServer(("", PORT), Handler)

print("serving at port", PORT)
httpd.serve_forever()

This is the class I'm exporting from terrain_generation.module.js:

export class world {
  constructor() {
  }

  static GetCube(){
    var geometry = new THREE.BoxGeometry();
    var material = new THREE.MeshBasicMaterial({
      color: 0x00ff00
    });
    this.cube = new THREE.Mesh(geometry, material);
    return this.cube;
  }

  static HelloWorld(){
    return "Hello world!";
  }
}

This is how I'm linking the script to the HTML page:

<script type="module" src="./js/terrain_generation.module.js"></script>

I've confirmed that the file name used in the source tag is the same as the file name. This is how I'm importing it and where I'm running into issues:

import {world} from "./js/terrain_generation.module.js";

This is the error I'm getting:

The requested module './js/terrain_generation.module.js' does not provide an export named 'world'

Any help would be much appreciated.

Edit: Tried using a newer version of python, ran back into the problem of incorrect MIME types.

I played around with the javascript MIME types in the python server and found a solution.

I changed the MIME type for.js files to text/javascript and now it works. Since javascript files were being parsed with a MIME type of application/x-javascript I think it could not use the ES6 modules due to a type mismatch.

I don't know why it worked and I will have to research MIME types more before I can figure out what was happening, maybe being a more generic MIME type of javascript helped.

One way to fix this is:
In terrain_generation.module.js write export default class world instead of export class world . And just import it as import world from "./js/terrain_generation.module.js";

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