Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: How to use ES6 modules?

I have a working Flask app that I'm trying to refactor to use ES6 imports. I don't need it to run on old browsers, and ES6 imports work in modern browsers without transpilation, right?

I'm just running this via Flask's built-in server at the moment. The production app is served via gevent instead, but I'm obviously not at that point with these changes yet.

Below is what I've tried so far. Where have I gone wrong?

views.py

@app.route('/home')
def serve_home():
    return render_template('home.html')

formatting.js

export function formatNumber(...) {
  ...
}

Attempt 1

home.html

<script type="text/javascript" src="/static/js/main.js"></script>

main.js

import {formatNumber} from "/static/js/formatting.js";

Error (main.js, line 1)

Uncaught SyntaxError: Unexpected token {

Attempt 2

  • Changed the script type to "module"

home.html

<script type="module" src="/static/js/main.js"></script>

Error (main.js, line 1)

Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking is enforced for module scripts per HTML spec.

Attempt 3

  • Changed the extension of each of the two Javascript files from "js" to "mjs"

home.html

<script type="module" src="/static/js/main.mjs"></script>

main.mjs

import {formatNumber} from "/static/js/formatting.mjs";

Error (main.mjs, line 1)

Failed to load module script: The server responded with a non-JavaScript MIME type of "application/octet-stream". Strict MIME type checking is enforced for module scripts per HTML spec.

like image 981
MarredCheese Avatar asked Jun 13 '19 19:06

MarredCheese


1 Answers

For those of you getting the error:

The server responded with a non-JavaScript MIME type [...]

...you'll want to confirm python is returning the expected mimetype of your JS files.

>>> import mimetypes
>>> mimetypes.guess_type("notExists.js")
('text/javascript', None)

For myself, using a Windows platform to host the web server from (eg. Flask's development server), I found I needed to update the registry to associate the file extension with text/javascript.

For example, in the registry editor:

  1. Under HKEY_CLASSES_ROOT, find .js (and .mjs if using that)
  2. Look at the value for "Content Type". It must say text/javascript, NOT text/plain, or application/octet-stream, etc.
like image 69
Ryan de Kleer Avatar answered Sep 28 '22 10:09

Ryan de Kleer