'How to load Javascript with imported modules?
I am trying to import modules from tensorflowjs, and below is my code. test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>
<script type="module" src="./test.js"></script>
</body>
</html>
test.js
import * as tf from "./node_modules/@tensorflow/tfjs";
import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter";
const MODEL_URL = './model.json';
const model = await loadGraphModel(MODEL_URL);
const cat = document.getElementById('cat');
model.execute(tf.browser.fromPixels(cat));
Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser:
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
Solution 1:[1]
You can use the following python script to serve your files:
serve.py
import http.server
import socketserver
import sys
PORT = 8000
if len(sys.argv) > 1:
PORT = int(sys.argv[1])
class HttpRequestHandler(http.server.SimpleHTTPRequestHandler):
extensions_map = {
# '': 'application/octet-stream',
'': 'text/html',
'.manifest': 'text/cache-manifest',
'.html': 'text/html',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.svg': 'image/svg+xml',
'.css': 'text/css',
'.js':'application/x-javascript',
'.wasm': 'application/wasm',
'.json': 'application/json',
'.xml': 'application/xml',
}
httpd = socketserver.TCPServer(("localhost", PORT), HttpRequestHandler)
try:
print(f"serving at http://localhost:{PORT}")
httpd.serve_forever()
except KeyboardInterrupt:
pass
then:
python ./serve.py 8000
By default, http.server does not take care of mime types. The above scripts indicate which mime type to use in the response header depending on the extension of the file.
Solution 2:[2]
If you use Node.js, you can use the http-server package to serve your files.
Install
npm install --global http-server
Use
http-server
Or alternatively, use: npx http-server
See the documentation for more details and options
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mathieu CAROFF |
| Solution 2 | Mathieu CAROFF |
